maker/arduino/ SerialCommunication


Example Arduino code

typedef uint8_t Byte;
typedef uint32_t Word;

Word x;

void setup() {
  x = 0;
  Serial.begin(256000);
}

void loop() {
  Byte cmd = ( x & 0x7F ) | 0x80; // example data
  Byte a = (x >> 3) & 0x7F;
  Byte b = (x >> 5) & 0x7F;
  Byte msg[4];
  msg[0] = cmd;
  msg[1] = a;
  msg[2] = b;
  msg[3] = 0xff;
  Serial.write(msg,4);

  x++;
  delay(250);
}

Example python code

#!/usr/bin/env python
import serial
from time import sleep
import sys


#COM = 'COM3'# windows non cygwin
#COM = '/dev/ttyACM0' # Linux
#COM = '/dev/ttyS2' # cygwin
COM = '/dev/tty.usbserial-1460' # mac

#BAUD = 9600
BAUD = 256000 # fine over a USB cable

ser = serial.Serial(COM, BAUD, timeout = .1)

print('Waiting for device');
sleep(3)
print(ser.name)

#check args
if("-m" in sys.argv or "--monitor" in sys.argv):
    monitor = True
else:
    monitor= False

def msg_to_hex(msg):
  h = [f"{x:02x}" for x in msg]
  return ".".join(h)

buf = []
while True:
  b = ser.read(1)
  if len(b) == 0:
    continue
  x = b[0]
  if x == 0xff:
    print(f"Message: {msg_to_hex(buf)}")
    buf = []
  elif x >= 0x80:
    if len(buf) > 0:
      print(f"Incomplete messsage: {msg_to_hex(buf)}")
    buf = [x]
  else:
    buf += [x]