Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js SerialPort Arduino Timing Issue

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

like image 377
bobbyg603 Avatar asked Jan 01 '26 02:01

bobbyg603


1 Answers

The problem had to do with Arduino's "AutoReset" see more here.

I didn't actually disable autoreset... I went ahead and implemented the code I posted above. I require user interaction to trigger SerialPort.write(). This works as long as there is a few seconds between when the serial connection is opened and the first write.

like image 143
bobbyg603 Avatar answered Jan 02 '26 18:01

bobbyg603



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!