text:
Output frequency from an SPI DAC (MCP4922) is lower than expected
I'm using a 2-channel, 12-bit DAC (MCP4922, datasheet) with an Arduino Uno, using the library written for it here. With the clock divider set to 2, I should have the SPI clock frequency at 8MHz. If each value sent to the DAC takes about 12 of these clock cycles, that leaves me with about 650kHz as my output frequency (when I'm sending a simple on-off signal like below), but the fastest I see is about 25kHz.

void loop() {   dac.output2(4095, 0);   dac.output2(0, 4095);  }

Am I misunderstanding how the transfer protocol works? How can I make this faster? I'd like to both understand why this is so slow, and also to get an output frequency of at least 50kHz.

Did you set the clock divider to 2, or to SPI_CLOCK_DIV2? 2) Did you setPortWrite(true)?

@EdgarBonet Yes to both, unfortunately.

Let's do some maths...

16MHz master clock / 2 = 8MHz SPI clock
2 transactions = 16 bits (not 12!)
8,000,000 / 16 = 500,000
2 transitions per cycle
2 channels
2 + 2 = 4
500,000 / 4 = 125,000Hz

So in a perfect world you could expect 125kHz from the DAC. However the world is far from perfect.
Let's look at what it's actually doing when you use output2():
void DAC_MCP49xx::output2(unsigned short data_A, unsigned short data_B) {
  this->_output(data_A, CHANNEL_A);
  this->_output(data_B, CHANNEL_B);

  // Update the output, if desired.
  // The reason this is only in the dual-output version is simple: it's mostly useless
  // for the single-output version, as it would make more sense to tie the \LDAC pin
  // to ground, or do it manually. However, there should be a single-call method
  // to update *both* channels in sync, which wouldn't be possible with multiple
  // separate DACs (for which there is latch()).
  if (automaticallyLatchDual) {
    this->latch();
  }
}

Assuming automaticallyLatchDual is false we can pretty much ignore that section. So it's calling _output() twice - once for each channel. And what does that do?
void DAC_MCP49xx::_output(unsigned short data, Channel chan) {
  // Truncate the unused bits to fit the 8/10/12 bits the DAC accepts
  if (this->bitwidth == 12)
    data &= 0xfff;
  else if (this->bitwidth == 10)
    data &= 0x3ff;
  else if (this->bitwidth == 8)
    data &= 0xff;

  // Drive chip select low
  if (this->port_write)
    PORTB &= 0xfb; // Clear PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, LOW);

  // bit 15: 0 for DAC A, 1 for DAC B. (Always 0 for MCP49x1.)
  // bit 14: buffer VREF?
  // bit 13: gain bit; 0 for 1x gain, 1 for 2x (thus we NOT the variable)
  // bit 12: shutdown bit. 1 for active operation
  // bits 11 through 0: data
  uint16_t out = (chan << 15) | (this->bufferVref << 14) | ((!this->gain2x) << 13) | (1 << 12) | (data << (12 - this->bitwidth));

  // Send the command and data bits
  SPI.transfer((out & 0xff00) >> 8);
  SPI.transfer(out & 0xff);

  // Return chip select to high
  if (this->port_write)
    PORTB |= (1 << 2); // set PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, HIGH);
}

That's quite a lot. All those boolean mathematics operations and decision making slows things down a lot. So does hopping from function to function (yes, the compiler will possibly try and inline some things).
Even the SPI.transfer() isn't that efficient with checks and while loops, etc.
To get anywhere near the kind of speed you are looking for you would need to use non-blocking SPI code so you can be transferring a byte out of the SPI port at the same time as getting the next byte ready to send. You don't need to wait for the current SPI transfer to finish (as the SPI library does), you just need to be sure that the previous one has finished before you start the next one.


text:
Power ON/OFF a car using Arduino with IR remote control
I'm trying somehow to power OFF the car when the song plays using Arduino using Infrared (IR) Remote.
I decided to play a song (SuperMario) using a Buzzer and when I press the Power ON button works fine and the song plays.
The problem is when I press Power OFF, I have to wait until the song ends to Power off the car.
I was thinking that maybe I need threads or something, but I'm not sure, or maybe there is a better way to fix this.
Here is a Demo program:
#include "IRremote.h"

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define powerLedRed    2
#define powerLedGreen  3
#define receiver       5
#define buzzer         7

void translateIR( void );
void powerON( void );;
void powerOFF( void );
void swap( int *x, int *y );
void playSuperMario( void );
void buzz( int targetPin, long frequency, long length );

int power           = 2;
int switchOFF       = 0;
int switchON        = 1;

int melody[] = {
  NOTE_E7, NOTE_E7, 0, NOTE_E7,  0, NOTE_C7, NOTE_E7, 0,
  NOTE_G7, 0, 0,  0,  NOTE_G6, 0, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6,  0, 0, NOTE_E6, 0, 0,
  NOTE_A6, 0, NOTE_B6,  0, NOTE_AS6, NOTE_A6, 0,
  NOTE_G6, NOTE_E7, NOTE_G7,  NOTE_A7, 0, NOTE_F7, NOTE_G7, 0,
  NOTE_E7, 0, NOTE_C7,  NOTE_D7, NOTE_B6, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6,  0, 0, NOTE_E6, 0, 0,
  NOTE_A6, 0, NOTE_B6,  0, NOTE_AS6, NOTE_A6, 0,
  NOTE_G6, NOTE_E7, NOTE_G7,  NOTE_A7, 0, NOTE_F7, NOTE_G7, 0,
  NOTE_E7, 0, NOTE_C7,  NOTE_D7, NOTE_B6, 0, 0
};

int tempo[] = {
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  9, 9, 9,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  9, 9, 9,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
};

int underworld_melody[] = {
  NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,  NOTE_AS3, NOTE_AS4, 0,  0,
  NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,  NOTE_AS3, NOTE_AS4, 0,  0,
  NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,  NOTE_DS3, NOTE_DS4, 0,  0,
  NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,  NOTE_DS3, NOTE_DS4, 0,  0,
  NOTE_DS4, NOTE_CS4, NOTE_D4, NOTE_CS4, NOTE_DS4, NOTE_DS4, NOTE_GS3,
  NOTE_G3, NOTE_CS4, NOTE_C4, NOTE_FS4, NOTE_F4, NOTE_E3, NOTE_AS4, NOTE_A4,
  NOTE_GS4, NOTE_DS4, NOTE_B3, NOTE_AS3, NOTE_A3, NOTE_GS3, 0, 0, 0
};

int underworld_tempo[] = {
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,
  6, 18, 18, 18,  6, 6,  6, 6,  6, 6,
  18, 18, 18, 18, 18, 18,  10, 10, 10,
  10, 10, 10, 3, 3, 3
};

IRrecv irrecv(receiver);
decode_results results;

void setup( void )
{
  pinMode(buzzer, OUTPUT);
  pinMode(powerLedGreen, OUTPUT);
  pinMode(powerLedRed,   OUTPUT);
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn();
}

void loop( void )
{
  if ( power == 2 ) {
    powerOFF();
  }

  if (irrecv.decode(&results)) {
    translateIR();
    irrecv.resume();
  }
}

void playSuperMario( void ) {
  Serial.println(" 'Mario Theme'");
  int size = sizeof(melody) / sizeof(int);
  for (int thisNote = 0; thisNote < size; thisNote++) {
    int noteDuration = 1000 / tempo[thisNote];
    buzz(buzzer, melody[thisNote], noteDuration);

    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    buzz(buzzer, 0, noteDuration);
  }
}

void buzz( int targetPin, long frequency, long length ) {
  digitalWrite(13, HIGH);
  long delayValue = 1000000 / frequency / 2; // calculate the delay value between transitions
  long numCycles = frequency * length / 1000; // calculate the number of cycles for proper timing

  for (long i = 0; i < numCycles; i++) { // for the calculated length of time...
    digitalWrite(targetPin, HIGH); // write the buzzer pin high to push out the diaphram
    delayMicroseconds(delayValue); // wait for the calculated delay value
    digitalWrite(targetPin, LOW); // write the buzzer pin low to pull back the diaphram
    delayMicroseconds(delayValue); // wait again or the calculated delay value
  }

  digitalWrite(13, LOW);
}

void translateIR( void ) {
  switch (results.value) {
    case 0xFF02FD:
      Serial.println(" -OK-");

      swap(&switchON, &switchOFF);

      if (switchON == 0 )
      {
        powerON();
        playSuperMario();
      }
      else
      {
        powerOFF();
      }
      break;
    default:
      Serial.println(" other button   ");
      power = 0;
  }
  //delay(500);
}

void powerOFF( void ) {
  digitalWrite(powerLedRed,   HIGH);
  digitalWrite(powerLedGreen, LOW);
  power = 0;
}

void powerON( void ) {
  digitalWrite(powerLedRed,   LOW);
  digitalWrite(powerLedGreen, HIGH);
}

void swap( int *x, int *y ) {
  if (*x != *y) {
    *x ^= *y;
    *y ^= *x;
    *x ^= *y;
  }
}

inside the translateIR function I have this:
void translateIR( void ) {
  switch (results.value) {
    case 0xFF02FD:
      Serial.println(" -OK-");

      swap(&switchON, &switchOFF);

      if (switchON == 0 )
      {
        powerON();
        playSuperMario();
      }
      else
      {
        powerOFF();
      }
      break;
    default:
      Serial.println(" other button   ");
      power = 0;
  }
  //delay(500);
}

Here is a VIDEO Demo.
How to fix this?

There are two ways you can accomplish this. FYI, my buzzer is connected to pin 11 which is a PWM pin on the Arduino UNO.

Get a DFPlayer mini which can play the song and all you do is press the stop function to stop the music just like in your code. (Recommended)
Use MelodyWithoutDelay(Okay, but it works just as well and is less expensive)

For this answer, I will explain the MelodyWithoutDelay method.
As you have heard before, the delay function is a terrible way to stall the Arduino.  This is because the Arduino can not be aware, or multitask, while it is staring at its own clock.  I dealt with the same issue when I tried to "multitask" my Arduino to play music while receiving commands via Bluetooth.
For this reason, I created code a bit similar to the ToneMelody example given by Arduino.  I called it MelodyWithoutDelay.  It's a pretty swag name :)
Anyway, all you have to do replace my melody[] and noteDuration[] code with your melody[] and tempo[] code. And you have to change lengthOfSong to the number of notes in your melody from start to finish.
You might have to include the pitches.h file from the toneMelody example code given by Arduino.
But the bare meat you should be looking at is the void melodyWithoutDelay().
Instead of creating the code applicable to you, I will create the most basic form, which is the one I show below.  I need to show the MelodyWithoutDelay example to some viewers out there for their own projects too!.
Just marinate your head in the code and it should give you a good understanding on how to attack your mission.
If you want to test my code, Upload it and all you have to do is type 'g' in the Serial monitor and you should be able to pause and play the song.
If you're wondering where I used the code check out my Instructable.
Good Luck!
Here is the code:
    //Invented by Nathan Ramanathan
