I recently flashed bootloader of Arduino to Atmega8. Unfortunately I stumbled on a problem I can't solved.
I am testing SerialEvent example on Atmega8. I modified it but started debugging it on my code (I think the same problem stops SerialEvent example from working).
I think the Atmega8 reads the characters sent through serial wrongly. That's why SerialEvent 'if' condition doesn't work also. Because it never gets '\n' symbol (it receives it but wrongly interprets it).
boolean prevState = true;
boolean OnOff = false;
boolean stringComplete = false;
String inputString = "";
String OnString = "on\n";
String OffString = "off\n";
void setup() {
Serial.begin(1200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// reserve 200 bytes for the inputString
inputString.reserve(200);
DDRD |= 0b00001100;
PORTD |= _BV(PD2);
// synchronization info for RPi
Serial.println("ARD - OK\n");
}
void loop() {
// turn on
if (OnOff == true && prevState == false){
PORTD |= _BV(PD2);
prevState = OnOff;
}
// turn off
if (OnOff == false && prevState == true){
PORTD &= ~_BV(PD2);
prevState = OnOff;
}
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
Serial.println(inputString);
if (inChar == '\n') {
stringComplete = true;
Serial.println("test\n");
}
if (stringComplete && inputString.equals(OnString)){
OnOff = true;
Serial.println("Turning on.\n");
}
else if (stringComplete && inputString.equals(OffString)){
OnOff = false;
Serial.println("Turning off.\n");
}
}
}
I tested a lot of behaviors. Below I attach one of the tests from Realterm:
First I reset the board - it responded with 'ARD - OK\n' - expected behavior. Then I sent 'on\n' and it responded with two lines but the characters aren't the same as 'on\n'. Then I sent 'test123\n' but once again got wrong characters. It prints multiple lines because it sends the string in which it accumulates the data every time SerialEvent() is fired.
Also sending for example variabl OnString works ok.
I really don't know why is it acting like that... Help would be appreciated :).
void loop(){if(Serial.available()) Serial.write(Serial.read());}
. – Edgar Bonet Jul 12 '16 at 15:13