I'm trying to get my Raspberry Pi/Node.js to communicate with an Arduino Uno using node-serialport. I'm having trouble with the following block of code:
Raspberry Pi
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort("/dev/ttyACM0", {
baudrate: 9600
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write(new Buffer('4','ascii'), function(err, results) {
console.log('err ' + err);
console.log('results ' + results);
});
});
Arduino
// LED on pin 12
int led = 12;
// Incoming serial data
int data=0;
void setup() {
// Pin 12 set to OUTPUT
pinMode(led, OUTPUT);
// Start listening on the serialport
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0){
// Read from serialport
data = Serial.read();
// Check and see if data received == 4
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);
}
// Reset data to 0
data=0;
}
}
}
I am only able to get the Arduino to blink the LED if I wrap a for loop around the serialPort.write() function. At the 40th loop iteration or so the LED finally starts blinking and will continue blinking until serialPort.write() loop is finished. This leads me to believe that I'm encountering some sort of timing issue. I'm looking for a more elegent (and non-blocking) solution to blinking the LED on the Arduino via the Pi. Any help would be greatly appreciated.
Thanks! Bobby