Skip to content

sprintf ("%d",...) works faulty for mega2560 #8945

@dsyleixa

Description

@dsyleixa

hello,
building a composed string by integers using sprintf works faulty for the Mega2560.
the same code works correctly for the DUE.

Tested on 2 platforms:
Arduino IDE 1.8.8,(Windows PC), 1.8.9 (RaspberryPi 2v1, Raspbian Stretch)

int32_t i0, i1, i2, i3, i4, i5, i6;             // int (common)

char    mbuf[1024];  // cstring msg buffer


//==================================================================
// setup
//==================================================================
void setup() {
  Serial.begin(115200);
  
  i0=0;
  i1=1;
  i2=-22;
  i3=33;
  i4=-444;
  i5=5555;
  i6= B10101010*256;
  i6+=B10101010;
}


//==================================================================
// loop
//==================================================================

void loop() {
  static bool stringComplete = false;  

  //-------------------------------------------------------------
  // Serial send  
 
  char formatstr[1024];
  strcpy(formatstr, "§");                               // initial key
  strcat(formatstr, "&i0=%d;&i1=%d;&i2=%d;&i3=%d;&i4=%d;&i5=%d;&i6=%d;");

  sprintf(mbuf, formatstr, i0,i1,i2,i3,i4,i5,i6);        
         
  for (int i=0; i<strlen(mbuf); i++ ) Serial.print(mbuf[i]);
  Serial.println();  

  i0++;

  //delay
  delay(1000); 
}

Serial output:

§&i0=0;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=1;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=2;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=3;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=4;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=5;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=6;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=7;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=8;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=9;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=10;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
§&i0=11;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;
...

instead, the correct output is expected to be like the following:

§&i0=0;&i1=1;&i2=-22;&i3=33;&i4=-444;&i5=5555;&i6=43690;
§&i0=1;&i1=1;&i2=-22;&i3=33;&i4=-444;&i5=5555;&i6=43690;
§&i0=2;&i1=1;&i2=-22;&i3=33;&i4=-444;&i5=5555;&i6=43690;
§&i0=3;&i1=1;&i2=-22;&i3=33;&i4=-444;&i5=5555;&i6=43690;
§&i0=4;&i1=1;&i2=-22;&i3=33;&i4=-444;&i5=5555;&i6=43690;
...

as stated, the last output is the correct one produced by a DUE by the same code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type: InvalidOff topic for this repository, or a bug report determined to not actually represent a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions