1

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

2
  • Does Serial.print() perform an ASCII conversion (itoa or similar) or is it sending the number back out as binary? If the AVR receives the bytes backwards then transmits them back to your computer reversed again, it would look alright... Commented Aug 19, 2010 at 3:38
  • In Arduino, you can specify how it sends it back, in my case I am sending it back as a decimal (see the second parameter, DEC). Serial.print(val, DEC); // send to python to check Commented Aug 21, 2010 at 22:58

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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;-).

1 Comment

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.
0

Way easier :

  crc_out = binascii.crc32(data_out) & 0xffffffff   # create unsigned long
  print "crc bytes written",arduino.write(struct.pack('<L', crc_out)) #L, I whatever u like to use just use 4 bytes value

  unsigned long crc_python = 0;
  for(uint8_t i=0;i<4;i++){        
    crc_python |= ((long) Serial.read() << (i*8));
  }

No union needed and short !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.