#include "pitches.h"  //File with all the music notes in the known universe
#define buzzer 11

unsigned long songMillis = 0;
bool check = false;
int thisNote = -1;
// notes in the melody:
//int melody[] = {
//  NOTE_E4, NOTE_F4, NOTE_FS4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5
//};

int melody[] = {//The FINAL COUNTDOWN song
  NOTE_B4, NOTE_A4, NOTE_B4, NOTE_E4, 0, NOTE_C5, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4, 0, NOTE_C5, NOTE_B4, NOTE_C5, NOTE_E4, NOTE_FS4, 0, NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,   NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_B4,NOTE_A4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,NOTE_FS4,0,NOTE_A4,NOTE_G4,NOTE_A4,NOTE_G4,NOTE_FS4,NOTE_A4,   NOTE_G4,NOTE_FS4,NOTE_G4,NOTE_A4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_A4,NOTE_G4,NOTE_FS4,NOTE_E4,NOTE_B4,NOTE_C5,NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_B4,NOTE_A4,    0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_E4,NOTE_FS4,0,NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4,0, NOTE_C5,NOTE_B4,NOTE_C5,NOTE_E4,   NOTE_FS4,0,NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,NOTE_G4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  16, 16, 4, 4, 2, 16, 16, 8, 8, 4, 2, 16, 16, 4, 4, 4, 4, 16, 16, 8, 8, 8, 8,  4,8,16,16,4,4,2,16,16,8,8,4,2,16,16,4,4,4,6,16,16,8,8,8,8,  2,16,16,3,16,16,8,8,8,8,4,8,1,4,8,16,16,4,4,2,16,16,8,8,8,  2,16,16,4,4,4,8,16,16,8,8,8,8,4,6,16,16,4,4,2,16,16,8,8,4,2,16,16,4,4,  4,6,16,16,8,8,8,8,4
};

const int lengthOfSong = 23+25+25+30+9; //For some reason the millis() doesn't like calculating array size.
//////////////////////////////////////////////////////////////////////
void setup() {
  Serial.begin(115200);
  Serial.println("Type 'g' to hear a melody.");
}

void loop() {
  // no need to repeat the melody.
  unsigned long currentMillis = millis();
  if (Serial.available()) {
    int c = Serial.read();
    if (c == 'g') {               //type 'g' to start song
      check = !(check);
    }
    if (c == 'h') {               //type 'h' in the serial monitor to confirm that the arduino listens to you while it plays music!
       Serial.println("Hello");
    }
  }
  else {
    if (check) {
      MelodyWithoutDelay(currentMillis);
    }
  }
}

void MelodyWithoutDelay(long cMillis) {
  int noteDuration = 1700 / noteDurations[thisNote];
  int pauseBetweenNotes = noteDuration * 1.2;

  if ((cMillis - songMillis <= pauseBetweenNotes / 4)) {
  }
  else if ((cMillis - songMillis <= pauseBetweenNotes)) {
    tone(buzzer, melody[thisNote], noteDuration);
  }
  else {
    if (thisNote >= lengthOfSong) {
      thisNote = -2;
      check = false;
    }
    thisNote++;
    noTone(buzzer);
    songMillis = cMillis;
  }
}

Did you figure out your issue and is it working now?

What you have to is in the for loop within function playSuperMario to check for the Off button. If so, stop the loop.
This is assuming the delay for waiting until the note is finished is ok.\
Maybe a better 'design' is not to use playSuperMario as one function, but within the loop function, to keep a boolean that defines if the song is playing or not. If playing, call a function: playNextNoteOfSuperMario. You also need to keep the index of the next to play note.
Something like:
bool CurrentlyPlaying = false;

Maybe you can skip this variable CurrentlyPlaying since it is probably the same as (power == 2) ??. 2 means something, so use an enumeration for that.
void powerOFF( void ) {
  digitalWrite(powerLedRed,   HIGH);
  digitalWrite(powerLedGreen, LOW);
  power = 0;
  CurrentlyPlaying = false;
}

void powerON( void ) {
  digitalWrite(powerLedRed,   LOW);
  digitalWrite(powerLedGreen, HIGH);
  I would expect power also to be assigned here.
  CurrentlyPlaying = true;
}

int CurrentNote = 0;

Set this variable again to 0 when Power On button pressed
void loop( void )
{
  if (songPlaying)
  {
      playNextNoteOfSuperMario();
  }

  if ( power == 2 ) {
    powerOFF();
  }

  if (irrecv.decode(&results)) {
    translateIR();
    irrecv.resume();
  }
}

void playNextNoteOfSuperMario( void ) {
  Serial.println(" 'Mario Theme'");
  int size = sizeof(melody) / sizeof(int);

  int noteDuration = 1000 / tempo[CurrentNote];
  buzz(buzzer, melody[CurrentNote], noteDuration);

  int pauseBetweenNotes = noteDuration * 1.30;
  delay(pauseBetweenNotes);

  buzz(buzzer, 0, noteDuration);
}

I already tried something similar (if (power == 0 ){} ) inside that loop, didn't work, or maybe I not understand you. Could you provide an Example?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
PIR sensor code logic works on Mega but not on Yún
I am trying to use this example(it works on Arduino Mega): millis() - lowIn comes greater than 5000when motion ends.
/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;

int pirPin = 3; //the digital pin connected to the PIR sensor's output
int ledPin = 13;

/////////////////////////////
//SETUP
void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}

////////////////////////////
//LOOP
void loop() {
  if (digitalRead(pirPin) == HIGH) {
    digitalWrite(ledPin, HIGH);
    //the led visualizes the sensor's output pin state
    if (lockLow) {
      // makes sure we wait for a transition to LOW before any further output is made:
      lockLow = false;
      Serial.println("---");
      Serial.print("motion detected at ");
      Serial.print(millis() / 1000);
      Serial.println(" sec");
      delay(50);
    }
    takeLowTime = true;
  }

  if (digitalRead(pirPin) == LOW) {
    digitalWrite(ledPin, LOW);
    //the led visualizes the sensors output pin state
    if (takeLowTime) {
      lowIn = millis();
      //save the time of the transition from high to LOW
      takeLowTime = false;
      //make sure this is only done at the start of a LOW phase
    }
    //if the sensor is low for more than the given pause,
    //we assume that no more motion is going to happen
    Serial.print(millis() - lowIn);
    Serial.print("    ");
    Serial.print(lockLow);
    Serial.print("    ");
    Serial.println(pause);
    if (!lockLow && millis() - lowIn > pause) {
      //makes sure this block of code is only executed again after
      //a new motion sequence has been detected
      lockLow = true;
      Serial.print("motion ended at "); //output
      Serial.print((millis() - pause) / 1000);
      Serial.println(" sec");
      delay(50);
    }
  }
}

But it doesn't work on a Yún shield mounted on an Arduino Leonardo. The difference of millis() - lowIn always comes out to be lower than pause.

The Arduino Leonardo uses the ATmega32U4 microcontroller which uses lower logic levels for the digital inputs. Perhaps that is not compatible with the PIR sensor. You can simulate the PIR sensor with a piece of wire and connect it to 5V or GND.
For the Leonardo, sometimes "SerialUSB" is used instead of "Serial". But if see a message on the serial monitor then "Serial" is okay.
If you can't make it work, then try to reduce the number of variables. In this case, remove the Yun shield and try it with the Leonardo board.
The Arduino Mega 2560 and Arduino Leonardo have both a 8-bit microcontroller and 'millis' works on both in exactly the same way. Therefor 'millis' itself or the variables can't be the problem.

what do you mean by "You can simulate the PIR sensor with a piece of wire and connect it to 5V or GND." ?

Instead of the PIR sensor, connect a piece of wire to pin 3 and connect that to either GND or 5V. That's all. It is just a test, perhaps there is trouble with the voltage level of the PIR sensor (but I don't know).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
MIDI output circuit behaving incorrectly when not connecting with USB
I recreated this circuit to send MIDI notes to my MIDI-USB adapter to my computer.

It works fine when the Arduino is powered via USB. When I power the Arduino Nano with 9v on Vin however, the output is gibberish. It just spams the input monitor on my computer with random midi commands. For testing I used this code:
    #include <MIDI.h>

    MIDI_CREATE_DEFAULT_INSTANCE();

    static const unsigned ledPin = 13;
    bool on = false;
    void setup()
    {
        pinMode(ledPin, OUTPUT);
        MIDI.begin(MIDI_CHANNEL_OFF);
    }

    void loop()
    {
        digitalWrite(ledPin, on);
        on = !on;
        MIDI.sendControlChange(12, 127, 1);
        delay(1000);
    }

The Arduino itself seems to be working fine when powered with 9v (note that I tested with both a wall power supply as well as a 9v battery) as the TX-led still  flashes briefly and the built-in led also toggles nicely.
At first I blamed my power supply and/or my power supply, but both work fine on my MIDI-keyboard so I don't think they are to blame.
Worth mentioning: When the Arduino was powered by Vin, I also as a test plugged in the USB-cable in the Arduino, But only touched the connector on the USB-port on my computer. I then received the correct notes.
Because of this I think it is an issue with the grounding. What am I doing wrong?
EDIT: Thanks for the response guys. I think I diagnosed my problem incorrectly. I'm using a cheap Chinese MIDI-adapter which I pried open, and it lacks an optocoupler. I'm getting a decent MIDI adapter now. Thanks!

What USB MIDI adapter are you using? That one? https://i.stack.imgur.com/yA3dT.jpg

Do you really need to use port 1?

@CL. Yup, that was the one I was using. After some after some googling on it I found out that it could lack an optocoupler, and after opening it confirmed that mine didn't have one as well. I ordered a good adapter now! Thanks!

If you are connecting multiple devices then they have to share a common ground.
I only know about British mains sockets, they all have an earth pin connecting to a common ground, so usually you are OK.
Plug in transformers 'wall warts' sometimes don't connect to ground, the give away is the plastic pin.  In this case you need to provides a separate earth and connect it to the rest of the equipment.
PCs normally have a good earth and this is passed by the USB to connected devices.  So "the Arduino always works when it is connected to the PC" is usually a good indicator of an earthing issue.
I think your keyboard uses a wall wart and therefore when you remove the USB they both float.  Touching the USB lead to the Arduinos USB socket grounds it all again.
So it looks like you diagnosed the fault correctly :)


text:
Multiple definition of "..." Compiler Error
I am creating a simple library to test how multiple files in an Arduino program works. I have three files. MotorController.ino:
#include <motor.h>

void setup() {
   motorInitialize();
}

void loop() {

}

motor.cpp:
#include "motor.h"

