Listen to arduino from linux

From wikiluntti

Introduction

Theory

Arduino using USB cable is either

  • /dev/ttyUSBx
  • /dev/ttyACMx
> ls -l /dev/ttyACM*

crw-rw---- 1 root uucp 166, 0 Mar 25 20:16 /dev/ttyACM0

Set the permissions:

  • sudo usermod -a -G uucp


Screen command: Install screen and use it it:

screen /dev/ttyACM0 9600
  • Ctrl+a and k will kill a screen session

Python.

import time
import serial

ardu=serial.Serial('/dev/ttyACM0',9600, timeout=.1)
time.sleep(1)
while True:
    line = ardu.readline()
    if len( line ) > 1:
        print( line )

Windows + python

The program reads four (4) data separated by commas and prints them.

import time
import serial

ardu=serial.Serial('COM10',115200, timeout=.1)
time.sleep(1)
while True:
    line = ardu.readline()
    if len( line ) > 1:
        s = ( line.decode('utf-8'))

        x = s.split(",")
        r = float(x[0])
        ax = float(x[1])
        ay = float(x[2])
        az = float(x[3])

        print( r, ax, ay, az)

Read and write to a file

Append to the. Also add the current time stamp. The program reads variables (multiplied by 10) from Serial port, divides them by ten and writes those as csv file. There is one last extra comma, but perhaps it doesn't matter.

The code doesn't start if the serial data is on a wrong position.

import time
import serial
import datetime

f = open("demofile.txt", "w+")

ardu=serial.Serial('COM6',9600, timeout=.1)
time.sleep(1)
while True:
    line = ardu.readline()
    if len( line ) > 1:
        s = ( line.decode('utf-8'))
        
        x = s.split(",")
        if len(x)>1:
        
            d = []
            f.write( str( datetime.datetime.now() ))
            f.write(", ")
            for i, data in enumerate(x):
                f.write( str( float(data)/10 ))
                f.write(", ")
                d.append( float(data)/10 )
            f.write("\n")
            print( d )

References