My guess is that new Buffer('4','ascii')
is doing an ASCII string, and not an ASCII character. The difference being that you're not sending 4
, or 44444444…
using your loop but 4\0
or 4\04\04\04\04\04\04\0…
using your loop.
So when you do Serial.available()
, it returns 2, as it got two byte buffered, but you only read one byte. As the buffer of the Arduino is a circular buffer that gets overwritten with new data over time, what can happen is that you're only reading the \0
s, until over time the timings shift and you get to read only the 4
s.
My advice would be to either read as many characters as there is in the buffer, or simply discard invalid reads, as Serial.read()
return -1
when the buffer is empty:
const int led=12;
void setup() {
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Read from serialport
int data = Serial.read();
// Check and see if data received == 4
// and thus discard data==-1 or data==`\0`
if(data=='4') {
// Blink the LED 3 times
for(int i=0;i<3;i++){
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led,LOW);
delay(1000);
}
}
}