void motorInitialize() {

  for (int i = 0; i < 4; i++) {
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
  }
  delay(1000);

}

and motor.h:
#ifndef _motor_h_
#define _motor_h_

#include "Arduino.h"
#include <Servo.h>

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

void motorInitialize();
#endif

When I try to compile the program, I get the error:
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor1'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor2'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor3'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor4'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motorArray'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

I have read similar posts on this issue, but none of the solutions seem to work for me. I've followed the instructions on the Arduino website on how to create a library, and that doesn't seem to resolve this issue.

Although the motor (global) variables are defined in a header files, they are included in both cpp files, thus defined twice.
Make them extern, and than define them in the motor.cpp file.
In motor.h, change
Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

to
extern Servo motor1, motor2, motor3, motor4;
extern Servo motorArray[4];

In motor.cpp, add:
Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

As a side note, use consts for values 4 and 2000.

Isn't #ifndef _motor_h_, #endif wrapping suppose to help you with double definitions?

@machineaddict It helps to prevent including a header file twice when compiling a c or cpp file, but it does not help when compiling two different c or cpp files. What is happened: file a.cpp is compiled (to e.g. a.o), and b.cpp is compiled to b.o. Than in the linker a.o and b.o both contains the same variable if defined in the .h file included by both and an error is shown.

I see. Thanks for the explanation!

@machineaddict You're welcome


text:
Serial monitor showing extra data
I am trying to communicate NODEMCU and Arduino Uno using Serial Communication (RX,TX) using SoftwareSerial library.
Here is my code
int count;
char reqst[] = " ";

void setup() {

  Serial.begin(115200);
  Serial.println("Ready");

}

void loop() {

 while ( Serial.available() > 0 )  {

  char inChar = Serial.read();
  reqst[count] = inChar;
  count++;

     if (inChar == '\n') {

        Serial.print("String: ");
        Serial.println(reqst);
        count = 0;
        delay(1000);

     }

 }

}

here my output in serial monitor is showing ;
String: aj
779
String: am
779
I have checked that from NODEMCU i am sending correct string but in Arduino Uno
the number "779" is coming from nowhere.
So my problem is i am not be able to execute my function according to the desired string. Can anyone tell why the number is coming below the string ?.

char reqst[] = " ";

Here you created an array two chars in length. But one of those characters must be used for the null terminator so actually it can only hold a string that's a single character long. If you write past the end of the array that will cause undefined behavior. This is likely to be the cause of the strange results you encountered. You need to size reqst[] large enough to contain any string you may receive, including the null terminator. You should add code to ensure that you never write off the end of the array and that it will always end in a null terminator.
I realize it may only be a simplified minimal example, but in the code you posted there is no need to store the incoming characters. Instead you could just print them as they are received.

Also needs to add a null to the end of the string before printing it.

thanks for the help.  the reason why i am storing the receiving string is because i will be doing string comparison operations and then do further operations using that string i have received.
Do u mean to say that i should fix the char reqst[] array size .?
can you have a look at the original code . strong apology for not sharing this one.
http://textuploader.com/d0li1
here output is
writting to radio is :
am00779
writting to radio is :
aj00779
still the 00779 is coming.

@Delta_G :guys , i hope u can see the full code given in the link in the comment above.

It's reasonable to provide a minimal code example, I just thought I'd mention it in case you weren't using the string for anything. As I said: "You need to size reqst[] large enough to contain any string you may receive, including the null terminator. You should add code to ensure that you never write off the end of the array and that it will always end in a null terminator."


text:
Interfacing with SPI
I am attempting to program an Arduino to interface with a DAC, specifically the AD7390 made by Analog Devices.
I have tried using the SPI library as a means of realising the interface but am confused by the PIN layout of the DAC. It provides me with SCK, SDI, CLR and LD pins.
The LD (Load Strobe) PIN is used to transfer buffers from the chip's on-board shift register to its DAC register.
The CLR PIN is used to forcibly clear the DAC register.
The documentation claims that the device is SPI compatible but, using these PINs with the Arduino Mega2560 as a micro-controller, only partially works and I am concerned that the circuit requirements of the SPI library are not being satisfied. In SPI documentation, a SS (slave select) PIN is universally mentioned but is not present with my device.
As I have managed to get the CLR PIN working, consistently and as expected, I wonder if a manual approach - i.e. using shiftIn() instead of the SPI library - is the way to go.
Any suggestions or advice would be appreciated.

The AD7390 data sheet timing diagrams show that /LD is in effect a slave select, but an active high one.
Specifically, it says that while /LD is high, each rising clock edge causes "Shift-Register-Data Advanced One-Bit", while when it is low, the shift register data is transferred to the DAC.
So basically you would need to use SPI in a mode where the slave select is controlled by software and asserted with the opposite of the usual polarity, but the actual shifting of the data can be accomplished with the hardware SPI engine.
It does not seem that you are always required to use the /CLR input - if you don't want to use it, wire it high.  Otherwise, you can connect it to a GPIO, take it low, and then raise it so that the rising edge causes an asynchronous clear.


text:
PHP/My SQL Database -> to Arduino Serial Monitor
I'm using this domain http://www.decathlon.commonarchitecture.ca/ to host my phpmyadmin database and php code. I would like to read a specific column of the database in the serial monitor, displaying each number one right after the other. I'm unsure of whether to work with a GSM shield, an Ethernet shield or an Arduino wifi shield. Here is my php code (indents are off I know):
<?php

 $dbhost = "mysql.commonarchitecture.ca";
 $username = "arduinodb";
 $password = "*******";
 $db = "arduinodb" ;

    mysql_connect("$dbhost" , "$username" , "$password");
     //echo "Connected" ;

    //select db
    mysql_select_db($db);
    //echo "Connected to db" ;

  $sql="SELECT * FROM data";

  $records=mysql_query($sql);

 ?>

 <!DOCTYPE html>

 <title> Consumption Data </title>

 Day
 Date
 Water Consumption (liters per person)

 <?php

    while($data=mysql_fetch_assoc($records)) {

         echo "
";

         echo "".$data['id']."	";

         echo "".$data['date']."	";

         echo "".$data['value']."	";

         echo "
";

     }//end while

     ?>

The code works, however I'm unsure of how to go about reading the data on an Arduino (very new to Arduino)
Here's my Arduino code paired with an ethernet shield
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192, 168, *, *);

EthernetClient client;

char server[] = "www.decathlon.commonarchitecture.ca";

void setup()
{
   Serial.begin(9600);

  // attempt a DHCP connection:
  Serial.println("Attempting to get an IP address using DHCP:");
  if (!Ethernet.begin(mac)) {
  // if DHCP fails, start with a hard-coded address:
  Serial.println("failed to get an IP address using DHCP, trying
  manually");
     Ethernet.begin(mac, ip);
  }

  Serial.print("My address:");
  Serial.println(Ethernet.localIP());
}

void loop()
{
    // connect to the server
    if (client.connect(server, 80))
    {
        // print to serial monitor
        Serial.println("connected...");
        Serial.println("ARDUINO: forming HTTP request message");

        // send data the server through GET request
        client.print("GET /index.php?value");
        client.println(" HTTP/1.1");
        client.print("HOST:  ");
        client.println(server);

        Serial.println("ARDUINO: HTTP message sent");

        // give server time to receive request
        delay(1000);

        // get the response from the page and print it to serial port
        // to ascertain that request was received properly
        if(client.available())
        {
            Serial.println("ARDUINO: HTTP message received");
            Serial.println("ARDUINO: printing received headers and
script response...\n");

            while(client.available())
            {
                char c = client.read();
                Serial.print(c);
            }
        }
        else
        {
            Serial.println("ARDUINO: no response received / no response
received in time");
        }

        client.stop();
    }
    // do nothing forever after:
    while(true);
}

My issue now is in getting the Arduino to read my php data, can I not use an http GET request to display data in my serial monitor? Am I using this function properly? There's a ton of documentation on posting Arduino sensor data to the web using php/my sql but not as much on retrieval of set data back into the serial monitor. Here's what the monitor reads currently...
Attempting to get an IP address using DHCP:
My address:192.168.*.*
connected...
ARDUINO: forming HTTP request message
ARDUINO: HTTP message sent
ARDUINO: no response received / no response received in time

Firstly if you really are using an Uno then you cant read the data without putting the uno on a network (obviously).  To do this you could get either a Ethernet shield of a Wifi shield.  A wifi shield is probably based on an ESP8266 and you talk to it by creating a serial connection (using a software serial port).  There are plenty of examples and messages on here to get you started.
Once that's working you need to write a web client (note that this is much easier if you program the ESP8266 rather than the Arduino).  Your client needs to request the page from your server and then parse the returned data and extract the field you want.
While you are waiting for you network shield to arrive you could practice doing it on a Windows PC with Visual Studio, it will be easier to debug.

Any one of a GSM shield, an Ethernet shield or an Arduino wifi shield should be able to pull a web page from a web server and feed it into your Arduino.
I highly recommend buying hardware from people that put lots of example program text on their website, rather than trying to save a few nickles buying "equivalent" hardware from people that don't give any examples, leading to hours of frustration.
Some of the places I've found that have lots of example program text (in no particular order):

Arduino Ethernet Shield 2: links to "Getting Started with the Arduino Ethernet Shield and Ethernet Shield 2" which in turn links to example code "WebClient: make a HTTP request" and "WebClientRepeating: Make repeated HTTP requests."
Arduino Ethernet Shield 2: links to Arduino Ethernet2 Library which in turn links to example code
W5500 Ethernet Shield for Arduino v1.0: links to WIZ5500 based Ethernet Shield library for Arduino which in turn links to example code "WebClient" and "WebClientRepeating"
Adafruit FONA 800 Shield - Voice/Data Cellular GSM for Arduino: links to Datasheets & App notes, and the "SIM800 IP App Note" has some brief examples of using HTTP to pull from a web server.
SparkFun ESP8266 Thing - Dev Board: links to ESP8266 Thing Development Board Hookup Guide, which has an example that "Read all the lines of the reply from server and print them to Serial". (related: "Quick Tip: HTTP GET with the ESP8266 Thing" )

If I were you, I would test the hardware with exactly the example programs given for that hardware, and resist the urge to "improve" them until after I confirm that the example programs actually do work.
(Perhaps you already did that? If so, please update your question to say the example code seemed to run OK, and exactly which example code you tried, and what minor changes you made that still seemed to run OK, so we can focus on what changed between "partially working" vs. "not even that part working").
(I personally find it easier to parse JSON data sent by a web server set up to send out "Content-Type: application/json; charset=utf-8", or TOML data sent by a web server as "Content-Type: text/plain; charset=utf-8",
rather than programmatically parse HTML tables sent by a web server set up to send out "Content-Type: text/html; charset=utf-8", but any of these ways should work).


text:
Arduino FIFO queue for with potentiometer values and 7 segment display
As of now I have code that takes a value from a potentiometer and maps it from 0-9. Based on this mapped value a number will be displayed on the seven segment display.
Currently, if I quickly turn the pot completely then back to zero it will show everything very quickly and then show 0 until I change the pot value again. What I am trying to do is make it so if it's quickly turned completely then back to 0, after a second it will display all the number from 0-9 then back down to 0, each for a second.
I was given a hint to use arrays to create a FIFO queue but I am not sure how to go about doing this and I have been stuck on this for a while. Here's my code:
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
int pinA = 2;
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;
int pinF = 7;
int pinG = 8;
int i;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pins as outputs.
  pinMode(pinA, OUTPUT);
  pinMode(pinB, OUTPUT);
  pinMode(pinC, OUTPUT);
  pinMode(pinD, OUTPUT);
  pinMode(pinE, OUTPUT);
  pinMode(pinF, OUTPUT);
  pinMode(pinG, OUTPUT);
}

void loop() {
  potval=map(analogRead(A0),0,921,0,9);
  if (potval==0){
    //0
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, HIGH);
  }
  if (potval==1){
    //1
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==2){
    //2
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, HIGH);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==3){
    //3
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==4){
    //4
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==5){
    //5
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==6){
    //6
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==7){
    //7
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==8){
    //8
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==9){
    //9
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
}

Without seeing the code it is bit difficult to help. Please edit your answer and include the relevant parts of the code, otherwise we will end up (re)writing your code for you.
Hint: why not, when you detect a change in the pot, take the new reading, and then count down/up slowly (at the rate that you desire) from the currently displayed reading to the new measured reading - using a for loop, which contains a delay()? With each iteration of the loop you can display the new value. Easy!
However, this sounds like a terrible idea
Note that your code won't do anything else whilst the display is incrementing and decrementing, using this method. So, if you were to spend a lot of time twiddling with the knob, then the code wouldn't get much time to actually do any real work, apart from displaying the updated value.
In order for your code to do real work, whilst displaying the new updated value, you would either need interrupts, or integrate the display updating procedure into the loop(), such that each iteration of the loop() updates the display (or upon each n iterations of loop(), as loop() will probably be looping to quickly. You will probably need to use millis()).
NOTE: From a UX aspect, although it all sounds very 1960's-James-Bond-evil-guy-equipment, the whole notion of the displayed value slowly following the actual location of the knob sounds, at best, extremely infuriating, if not down right dangerous (depending upon the context). Human feedback should be as fast as possible. Else the user will constantly be turning the knob to reach the value that they which to achieve, when in fact they have already passed that value, and may be over compensating, and it is just the fancy display graphics that is showing the wrong value.
Assuming that the knob is controlling something else (actuator, motor, heater, etc.), and not just a pretty display in itself, unless, you are actually outputting the delayed displayed digital value, and not the knob's actual current analogue value, I would seriously recommend against doing this.
I may be wrong, and it would probably require a separate question on SE.UX, although, I would imagine that it has been asked already.

Code was added and the pot is just being used to control a 7 segment

Usually anything with a slower refresh rate than 100-60ms is considered laggy and should be avoided. So you could implement some smoothing (say only allow decreasing values) to make the counter seem smoother, otherwise it's quite pointless, human motion itself is rather smooth already if you sample fast enough.

First of all, that way of writing the displays is quite horrible to me ;) Better to use a matrix (and, please, no ints for small variables like pin numbers, and make them constant). This is the code fixed with these improvements:
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
const byte pinA = 2;
const byte pinB = 3;
const byte pinC = 4;
const byte pinD = 5;
const byte pinE = 6;
const byte pinF = 7;
const byte pinG = 8;

