For some reason when I loop my code through a separate function the serial port hangs up. The serial connection appears fine when I call cases within the loop but not when I call outside.
I tried to figure out where the problem is and for some reason using the Serial.print(ComControlValue);
and the output is
-1
But the error still persists.
Previous it was this before I changed the baudrate
-b⸮⸮⸮⸮ Waiting for Command
It's not printing out the -1 I'm using as the main case. Could this be the problem?
#include <Wire.h>
/* RPi Army variables */
int RPi[3] = {3,6,9}; // SDA/SCL code names for the different Raspberry pi's
/* Define parameters for computer control */
int ComControlValue = -1;
void setup() {
Serial.begin(115200); // Establish Serial connection to computer
Wire.begin(); // join i2c bus as master
}
void loop() {
switch(ComControlValue){
/* -1 : nothing happened yet */
case -1:
Serial.println("Waiting for Command");
while (Serial.available()==0){}
ComControlValue=Serial.parseInt(); // Pull value from serial port
break;
case 111:
Serial.println("Eat more Toast");
ComControlValue = -1;
break;
case 210:
Sendsignals(RPi[0],333);
Sendsignals(RPi[1],333);
Sendsignals(RPi[2],333);
ComControlValue= -1;
Serial.print(ComControlValue);
break;
}
}
void Sendsignals(int Rpi, int code){
char str[4];
sprintf(str, "%3d\n", code);
Wire.beginTransmission(Rpi); // transmit to device of choice
Wire.write(str); // sends 16 bytes
Wire.endTransmission(); // stop transmitting
}
1 Answer 1
Your str variable in function Sendsignals is short. sprintf writes 5 bytes to it, 3 digits, the \n and terminating zero. The terminating zero is written outside of the allocated array and causes the crash.
-
This causes the serial terminal to disconnect? How to fix? Should I increase the str to 8 bits?Hojo.Timberwolf– Hojo.Timberwolf2018年11月16日 08:47:47 +00:00Commented Nov 16, 2018 at 8:47
-
Thanks. I changed the size of the str to 16 and it fixed the issue.Hojo.Timberwolf– Hojo.Timberwolf2018年11月16日 08:58:59 +00:00Commented Nov 16, 2018 at 8:58
-
str[5] would be enough, if your codes have always 3 digits2018年11月16日 09:07:09 +00:00Commented Nov 16, 2018 at 9:07
Wire
transmission. You should also consider changingsprintf
tosnprintf
- apparently it's more robust against buffer issues, and requires the buffer size to be set manually.break;
when going through my separate function.while (Serial.available()==0){}
blocks the loop