Weird formatting behavior with sprintf function I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.

But that line:

sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));


returns something like this:

3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)


It's suppose to return something like this:

3000;110;291;263;230;0;0;245


Here is my sketch:

int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;

volatile boolean interruptFlag = 0;
char read[45];
char signal[2048];
volatile int count = 0;
volatile long x = 0;

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

  noInterrupts(); // Stop interrupts.

  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.

  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be &lt;65536)

  // Turn on CTC mode.
  TCCR1B |= (1 &lt;&lt; WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 &lt;&lt; CS12) | (1 &lt;&lt; CS11) | (1 &lt;&lt; CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 &lt;&lt; OCIE1A);

  interrupts(); // Allow interrupts.  
}

ISR(TIMER1_COMPA_vect){    
  if (!interruptFlag){  
    interruptFlag = 1;    
  }  
}

void loop() {
  if (interruptFlag){    
    writeAnalogSignals();
    count++; 
    interruptFlag = 0;     
  }     
}

void writeAnalogSignals() { 
  if (strlen(read) == 0) {
    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  } else {
    sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  }
  strcat(signal, read);

  x += 2;  

  if (count &gt;= 50) {
    Serial.print(signal);
    signal[0] = 0;
    count = 0;    
  }  
}
Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.

When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.

For a data rate of 50Hz, I suggest to raise the baudrate to 115200.

Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt.
See the BlinkWithouDelay example and use 20ms as an interval.