byte Matrix[][7] = { { LOW , LOW , LOW , LOW , LOW , LOW , HIGH}, // potval 0
                     { HIGH, LOW , LOW , HIGH, HIGH, HIGH, HIGH}, // potval 1
                     ... fill with the other rows ...
                     { LOW , LOW , LOW , HIGH, HIGH, LOW , LOW }  // potval 9
                    };

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pins as outputs.
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinD, OUTPUT);
pinMode(pinE, OUTPUT);
pinMode(pinF, OUTPUT);
pinMode(pinG, OUTPUT);
}

void loop() {
    potval=map(analogRead(A0),0,921,0,9);

    digitalWrite(pinA, Matrix[potval][0]);
    digitalWrite(pinB, Matrix[potval][0]);
    digitalWrite(pinC, Matrix[potval][0]);
    digitalWrite(pinD, Matrix[potval][0]);
    digitalWrite(pinE, Matrix[potval][0]);
    digitalWrite(pinF, Matrix[potval][0]);
    digitalWrite(pinG, Matrix[potval][0]);
}

You can further improve it by not having seven variables but only an array to iterate over, but .. ok, let's keep this.
Ok, now you want to do a "slow movement". In order to do this you can use a variable to track the current position, and let it move towards the target value once every XX ms. This is the approach used, for instance, in CNCs and 3d printers movements.
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
const byte pinA = 2;
const byte pinB = 3;
const byte pinC = 4;
const byte pinD = 5;
const byte pinE = 6;
const byte pinF = 7;
const byte pinG = 8;

unsigned long int prevMillis;
const int delayBetweenMovement = 200;

byte Matrix[][7] = { { LOW , LOW , LOW , LOW , LOW , LOW , HIGH}, // potval 0
                     { HIGH, LOW , LOW , HIGH, HIGH, HIGH, HIGH}, // potval 1
                     ... fill with the other rows ...
                     { LOW , LOW , LOW , HIGH, HIGH, LOW , LOW }  // potval 9
                    };

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pins as outputs.
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinD, OUTPUT);
pinMode(pinE, OUTPUT);
pinMode(pinF, OUTPUT);
pinMode(pinG, OUTPUT);
prevMillis = millis() - delayBetweenMovement;
}

void loop() {
    if ((millis() - prevMillis) >= delayBetweenMovement)
    {
        prevMillis += delayBetweenMovement;

        potval=map(analogRead(A0),0,921,0,9);
        static int CurrentPotVal = potval;

        if (potval > CurrentPotVal)
            CurrentPotVal++;
        if (potval < CurrentPotVal)
            CurrentPotVal--;

        digitalWrite(pinA, Matrix[CurrentPotVal][0]);
        digitalWrite(pinB, Matrix[CurrentPotVal][0]);
        digitalWrite(pinC, Matrix[CurrentPotVal][0]);
        digitalWrite(pinD, Matrix[CurrentPotVal][0]);
        digitalWrite(pinE, Matrix[CurrentPotVal][0]);
        digitalWrite(pinF, Matrix[CurrentPotVal][0]);
        digitalWrite(pinG, Matrix[CurrentPotVal][0]);
    }
}

The delayBetweenMovement constant makes a delay between the readings. With this method, if you quickly turn it to 9 and then to 0 you will not arrive to 9. For instance you put a 9, the display starts doing 0..1..2..3, then you switch to 0 and the count will not reach 9, but start going back to 0. Reaching 9 will require some more structures; if you need it ask and I'll make some modifications
EDIT: as requested, here is a version that can memoryze up to 20 states and reproduce them. If you need them just increase the FIFO size.
Note: I haven't tested these programs. In the other two I was pretty confident I hadn't made any major bug, but this one is a bit more complicated. There can be some bugs left..
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
const byte pinA = 2;
const byte pinB = 3;
const byte pinC = 4;
const byte pinD = 5;
const byte pinE = 6;
const byte pinF = 7;
const byte pinG = 8;

unsigned long int prevMillis;
const int delayBetweenMovement = 200;

byte Matrix[][7] = { { LOW , LOW , LOW , LOW , LOW , LOW , HIGH}, // potval 0
                     { HIGH, LOW , LOW , HIGH, HIGH, HIGH, HIGH}, // potval 1
                     ... fill with the other rows ...
                     { LOW , LOW , LOW , HIGH, HIGH, LOW , LOW }  // potval 9
                    };

const byte FifoSize = 20;
byte TargetFifo[FifoSize];
byte FifoHead = 0, FifoTail = 0;

byte potval;

// the setup routine runs once when you press reset:
void setup() {
    // initialize the digital pins as outputs.
    pinMode(pinA, OUTPUT);
    pinMode(pinB, OUTPUT);
    pinMode(pinC, OUTPUT);
    pinMode(pinD, OUTPUT);
    pinMode(pinE, OUTPUT);
    pinMode(pinF, OUTPUT);
    pinMode(pinG, OUTPUT);
    prevMillis = millis() - delayBetweenMovement;
}

byte FifoAvailableForWrite()
{
    if (FifoTail > FifoHead)
        return (FifoSize - FifoTail + FifoHead);
    else
        return (FifoHead - FifoTail);
}

void loop() {
    potval=map(analogRead(A0),0,921,0,9);
    static byte prevPotVal = potval;
    static int CurrentPotVal = potval;

    if ((prevPotVal != potval) && (FifoAvailableForWrite() > 1))
    {
        TargetFifo[FifoTail] = potval;
        prevPotVal = potval;
        FifoTail = (FifoTail + 1) % FifoSize;
    }

    if ((millis() - prevMillis) >= delayBetweenMovement)
    {
        prevMillis += delayBetweenMovement;

        if (FifoHead != FifoTail)
        {
            if (TargetFifo[FifoHead] > CurrentPotVal)
                CurrentPotVal++;
            if (TargetFifo[FifoHead] < CurrentPotVal)
                CurrentPotVal--;
            while (TargetFifo[FifoHead] == CurrentPotVal)
                FifoHead = (FifoHead + 1) % FifoSize;
        }

        digitalWrite(pinA, Matrix[CurrentPotVal][0]);
        digitalWrite(pinB, Matrix[CurrentPotVal][0]);
        digitalWrite(pinC, Matrix[CurrentPotVal][0]);
        digitalWrite(pinD, Matrix[CurrentPotVal][0]);
        digitalWrite(pinE, Matrix[CurrentPotVal][0]);
        digitalWrite(pinF, Matrix[CurrentPotVal][0]);
        digitalWrite(pinG, Matrix[CurrentPotVal][0]);
    }
}

Thank you for this! However, I do need it to go to 9 then back to 0 so if you could grab back to me on how to do it or with the code that would be greatly appreciated. Thanks once again.

@TahaA I tried to develop a fifo based solution.. See if that works..


text:
Error while boot loading Atmega 2560 using Arduino Mega 2560
I have developed custom board using Atmega 2560. I am doing boot loading process using the process of migrate from an Arduino board to a standalone microcontroller.

I have followed this steps...
1) Upload the ArduinoISP sketch onto your Arduino board.
2) Wire up the Arduino board and microcontroller as connections mentioned on Arduino Site.
3) Select "Arduino/Genuino Mega/ Mega 2560" from the Tools > Board menu.
4) Select "Arduino as ISP" from Tools > Programmer
5) Run Tools > Burn Bootloader
While doing this process I am getting this Error...

avrdude: Yikes!  Invalid device signature.
           Double check connections and try again, or use -F to override
           this check.
  Error while burning bootloader.

I have done connection like this...
MISO  -  D50
MOSI  -  D51
SCK   -  D52
Reset -  D53/Reset
+5V   -  Vcc
GND   -  GND

What wrong I am doing? Or any step I have missed?

Is that a clone of mega just without the FTDI IC ?

@SagnikPradhan Yes it is a clone without FTDI IC

Same connections worked for me. Just one connection have to change.
Reset - D10

You wired the whole thing backwards. The proper wiring is
Your board - Arduino
     MISO  -  D50
     MOSI  -  D51
     SCK   -  D52
     Reset -  D53
     Vcc   -  5V
     GND   -  GND

This is kind of obvious from the picture: you would normally use the ISP
connector of the target board.


text:
How do I measure speed and manipulate the speed based on distance covered?
I'm doing a project on arduino. I'm using a online simulator to design the circuit. I have a dc motor. How do we measure the rpm,speed at that rpm,distance covered by the motor in a given time. For example,
When motor starts, it starts rotating slowly and gradually increases it's RPM. When it covered a distance of 50 meters, the motor slows down and stops. After 10 seconds, the motor starts again at that 50 meter point and goes to 100 meters point and stops. Like this it stops for every 50m. For this we need to keep track of the distance travelled by motor and control it's speed.
How do I achieve the above working. I have tried alot and verified many tutorials but couldn't understand what to do. Please help me out.
(The online simulator I'm using has a L293D motor driver, IR sensor and a ultrasonic distance sensor in it's component list.)

Put an encoder on the shaft; this way you will be able to "read" the rotational speed. Whis is linked to the vehicle by a constant. And integrating the speed (summing up) will give you the distance travelled.

Rather than computing and integrating the speed (which amount to computing the integral of a derivative), you just have to count the pulses from the encoder.

@EdgarBonet yes, in fact summing up the "frequencies" that you read is equivalent to counting the pulses... I tend to overcomplicate things ;)

They key point here is to know the distance. The simplest way of finding that distance is to know how many times the wheel has completed an entire revolution. Multiply that number of revolutions by the circumference of your wheel and you have the distance the wheel has covered.
Depending on how precisely you want to measure that distance you may get away with a simple magnet and hall effect sensor. Place the magnet on the wheel, and locate the hall effect sensor so the magnet passes it close enough to trigger. Each pulse from the sensor is one rotation of the wheel.
You could increase the resolution by adding more magnets - 4 magnets set at 90° points around the wheel will give you a pulse for each quarter of a revolution (so multiply pulses by a quarter of your circumference).
If you want better resolution and accuracy you could attach a rotary encoder to the axle of the wheel. This, depending on the encoder, can give you far better resolution than simple magnets. Some will also give you the angle the wheel is at (not that such information would be of interest in this project).


text:
sizeof() on custom library constructor returns wrong result
I made a custom library (let's call it DigitalOutput.h) to learn a bit about librairies and to simplify my work. Here is the basic constructor in the .h file:
DigitalOutput(uint8_t pin);

Here is the code in the .cpp file :
DigitalOutput::DigitalOutput(uint8_t pin)
{
    _pin    = pin;
    _status = LOW;
    pinMode(pin, OUTPUT);
}

So very simple stuff. Now, in my program, I call the function the usual way:
DigitalOutput LED(7); // pin #7 will be configured
                      // as an output pin to control the LED

Now the issue comes when I create an array and then use the sizeof() function.
Here is the code from my program (using an Arduino Mega):
DigitalOutput   LED_array[] = {22,23,24,25,26,27,28,29,
                               30,31,32,33,34,35,36,37};

So, the array contains 16 elements. But when I do for instance...
#define         LED_NUMBER    sizeof(LED_array)
//...
void setup(){
    //...
    Serial.println(sizeof(LED_array));
    Serial.println(LE_NUMBER);
}

...I get 160 as a result in both cases instead of 16...
So I end up doing a weird #define LED_NUMBER sizeof(LED_array) / 10 in order to get the proper result which is then used throughout the program. Any idea of why this isn't working right?

Please give a full working example that we can test ourself. Then we will tell you why a single object uses 10 bytes. Despite the compiler optimizations, I think that when the same object is declared more than once, that the size will be the same for every object.

As you already have the answer, I'll just mention a macro to address this very issue, #define countof(a) (sizeof(a)/sizeof(a[0])), where countof(LED_Array) evaluates to the number of members in the array, not to its memory size. I keep this definition in an 'h' file on my local system (named, oddly enough, local.h!) with other simple-but-useful tools I need on occasion.

It is working perfectly correctly.
sizeof doesn't return the number of elements in an array, it returns the number of bytes the array takes up. Since each entry in your array is an instance of your DigitalOutput class, the size is the number of elements multiplied by the size of the class - in this case 10 bytes.
To get the number of elements you must divide the number of bytes by the size of one element:
int numEles = sizeof(LED_array) / sizeof(DigitalOutput);

or
int numEles = sizeof(LED_array) / sizeof(LED_array[0]);

Well thanks to you all. This was the problem, I did not understand sizeof() well enough and read its definition in the Arduino documentations without really understanding what it was doing. I went back to it with your comments and now I'm getting it. Thanks for your help guys.

Note that the first is more robust (using sizeof(DigitalOutput)), in case you ever make LED_array dynamic and it has zero elements.

If you make the array dynamic you won't be using sizeof. That will just return the size of the pointer (2 or 4 depending on architecture) regardless of the size of the array. sizeof is a compile-time command not a library function.

Thanks Michel, I actually went with sizeof(DigitalOutput)but without foreseeing the issues you were mentioning. Good to know! Thanks Majenko, that's some good input I actually totally assumed it was a function.

Most people do. The C++ reference actually lists it as an operator - that is, in the same class as +, /, etc.

Indeed. By the way, does it mean I shouldn't use sizeof during runtime and only use it for compile-time operations? Will it cause unexpected errors? Or, as it is listed as an operator, will it be fine?

It will be replaced at compile time with the size of whatever you specify. Since sizes of static things never change at runtime what you ask makes no sense.

@Majenko ... I meant more like the (amount of bytes used by the dynamic array) / sizeof(DigitalOutput ) ... returning 2 or 4 does not really give helpful information :-)

You are checking the size of the object (DigitalOutput).
This object contains:

_pin
_status

And this probably results in 10 bytes per object, times 16 objects = 160 bytes.
So you are not creating an (unsigned byte) array which is 16 bytes.


text:
Using SoftwareSerial library with EnableInterrupt
I'm working on a project that involves both serial communication and GSM transmission.
I'm using the SoftwareSerial library for RS232 communication, and GSM (SMS) transmission:

TX and RX for RS232 : Arduino Uno D3 and D4 pins
TX and RX for GSM module : Arduino Uno D7 and D8 pins

The project requires also the use of the EnableInterrupt library to enable interrupt in Arduino's analog pins, meaning that I DON'T USE EnableInterrupt for all of the Arduino's digital pins including D3, D4, D7 and D8.
However when running the program that includes the two libraries, this long error message shows up :
libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_3'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_5'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_4'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Erreur de compilation pour la carte Arduino/Genuino Uno

Clearly, there is a conflict between the two libraries, Is there any solution to remove this conflict and run the two libraries together ?
Thanks in advance !

With SoftwareSerial, you can use only one RX at a time. Could you replace the Arduino Uno with a Arduino Mega 2560 ? That one has 3 spare hardware serial ports.

SoftwareSerial uses all PinChange interrupts.
EnableInterrupts uses all PinChange interrupts.

You can see the conflict.
All you can do is to modify both libraries to remove support for the interrupts you don't need it to support - that way you share out the responsibility for handling the different interrupts between the two libraries.

I would suggest using different software serial libraries and pins.  To apply this answer, I would suggest this configuration:

Connect your RS232 device to pins 0 & 1 and use Serial
Connect your GSM device to pins 8 & 9 and use AltSoftSerial (it must use those pins).

If you do not send anything to the RS232 device, you can still use Serial for debug statements.  Don't even connect the TX pin to the RS232 device.  You will have to disconnect the RX pin to upload new sketches over USB.  Or, if the RS232 device receives formatted commands, it would ignore debug statments that don't look like commands.  This has the added benefit that the Serial Monitor window will display the commands you do send to the RS232 device.
If you really need to use 3 serial ports, you will have to use this configuration:

Use Serial for whatever
Connect the RS232 or GSM device to pins 8 & 9 and use AltSoftSerial
Connect the other device to any two pins and use my NeoSWSerial.

AltSoftSerial is more efficient at transmitting than NeoSWSerial, so use AltSoftSerial for the device to which you send the most data.  NeoSWSerial is limited to baud rates 9600, 19200 and 38400, so that may be a consideration.
SoftwareSerial is a terrible choice, because it disables interrupts for long periods of time, it can only listen to one port at a time, and it cannot transmit and receive at the same time.
AltSoftSerial and NeoSWSerial do not have these limitations, and they can co-exist to give you 2 extra serial ports.  You should also be aware the NeoSWSerial disables interrupts while transmitting (not receiving).  AltSoftSerial uses one of the TIMER resources, while NeoSWSerial simply uses the millis() timer.
ADDENDUM
To answer your original question about using the EnableInterrupt library at the same time as a software serial library:
If you are using the first configuration above, AltSoftSerial will not conflict with EnableInterrupt.
If you are using the second configuration, NeoSWSerial will conflict with EnableInterrupt.  For this possibility, NeoSWSerial has an option to disable using all the Pin Change Interrupt ISRs.  Uncomment this line and call the NeoSWSerial::rxISR from the appropriate enableInterrupt() callback function:
#include <NeoSWSerial.h>
NeoSWSerial oneDevice( RX_PIN, TX_PIN );

void myISR()
{
  NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( RX_PIN ) ) );
}

void setup()
{
  enableInterrupt( RX_PIN, myISR, CHANGE );
}

This puts EnableInterrupt in charge of the ISRs.  If you want to try NeoSWSerial, it is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.


text:
What datatype is the names of the analog inputs?
I am writing a code for an automatic garden, and for this, I will use an array of sensors. I want to represent each plant as a class, and so one of the private variables will then be the sensorID, the name of the input on the analog inputs. But these are called 'A0' 'A1' and so forth, so I am wondering what datatype they are?
class Plant{
private:
String name;
??? sensorId;
...
public:
readSensor(??? sensorId);
...
};

I want to standardize this so I don't have to physically write 'A0' or 'A1' each time I need to read the sensor.

they are mapped to bytes in arduino

They're uint8_t:
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Those are defined in the pins_arduino.h file in the board's variant folder.


