arduino and pyserial

At the moment the only thing that separates your numbers is comma, yuo extract a number like this you read the serial port one bit at a time until you find a comma, that marks the end of your last number. Then you gather bytes into a list until you get another comma, don’t add that to the list. Then you convert each byte from the character into a number with an (ord(data[0]).
For each successive number you then multiply the previous number by ten and add the next byte to it.

Bottom line is you have to think about what data format you are sending and how you communicate with the arduino.

This bit of code I used to get two 16 bit ints from the arduino. Each byte was tagged with a unique top two bits so I could identify them.

def openPort():
       global running
       # tell the arduino to start sending
       running = True
def checkInput(b): # see if the bytes have been received in the correct order
       correct = True
       for i in range(0,4):
            #print i," - " # ,hex(ord(b[i]))
            if (ord(b[i]) >> 6) != i :
               correct = False
       return correct
def getData():
   global reading, running
   if running :     
        a =        
        if checkInput(a) :
            reading[0] = ((ord(a[0]) & 0x1f)<< 5) | (ord(a[1]) &0x1f)
            reading[1] = ((ord(a[2]) & 0x1f)<<5) | (ord(a[3]) &0x1f)
            #print reading[0]," - ",reading[1]
            correct = False
            while correct == False : # resyncronise 
                print "lost sync ",ser.inWaiting()
                b =
                t = a[1] + a[2] + a[3] + b[0]
                a = t
                correct = checkInput(a)

The code is from my book:-
Which describes both the arduino code and the python code. You should be able to down load both from the book’s web site.
It is chapter 16.

Would you recommend breaking the numbers down before sending them?

You have no choice the numbers are sent only one byte at a time by the hardware so they are broken down.

The demo I linked to in Reply #9 works in both directions. Have you got that to work?

This newer demo shows how you can send binary data from Python to the Arduino. The same concept could also be used in reverse.


I would be testing out my code but i keep getting this error when attempting to import pyserial:

Traceback (most recent call last):
File “<blender_console>”, line 1, in
File “C:\Python33\”, line 19, in
from serial.serialwin32 import *
File “C:\Python33\serial\”, line 12, in
from serial import win32
File “C:\Python33\serial\”, line 196
MAXDWORD = 4294967295L # Variable c_uint
SyntaxError: invalid syntax

I give up.


That looks like a windows problem. Unfortunately for you I have only used Python under Linux.