Strange C++ Arduino serial behavior
I am writing some code for my arduino to print 4 button states and the X,Y coordinates from an analogue joystick and I am having strange behavior.
Here is the code:
int x,y;
x = analogRead(joy_x);
y = analogRead(joy_y);
char* buf = new char[4];
sprintf(buf, "%4d", x);
Serial.print("X:");
Serial.print(buf);
Serial.print(" Y:");
sprintf(buf, "%4d", y);
Serial.println(buf);
int one,two,three,four;
one = digitalRead(touchOne);
two = digitalRead(touchTwo);
three = digitalRead(touchThree);
four = digitalRead(touchFour);
// create an array of states set to the default values
char states[4] = {'X', 'X', 'X', 'X'};
// change each value if it is not in the default state
if(one == 1) states[0] = 'O';
if(two == 1) states[1] = 'O';
if(three == 1) states[2] = 'O';
if(four == 1) states[3] = 'O';
// output the states to the OLED display
//display.print(states);
Serial.print(states);
When it is run the serial output looks like this:
XXXX3X: 515 Y: 520
XXXX3X: 516 Y: 520
XXXX3X: 516 Y: 519
XXXX3X: 516 Y: 520
XXXX3X: 515 Y: 520
XXXX3X: 516 Y: 519
XXXX3X: 516 Y: 520
XXXX3X: 515 Y: 519
XXXX3X: 516 Y: 520
Even though the X, Y should be before the XXXX and the number three appears from nowhere. I hope this mystery can be solved, thanks.
You have several buffer overruns in the code.
char* buf = new char[4];
sprintf(buf, "%4d", x);
...
sprintf(buf, "%4d", y);
This needs room for the null terminator which sprintf
adds.
char* buf = new char[5];
Also easier: there's no need to use the free store here.
char buf[5];
Same kind of thing here:
char states[4] = {'X', 'X', 'X', 'X'};
...
Serial.print(states);
We need to add a null terminator to make it a valid string.
char states[5] = {'X', 'X', 'X', 'X', ' '};
That should take care of the immediate memory issues.
链接地址: http://www.djcxy.com/p/78606.html上一篇: 为什么我得到这个错误?
下一篇: 奇怪的C ++ Arduino串行行为