text:
Converting between NEC and HEX values from IR receiver
I jacked one of the IR receivers from my LED strip and hooked it up to my ESP8266 NodeMCU (running Arduino code). I found a great library called IRremoteESP8266. With this library, I can basically receive and send IR signals. However, the HEX values I get in are different from the NEC values I have to send out.
Here's what I've got:
Serial.println((uint32_t) (results.value & 0xFFFFFFFF), HEX);

When I compile this and I open the Serial Monitor, I get D7E84B1B when I press the button on my remote. I searched for it on Google, and I found a site that shows this:
‘real’ decode: FF02FD, hash decode: D7E84B1B

So naturally I tried doing:
irsend.sendNEC(0x00FF02FD, 32);

and it works just fine. The code example for receiving and sending can be found on the repository.
How do I make a conversion between what I receive and what I send, so I can basically mirror what I do?
EDIT:
According to the website I got the real NEC value from, they simply do:
Serial.print(results.value, HEX);

However, when I try to do that, I get this error:

call of overloaded 'println(uint64_t&, int)' is ambiguous

I know they are different projects, but the ESP8266 project I use is based off the IRremote library, which they seem to use.

There is a comment in the linked receiving code: // print() & println() can't handle printing long longs. (uint64_t)  you could just try casting it back to uint32_t - Serial.print((uint32_t)results.value, HEX);


text:
Countdown sometime stop
I've made a game with 3 countdowns and 1 global countdown.

When we start, the global one, go from 45:00 to 00:00.
The 1 go from 15:00 to 00:00 and if it reach 00:00:
The 2 start and go from 15:00 to 00:00 and it if reach 00:00:
The 3 start and go from 15:00 to 00:00

If you win little game, you can stop a countdown and start the next. If you win the 3 games, you stop the 3 countdown and the global too.
But sometime, my 2nd countdown stop itself, sometime at 13:58 or 10:54…
Is it possible that the millis() cause that bug ? Do you have an idea to improve my code and fix that ?
Fun fact : Sometime countdowns go from 01 to 60 instead of 00 to 59……
Sorry for my english, i'm not native speaker.
//14-06-17 Correctifs LED
//10-06-17 Correctif Jeu 1

#include "musical_notes.h"
#include "TM1637.h"
#include "SevenSegmentTM1637.h"
#include "OnewireKeypad.h"
#include "Password.h"

SevenSegmentTM1637    displaya(4, 5);
SevenSegmentTM1637    displayb(6, 7);
SevenSegmentTM1637    displayc(8, 9);
SevenSegmentTM1637    displayd(50, 51);

TM1637 tm1637a(50, 51); //TIMER GLOBAL 45
TM1637 tm1637b(4, 5); //TIMER 1 15
TM1637 tm1637c(6, 7); //TIMER 2 15
TM1637 tm1637d(8, 9); //TIMER 3 15

char KEYS[] = {
  '1', '4', '7', '*',
  '2', '5', '8', '0',
  '3', '6', '9', '#',
  'A', 'B', 'C', 'D'
};
OnewireKeypad <Print, 16 > KP(Serial, KEYS, 4, 4, A0, 4700, 1000, ExtremePrec );
Password password = Password( "8751" );

//PREMIER JEU
int checkbranche = 23;
int checkbrancheb = 22;
int checkbranchec = 24;
int state = HIGH;
int reading;
int readingb;
int readingc;
int previous = LOW;
int previousb = LOW;

int readingstart;
int checkstart = A1;

int speakerPin = 52;
int runOPEN = 0;
int runJEU1 = 0;
int runJEU2 = 0;
int runJEU3 = 0;
int runFAILGLOBAL = 0;

int winJEU1 = 0;
int winJEU2 = 0;
int winJEU3 = 0;
int winGLOBAL = 0;
int looseGLOBAL = 0;

int LED_jeu1_V = 30;
int LED_jeu1_R = 31;
int LED_jeu2_V = 33;
int LED_jeu2_R = 32;
int LED_jeu3_V = 35;
int LED_jeu3_R = 34;

int LED_jglobal1 = 36;
int LED_jglobal2 = 37;
int LED_jglobal3 = 38;
int LED_jglobal4 = 39;

int runcode = 0;

int second=0, minute=45, hour=0; // déclarer des variables de temps
int second1=0, minute1=15, hour1=0; // déclarer des variables de temps
int second2=0, minute2=15, hour2=0; // déclarer des variables de temps
int second3=0, minute3=15, hour3=0; // déclarer des variables de temps
long previousTime = 0;//détient temps précédent en ms
long previousTime1 = 0;//détient temps précédent en ms
long previousTime2 = 0;//détient temps précédent en ms
long previousTime3 = 0;//détient temps précédent en ms
long previousDelay = 0;//détient temps précédent en ms depuis buzzer était actif
long previousDelay1 = 0;//détient temps précédent en ms depuis buzzer était actif
long previousDelay2 = 0;//détient temps précédent en ms depuis buzzer était actif
long previousDelay3 = 0;//détient temps précédent en ms depuis buzzer était actif
long interval = 60000;//60 secondes de retard
long interval1 = 60000;//60 secondes de retard
long interval2 = 60000;//60 secondes de retard
long interval3 = 60000;//60 secondes de retard

int dismentel1 = 0; int fail1 = 0;
int dismentel2 = 0; int fail2 = 0;
int dismentel3 = 0; int fail3 = 0;
int dismentel4 = 0; int fail4 = 0;

char hour_str[4]; // Pour Convertir int en char
char minute_str[4]; // Pour Convertir int en char
char second_str[4]; // Pour Convertir int en char
char timeInt_str[0];  // Pour Convertir int en char

int accessgame = 3; //Activation de led quand les minutes arrivent à 3

unsigned char halfsecond=0;

void setup() {
  Serial.begin(19200);

  KP.SetHoldTime(3000);
  KP.SetKeypadVoltage(5.0);
  KP.ShowRange();

   displaya.begin();
   displayb.begin();
   displayc.begin();
   displayd.begin();

   tm1637a.set(4);
   tm1637a.init();
   tm1637a.point(POINT_ON);

   tm1637b.set(4);
   tm1637b.init();
   tm1637b.point(POINT_ON);

   tm1637c.set(4);
   tm1637c.init();
   tm1637c.point(POINT_ON);

   tm1637d.set(4);
   tm1637d.init();
   tm1637d.point(POINT_ON);

   pinMode(checkbranche, INPUT);
   pinMode(checkbrancheb, INPUT);
   pinMode(checkbranchec, INPUT);
   pinMode(checkstart, INPUT);
   pinMode(speakerPin, OUTPUT);

   pinMode(LED_jeu1_V, OUTPUT);
   pinMode(LED_jeu1_R, OUTPUT);
   pinMode(LED_jeu2_V, OUTPUT);
   pinMode(LED_jeu2_R, OUTPUT);
   pinMode(LED_jeu3_V, OUTPUT);
   pinMode(LED_jeu3_R, OUTPUT);

   pinMode(LED_jglobal1, OUTPUT);
   pinMode(LED_jglobal2, OUTPUT);
   pinMode(LED_jglobal3, OUTPUT);
   pinMode(LED_jglobal4, OUTPUT);

   delay(1000);

};

