I want to create a simple program, that responds to me sending a character over the Arduino IDE console. I am using an arduino UNO. Here is my program:
volatile bool MeasReceived=false;
ISR(PCINT2_vect){
PCICR = 0b00000000; // turn off port d
MeasReceived=true;
}
void setup() {
Serial.begin(9600);
Serial.flush();
Serial.print("Hello PC");
delay(1000);
cli();
PCICR |= 0b00000100; // turn on port d
PCMSK2 |= 0b0000001; // turn on pins PD0 , PCINT16
sei();
}
void loop() {
if(MeasReceived==true){
MeasReceived=false;
inByte = Serial.read();
if(inByte=='A'){ //A: PC requests measurement data from Arduino
Serial.print('B');
}
else{
Serial.print(inByte);
}
}
PCICR = 0b00000001; // re-enable port d
}
What I do is that I set the RX pin as a pin change interrupt. After that, I send a character through the console, for example 'A'. The ISR kicks in, firstly disabling the interrupt, and after that, the flag is set true. That way, I enter the part of the code where I do the Serial.read() command, to find what character was sent to me via the console.
The problem is that, no matter the character I send, the result is always 255. That means that the value of inByte, after the Serial.read() is always 255. What goes wrong?
EDIT: Original question answered by me below. However, one interesting thing occured in the new code posted below. If I put the Arduino to sleep (powerDown Mode), and try to wake it up with the serial interrupt, if I send only one character, then the arduino does wake up, but does not enter the ISR! If I send two characters, then the ISR is accessed and the flags set, with the program working fine. Here is the code, to reproduce the issue:
volatile bool MeasReceived=false;
uint8_t inByte;
ISR(PCINT2_vect){
PCMSK2 = 0b00000000; // turn off port d
MeasReceived=true;
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
Serial.flush();
Serial.print("Hello PC");
delay(1000);
cli();
PCICR = 0b00000100; // turn on port d
PCMSK2 = 0b00000001; // turn on pins PD0 , PCINT16
sei();
}
void loop() {
if(MeasReceived==true){
MeasReceived=false;
delay(2000);
inByte = Serial.read();
if(inByte=='A'){ //A: PC requests measurement data from Arduino
Serial.print('B');
}
else{
Serial.print(inByte);
}
PCMSK2 = 0b00000001;
}
set_sleep_mode(SLEEP_MODE_PWR_DOWN); //Set power down mode
sleep_bod_disable(); //disable brown-out detection
digitalWrite(LED_BUILTIN, LOW);
sleep_enable();
sleep_cpu();
sleep_disable();
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
//int i=Serial.available();
//Serial.print(i);
delay(1000);
}
So, by sending one character, the Arduino wakes up, the LED shines, and after the two seconds, Arduino goes back to sleep, never entering the ISR and as a result not setting the flag. Furthermore, having sent one character, if I uncomment the Serial.available() printing, it prints "0"!
If I send two characters, the Arduino wakes up, and the program works fine.