tags:

views:

146

answers:

2

I need to send integers greater than 255? Does anyone know how to do this?

+2  A: 

Encode them into binary strings with Python's struct module. I don't know if arduino wants them little-endian or big-endian, but, if its docs aren't clear about this, a little experiment should easily settle the question;-).

Alex Martelli
Note: Arduino is little endian. You can swap endianess using struct module, I didn't have to though. Just for the record, I was on intel x86 mac osx 10.6.4. python 2.6.1, 64 bit.
toddstavish
A: 

Here's how (Thanks for the idea, Alex!):

Python:

def packIntegerAsULong(value):
    """Packs a python 4 byte unsigned integer to an arduino unsigned long"""
    return struct.pack('I', value)    #should check bounds

# To see what it looks like on python side
val = 15000
print binascii.hexlify(port.packIntegerAsULong(val))

# send and receive via pyserial
ser = serial.Serial(serialport, bps, timeout=1)
ser.write(packIntegerAsULong(val))
line = ser.readLine()
print line

Arduino:

unsigned long readULongFromBytes() {
  union u_tag {
    byte b[4];
    unsigned long ulval;
  } u;
  u.b[0] = Serial.read();
  u.b[1] = Serial.read();
  u.b[2] = Serial.read();
  u.b[3] = Serial.read();
  return u.ulval;
}
unsigned long val = readULongFromBytes();
Serial.print(val, DEC); // send to python to check
toddstavish