// run loop (forever)
void loop() {

readingstart = digitalRead(checkstart);
reading = digitalRead(checkbranche);
readingb = digitalRead(checkbrancheb);
readingc = digitalRead(checkbranchec);

if (runcode < 1) {
Serial.println("WHAT");

      if (readingstart == HIGH) {

        for (; runOPEN < 1; runOPEN++) {
          uhoh();
         }

    countdown();

Serial.print(halfsecond);
Serial.println(" ");

  if (dismentel1 == 1) {digitalWrite(LED_jglobal1, HIGH);} else {digitalWrite(LED_jglobal1, LOW);}
  if (dismentel2 == 1) {digitalWrite(LED_jglobal2, HIGH);} else {digitalWrite(LED_jglobal2, LOW);}
  if (dismentel3 == 1) {digitalWrite(LED_jglobal3, HIGH);} else {digitalWrite(LED_jglobal3, LOW);}
  if (dismentel4 == 1) {digitalWrite(LED_jglobal4, HIGH);} else {digitalWrite(LED_jglobal4, LOW);}

// GESTION DU JEU 1 //
  if (reading == LOW) {  //REVISION 1 HIGH -> LOW
      countdown1();

      if (second1 > 0 && minute1 >= 0) {
          int8_t timeDisp1[4];
          timeDisp1[0] = minute1 / 10;
          timeDisp1[1] = minute1 % 10;
          timeDisp1[2] = second1 / 10;
          timeDisp1[3] = second1 % 10;
          tm1637b.display(timeDisp1);

      if (minute1 < accessgame) {
        digitalWrite(LED_jeu1_V, LOW);
        digitalWrite(LED_jeu1_R, HIGH);
      } else {
        digitalWrite(LED_jeu1_V, HIGH);
        digitalWrite(LED_jeu1_R, LOW);
      }

          dismentel1 = 0;

      } else {
          displaya.print("FAIL");
            digitalWrite(LED_jeu1_V, HIGH);
            digitalWrite(LED_jeu1_R, LOW);
            for (; runJEU1 < 1; runJEU1++) {
              squeak();
            }
           fail1 = 1;
      }

  } else {
      displaya.print("--5-");
      digitalWrite(LED_jeu1_V, LOW);
      digitalWrite(LED_jeu1_R, HIGH);
      for (; winJEU1 < 1; winJEU1++) {
        wingame();
       }
       dismentel1 = 1;
  }

// GESTION DU JEU 1 //

// GESTION DU JEU 2 //
  if (readingb == HIGH) {
    dismentel2 = 1;
  }

  if ((dismentel1 == 1 or fail1 == 1) && dismentel2 == 0) {
    countdown2();

    if (second2 > 0 && minute2 >= 0) {
      int8_t timeDisp2[4];
      timeDisp2[0] = minute2 / 10;
      timeDisp2[1] = minute2 % 10;
      timeDisp2[2] = second2 / 10;
      timeDisp2[3] = second2 % 10;
      tm1637c.display(timeDisp2);
      if (minute2 < accessgame) {
        digitalWrite(LED_jeu2_V, LOW);
        digitalWrite(LED_jeu2_R, HIGH);
      } else {
        digitalWrite(LED_jeu2_V, HIGH);
        digitalWrite(LED_jeu2_R, LOW);
      }
      dismentel2 = 0;
    } else {
        displayb.print("FAIL");
          digitalWrite(LED_jeu2_V, HIGH);
          digitalWrite(LED_jeu2_R, LOW);
          for (; runJEU2 < 1; runJEU2++) {
            squeak();
          }
         fail2 = 1;
    }

  } else if ((dismentel1 == 1 or fail1 == 1)  && dismentel2 == 1){
      displayb.print("-7--");
      digitalWrite(LED_jeu2_V, LOW);
      digitalWrite(LED_jeu2_R, HIGH);
      for (; winJEU2 < 1; winJEU2++) {
        wingame();
       }
       dismentel2 = 1;
  } else {
    displayb.print("----");
      digitalWrite(LED_jeu2_V, HIGH);
      digitalWrite(LED_jeu2_R, HIGH);
      }

// GESTION DU JEU 2 //

// GESTION DU JEU 3 //

  if (readingc == HIGH) {
    dismentel3 = 1;
  }

  if ((dismentel2 == 1 or fail2 == 1) && dismentel3 == 0) {
    countdown3();

    if (second3 > 0 && minute3 >= 0) {
      int8_t timeDisp3[4];
      timeDisp3[0] = minute3 / 10;
      timeDisp3[1] = minute3 % 10;
      timeDisp3[2] = second3 / 10;
      timeDisp3[3] = second3 % 10;
      tm1637d.display(timeDisp3);
      if (minute3 < accessgame) {
        digitalWrite(LED_jeu3_V, LOW);
        digitalWrite(LED_jeu3_R, HIGH);
      } else {
        digitalWrite(LED_jeu3_V, HIGH);
        digitalWrite(LED_jeu3_R, LOW);
      }
      dismentel3 = 0;
    } else {
        displayc.print("FAIL");
          digitalWrite(LED_jeu3_V, HIGH);
          digitalWrite(LED_jeu3_R, LOW);
          for (; runJEU3 < 1; runJEU3++) {
            squeak();
          }
         fail3 = 1;
    }

  } else if ((dismentel2 == 1 or fail2 == 1)  && dismentel3 == 1){
      displayc.print("---1");
      digitalWrite(LED_jeu3_V, LOW);
      digitalWrite(LED_jeu3_R, HIGH);
      for (; winJEU3 < 1; winJEU3++) {
        wingame();
       }
       dismentel3 = 1;
  } else {
    displayc.print("----");
      digitalWrite(LED_jeu3_V, HIGH);
      digitalWrite(LED_jeu3_R, HIGH);
      }

      } else {

second=0; minute=45; hour=0; // déclarer des variables de temps
second1=0; minute1=15; hour1=0; // déclarer des variables de temps
second2=0; minute2=15; hour2=0; // déclarer des variables de temps
second3=0; minute3=15; hour3=0; // déclarer des variables de temps
previousTime = 0;//détient temps précédent en ms
previousTime1 = 0;//détient temps précédent en ms
previousTime2 = 0;//détient temps précédent en ms
previousTime3 = 0;//détient temps précédent en ms
previousDelay = 0;//détient temps précédent en ms depuis buzzer était actif
previousDelay1 = 0;//détient temps précédent en ms depuis buzzer était actif
previousDelay2 = 0;//détient temps précédent en ms depuis buzzer était actif
previousDelay3 = 0;//détient temps précédent en ms depuis buzzer était actif
interval = 60000;//60 secondes de retard
interval1 = 60000;//60 secondes de retard
interval2 = 60000;//60 secondes de retard
interval3 = 60000;//60 secondes de retard
runOPEN = 0;
dismentel1 = 0; fail1 = 0;
dismentel2 = 0; fail2 = 0;
dismentel3 = 0; fail3 = 0;
dismentel4 = 0; fail4 = 0;
    displaya.print("-   ");
    displayd.print("-   ");

      }

}

// GESTION DU JEU 3 //

// VALIDATION GLOBALE PAR DIGICODE //
  char Key;
  byte KState = KP.Key_State();

  if (KState == PRESSED) {
    if ( Key = KP.Getkey() ) {
      Serial << "Pressed: " << Key << "\n";
      switch (Key) {
        case '*': checkPassword(); break;
        case '#': password.reset(); break;
        default: password.append(Key);
      }
    }
  }
  else if (KState == HELD) {
    Serial << "Key:" << KP.Getkey() << " being held\n";
  }
// VALIDATION GLOBALE PAR DIGICODE //

};

void beep (int speakerPin, float noteFrequency, long noteDuration)
{
  int x;
  // Convert the frequency to microseconds
  float microsecondsPerWave = 1000000/noteFrequency;
  // Calculate how many HIGH/LOW cycles there are per millisecond
  float millisecondsPerCycle = 1000/(microsecondsPerWave * 2);
  // Multiply noteDuration * number or cycles per millisecond
  float loopTime = noteDuration * millisecondsPerCycle;
  // Play the note for the calculated loopTime.
  for (x=0;x<loopTime;x++)
          {
              digitalWrite(speakerPin,HIGH);
              delayMicroseconds(microsecondsPerWave);
              digitalWrite(speakerPin,LOW);
              delayMicroseconds(microsecondsPerWave);
          }
}

void waka() {
  for (int i=1000; i<3000; i=i*1.05) {
    beep(speakerPin,i,10);
  }
  delay(100);
  for (int i=2000; i>1000; i=i*.95) {
    beep(speakerPin,i,10);
  }
    for (int i=1000; i<3000; i=i*1.05) {
    beep(speakerPin,i,10);
  }
  delay(100);
  for (int i=2000; i>1000; i=i*.95) {
    beep(speakerPin,i,10);
  }
    for (int i=1000; i<3000; i=i*1.05) {
    beep(speakerPin,i,10);
  }
  delay(100);
  for (int i=2000; i>1000; i=i*.95) {
    beep(speakerPin,i,10);
  }
    for (int i=1000; i<3000; i=i*1.05) {
    beep(speakerPin,i,10);
  }
  delay(100);

            beep(speakerPin, note_Bb5,300); //B b
          delay(50);
          beep(speakerPin, note_C6,300); //C
          delay(50);
          beep(speakerPin, note_Ab5,300); //A b
          delay(50);
          beep(speakerPin, note_Ab4,300); //A b
          delay(50);
          beep(speakerPin, note_Eb5,500); //E b
          delay(500);
}

void squeak() {
//  for (int i=100; i<5000; i=i*1.45) {
//    beep(speakerPin,i,60);
//  }
//  delay(10);
  for (int i=3500; i>10; i=i/1.15) {
    beep(speakerPin,i,60);
  }
}
void wingame() {
  for (int i=100; i<5000; i=i*1.45) {
    beep(speakerPin,i,60);
  }

}

void uhoh() {
  for (int i=1000; i<2000; i=i*1.10) {
    beep(speakerPin,i,10);
  }
  delay(50);
  for (int i=1000; i>500; i=i*.90) {
    beep(speakerPin,i,10);
  }
  delay(50);
  for (int i=1000; i<2000; i=i*1.10) {
    beep(speakerPin,i,10);
  }
  delay(50);
  for (int i=1000; i>500; i=i*.90) {
    beep(speakerPin,i,10);
  }
  delay(50);
    for (int i=1000; i<2000; i=i*1.10) {
    beep(speakerPin,i,10);
  }
  delay(50);
  for (int i=1000; i>500; i=i*.90) {
    beep(speakerPin,i,10);
  }
  delay(50);
    for (int i=1000; i<2000; i=i*1.10) {
    beep(speakerPin,i,10);
  }
  delay(50);
  for (int i=1000; i>500; i=i*.90) {
    beep(speakerPin,i,10);
  }
  delay(50);
    for (int i=1000; i<5000; i=i*1.05) {
    beep(speakerPin,i,10);
  }
 delay(300);

  for (int i=1000; i<3000; i=i*1.03) {
    beep(speakerPin,i,10);
  }
  for (int i=3000; i>1000; i=i*.97) {
    beep(speakerPin,i,10);
  }
}

void checkPassword()
{
  if (password.evaluate()) {
    Serial.println("Success");
    runcode = 1;
    displayd.print(" YOU");
    displayd.print(" YOU");
    displaya.print(" ARE");
    displaya.print(" ARE");
    displayb.print(" THE");
    displayb.print(" THE");
    displayc.print("BEST");
    displayc.print("BEST");
    digitalWrite(LED_jglobal4, HIGH);

    for (; winGLOBAL < 1; winGLOBAL++) {
      waka();
     }
    password.reset();
  } else {
    Serial.println("Wrong");
    password.reset();

    for (; looseGLOBAL < 1; looseGLOBAL++) {
    squeak();
    looseGLOBAL = 0;
    }

  }
}
/**********************************************************************
 *                        GLOBAL                                      *
 **********************************************************************/
void countdown(){

 static unsigned long lastTick = 0; // mettre en place une variable locale pour maintenir la dernière fois que nous décrémentés une seconde
  static unsigned long currentMillis = 0;
  // (variables statiques sont initialisées une fois et conservent leurs valeurs entre les appels de fonction)
  // diminuer à une seconde tous 1000 millisecondes
  if (second > 0) {
    if (millis() - lastTick >= 1000) {
      lastTick = millis();
      second--;

      int8_t timeDisp[4];
      timeDisp[0] = minute / 10;
      timeDisp[1] = minute % 10;
      timeDisp[2] = second / 10;
      timeDisp[3] = second % 10;
      tm1637a.display(timeDisp);
      tm1637a.point(POINT_ON);

    }
  } else {
       displayd.print("FAIL");
      for (; runFAILGLOBAL < 1; runFAILGLOBAL++) {
          squeak();
      }
  }
 // décrémenter une minute toutes les 60 secondes
  if (minute > 0) {
    if (second <= 0) {
      minute--;
      second = 60; // remettre les secondes à 60
    }
  }
  // décrémenter une heure tous les 60 minutes
  if (hour > 0) {
    if (minute <= 0) {
      hour--;
      minute = 60; // réinitialiser minutes à 60
    }//closes if
  }//closes if

  //le code ci-dessous bips de la sirène une fois par minute.
  currentMillis = millis();
  if (currentMillis - previousTime > interval)
  {
    previousTime = currentMillis;
    previousDelay = currentMillis;
  }

  if (currentMillis - previousDelay > 100) {//100ms durée de chirp
  }
} //close countdown();

/**********************************************************************
 *                        JEU1                                        *
 **********************************************************************/
void countdown1(){

 static unsigned long lastTick1 = 0; // mettre en place une variable locale pour maintenir la dernière fois que nous décrémentés une seconde
  static unsigned long currentMillis1 = 0;
  // (variables statiques sont initialisées une fois et conservent leurs valeurs entre les appels de fonction)
  // diminuer à une seconde tous 1000 millisecondes
  if (second1 > 0) {
    if (millis() - lastTick1 >= 1000) {
      lastTick1 = millis();
      second1--;

    }
  }
 // décrémenter une minute toutes les 60 secondes
  if (minute1 > 0) {
    if (second1 <= 0) {
      minute1--;
      second1 = 60; // remettre les secondes à 60
    }
  }
  // décrémenter une heure tous les 60 minutes
  if (hour1 > 0) {
    if (minute1 <= 0) {
      hour1--;
      minute1 = 60; // réinitialiser minutes à 60
    }//closes if
  }//closes if

  //le code ci-dessous bips de la sirène une fois par minute.
  currentMillis1 = millis();
  if (currentMillis1 - previousTime1 > interval1)
  {
    previousTime1 = currentMillis1;
    previousDelay1 = currentMillis1;
  }

  if (currentMillis1 - previousDelay1 > 100) {//100ms durée de chirp
  }

} //close countdown1();

