Loading [MathJax]/extensions/MathZoom.js

Monday, 20 July 2015

Communicating with the Arduino

After connecting the Raspberry Pi to the Arduino, the next step was to communicate with it programmatically rather than simply uploading sketches.

As a first attempt I decided to try using Nanpy. This is a library that allows you to drive the Arduino from the Raspberry Pi using Python scripts. The version I tried to install was v0.94.

This wasn't successful. When I ran a simple script to blink the on-board LED on the Arduino I got the following error:

nanpy.serialmanager.SerialManagerError: Serial timeout

I edited the Nanpy sketch to enable some basic "Logging", again using the LED. This resulted in the discovery that the serial communications were not being set-up correctly. In particular:

if (ComChannel::available()))

was not evaluating to true.

I wasn't able to discover why so I've decided to park Nanpy for the time-being. If I get it working then I'll post full details for setting it up.

But there are always many ways to solve a problem in computing, without even harming any cats! I checked serial communication was working by running the ASCIITable example sketch on the Arduino IDA and viewing data in the Serial Monitor. This was OK, so I could try writing some code to simply switch on the on-board LED using Python.

I uploaded this sketch to the Arduino

// SerialTest
byte inByte;

void setup() {
   // initialise serial comms at 9600 baud
   Serial.begin(9600);
   pinMode(13,OUTPUT);

   // The on-board LED is explicitly off. 
   digitalWrite(13, LOW);
}

void loop() {
  while (Serial.available() > 0)
  {
     inByte = Serial.read();
     // If the byte is a digit in the range 0-9, light the LED
     // otherwise, turn it off
     if (inByte > 47 && inByte < 58)
     {
         digitalWrite(13, HIGH); 
     }
     else
     {
        digitalWrite(13, LOW);
     }
  }
}

Finally I wrote a very simple python script to write characters to the serial port. This should wait 5 seconds, turn on the LED, wait 5 seconds and turn off the LED, and repeat.

from time import sleep
import serial
arduino = serial.Serial('/dev/ttyUSB0')

sleep(5)
arduino.write('5')
sleep(5)
arduino.write('x')
sleep(5)
arduino.write('2')
sleep(5)
arduino.write('x')

I ran the script and the LED turned on and off as expected.

No comments:

Post a Comment