perjantai 15. helmikuuta 2013

Reading and writing serial ports with python

Today we had to find information how to read information from serialport with computer. First we write a simple program for arduino which prints something for serial monitor:


void setup()
{
  Serial.begin(115200);
  Serial.println("Foo bar");
}

void loop()
{
  Serial.println("Moi");
  delay(500); //ms
}

This prints to arduino serial monitor, first "Foo bar" only once, and then "Moi" always after 0,5 seconds.


Then we want to read that from usb port. You must have permissions to read from serial port. Example sudo chmod 777 /dev/ttyACM0 (see the right port from arduino ide.

Create a new file in linux: cat > read.py
open it with text-editor, i used nano: nano read.py

Then we write a simple python program to read that from usb port (copy this code and also remember to indent the code for if and while parts.):


import serial, sys

ser = serial.Serial("/dev/ttyACM0", 115200)

if (ser):
print("Serial port " + ser.portstr+ " opened.")

while True:
sys.stdout.write(ser.read(1) )
sys.stdout.flush()

Then open the file in terminal: python read.py
And we can see it prints that program written for arduino.


And if you want to write something, just add this line
ser.write ('5')

Ei kommentteja:

Lähetä kommentti