/**********************************************************************
 *                        JEU2                                        *
 **********************************************************************/
void countdown2(){

 static unsigned long lastTick2 = 0; // mettre en place une variable locale pour maintenir la dernière fois que nous décrémentés une seconde
  static unsigned long currentMillis2 = 0;
  // (variables statiques sont initialisées une fois et conservent leurs valeurs entre les appels de fonction)
  // diminuer à une seconde tous 1000 millisecondes
  if (second2 > 0) {
    if (millis() - lastTick2 >= 1000) {
      lastTick2 = millis();
      second2--;
    }
  }
 // décrémenter une minute toutes les 60 secondes
  if (minute2 > 0) {
    if (second2 <= 0) {
      minute2--;
      second2 = 60; // remettre les secondes à 60
    }
  }
  // décrémenter une heure tous les 60 minutes
  if (hour2 > 0) {
    if (minute2 <= 0) {
      hour2--;
      minute2 = 60; // réinitialiser minutes à 60
    }//closes if
  }//closes if

  //le code ci-dessous bips de la sirène une fois par minute.
  currentMillis2 = millis();
  if (currentMillis2 - previousTime2 > interval1)
  {
    previousTime2 = currentMillis2;
    previousDelay2 = currentMillis2;
  }

  if (currentMillis2 - previousDelay2 > 100) {//100ms durée de chirp
  }

} //close countdown2();

/**********************************************************************
 *                        JEU3                                        *
 **********************************************************************/
void countdown3(){

 static unsigned long lastTick3 = 0; // mettre en place une variable locale pour maintenir la dernière fois que nous décrémentés une seconde
  static unsigned long currentMillis3 = 0;
  // (variables statiques sont initialisées une fois et conservent leurs valeurs entre les appels de fonction)
  // diminuer à une seconde tous 1000 millisecondes
  if (second3 > 0) {
    if (millis() - lastTick3 >= 1000) {
      lastTick3 = millis();
      second3--;

    }
  }
 // décrémenter une minute toutes les 60 secondes
  if (minute3 > 0) {
    if (second3 <= 0) {
      minute3--;
      second3 = 60; // remettre les secondes à 60
    }
  }
  // décrémenter une heure tous les 60 minutes
  if (hour3 > 0) {
    if (minute3 <= 0) {
      hour3--;
      minute3 = 60; // réinitialiser minutes à 60
    }//closes if
  }//closes if

  //le code ci-dessous bips de la sirène une fois par minute.
  currentMillis3 = millis();
  if (currentMillis3 - previousTime3 > interval1)
  {
    previousTime3 = currentMillis3;
    previousDelay3 = currentMillis3;
  }

  if (currentMillis3 - previousDelay3 > 100) {//100ms durée de chirp
  }
} //close countdown2();

That code is a mess. I'm sure you can refactor a lot of it. To get you started here's a C++ class you can use as a countdown timer. I just whipped this up, but it should work. However, it does not handle the case where millis() overflows (after about 50 days).
class Countdown {
public:
    const uint32_t ms_per_hour = 60l * 60l * 1000l;
    const uint32_t ms_per_minute = 60l * 1000l;
    const uint32_t ms_per_second = 1000l;

    // Constructor
    Countdown(int hours, int minutes, int seconds) {
        duration = hours * ms_per_hour +
                   minutes * ms_per_minute  +
                   seconds * ms_per_second ;
        started = false;
        finished = false;
    }
    // Call this to start the countdown
    void start() {
        started = true;
        finished = false;
        start_time = millis();
    }

    // Stop the timer
    void stop() {
        finished = true;
    }

    // Is timer running?
    bool is_running() {
        return started == true && finished == false;
    }

    // Call this to check if the countdown is finished
    bool times_up() {
        if (finished) return true;
        else if (!started) return false;
        if (elapsed_time() >= duration) {
            finished = true;
            return true;
        }
        return false;
    }

    // Returns a string representation of how much time has passed
    const char * get_elapsed(const char *format="hh:mm:ss") {
        return ms_to_string(format, elapsed_time());
    }
    // Returns a string representation of how much time is left
    const char * get_remaining(const char *format="hh:mm:ss") {
        return ms_to_string(format, duration - elapsed_time());
    }

    // Returns an array of decimal digits for display of time passed
    const char * get_digits_elapsed(const char *format="mmss") {
        return ms_to_digits(format, elapsed_time());
    }
    // Returns an array of decimal digits for display of time remaining
    const char * get_digits_remaining(const char *format="mmss") {
        return ms_to_digits(format, duration - elapsed_time());
    }

protected:
    unsigned long elapsed_time() {
        return millis() - start_time;
    }

    bool started, finished;
    uint32_t duration, start_time;
    char buffer[32];

    char * ms_to_digits(const char *format, uint32_t ms) {
        uint16_t hours = ms / ms_per_hour;
        ms %= ms_per_hour;
        uint16_t minutes = ms / ms_per_minute;
        ms %= ms_per_minute;
        uint16_t seconds= ms / ms_per_second;

        int index = 0;
        for (int i = 0; 0 != format[i]; i++) {
            if ('h' == format[i] || 'm' == format[i] || 's' == format[i]) {
                uint16_t val = 'h' == format[i] ? hours : ('m' == format[i] ? minutes : seconds);
                if (format[i] == format[i+1]) {
                    buffer[index++] = (char)(val / 10);
                    i += 1;
                }
                buffer[index++] = char(val % 10);
            }
        }
        return buffer;
    }

    char * ms_to_string(const char *format, uint32_t ms) {
        uint16_t hours = ms / ms_per_hour;
        ms %= ms_per_hour;
        uint16_t minutes = ms / ms_per_minute;
        ms %= ms_per_minute;
        uint16_t seconds= ms / ms_per_second;

        buffer[0] = 0;
        int index = 0;
        for (int i = 0; 0 != format[i]; i++) {
            if ('h' == format[i] || 'm' == format[i] || 's' == format[i]) {
                uint16_t val = 'h' == format[i] ? hours : ('m' == format[i] ? minutes : seconds);
                if (format[i] == format[i+1]) {
                    index += sprintf(&buffer[index], "%02d", val);
                    i += 1;
                }
                else {
                  index += sprintf(&buffer[index], "%d", val);
                }
            }
            else {
                buffer[index++] = format[i];
            }
        }
        buffer[index] = '\0';
        return buffer;
    }
};

To use it, you would create 3 objects:
Countdown cd1(0, 45, 0);  // 45 minutes
Countdown cd2(0, 15, 0);  // 15 minutes
Countdown cd3(0, 15, 0);  // 15 minutes

Then, start #1 in setup:
void setup() {
    cd1.start();
}

And in loop:
void loop() {
    if (cd3.times_up()) {
       // game over
    }
    else if (cd2.times_up()) {
        // 2nd timer expired, do something
        if (!cd3.is_running()) cd3.start();  // Start #3
        // update display
        tm1637d.display(c3.get_digits_remaining());
    }
    else if (cd1.times_up()) {
        // 1st timer expired, do something
        if (!cd2.is_running()) cd2.start();  // Start #2
        // update display
        tm1637c.display(c2.get_digits_remaining());
    }
    else {
        // update display
        tm1637b.display(c1.get_digits_remaining());
    }
}

You wrote: “it does not handle the case where millis() overflows”. Your code handles the millis() rollover perfectly fine.

@EdgarBonet Ah, yes. You are right. Thanks for pointing that out.

Thank you for you answer. I understand your code, but i don't know how to show countdown on the 4 digit display with that code.

And also how to stop a countdown with a   if (reading == LOW) but i'm going to try. Thank you !

@Fluti Ok, I added a function to return the time as an array of digits. Also, added a stop() function.


text:
compiler says I have to declare my hexidacimal I try to compare
#include <IRremote.h>

int RECV_PIN = 11; // IR Receiver - Arduino Pin Number 11
IRrecv irrecv(RECV_PIN);
decode_results results;

int led = 12;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if(irrecv.decode(&results)) //this checks to see if a code has been received
{
    if(results.value == FF6897) //if the button press equals the hex value FF6897
    {
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);               // wait for a second
        digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);               // wait for a second//do something useful here
    }
    irrecv.resume(); //receive the next value
}
  }

The issue is in the second if in the void loop the error I get is

exit status 1 'FF6897' was not declared in this scope

why does he do this? Why doesnt it just accept my IRcode for comparison.

I think this is a good question, because it isn't obvious why its failing unless you know C/C++, the numbering prefix is not intuitive.  Maybe a little research before asking would have helped, but...

Nothing here that hasn't been covered in comments already but just putting it in the form of an answer to save digging...
How is the compiler supposed to know that a number is hex rather than decimal?
Sure 1234beef is obviously hex but what about 12345678? Is that hex or decimal?
You need some method for the compiler to know.
You also need some way for the compiler to know if something is a number or a variable. Take the code if (x == deadbeef) {...} is deadbeef a hex number or a variable name?
C uses a very simple convention. If it starts with a number it's a number, if it starts with a letter it's a variable. This is why variable names can contain numbers but can't start with them.
If an integer starts with an 0 e.g. 0123 then it's in octal.
If an integer starts with 0x e.g. 0x123 then it's in hex.
If an integer starts with something other than a 0 e.g. 123 then its in decimal.

e.g.
printf("123 = %d\r\n0x123 = %d\r\n0123 = %d\r\n", 123 , 0x123 , 0123);

returns
123 = 123
0x123 = 291
0123 = 83

This convention, especially the 0x prefix for hexadecimal, is very widely used in other programming languages.

By comparing my code to another one, I found out that putting 0x in front of the hex will fix it, I don't have a clue why this is though.

Hexadecimal literals are typically preceded by 0x, else how would the compiler distinguish the variable name deadbeef from the hexadecimal value deadbeef?

There is also the prefix 0 and b for declaring Octal (base 8) and binary.  Octal can cause you issues when declaring decimal numbers that you want to pad with zeros, i.e. 00100 is 64 not 100 with to leading zeros.

@CodeGorilla the 0b prefix for binary isn't very standard yet. I believe C++ 14 makes it standard but c++ 11 is only just becoming common so that's at least a few years off general usage. Until then its down to individual compilers and extensions whether it's supported. Personally right now I'd avoid it even if the tool I was using supported it, the lack of portability isn't worth the minimal benefits it gives.

@Andrew - The only place I had seen it was here :)  I agree about avoiding binary, but mainly because hex is much easier.