Advertisement
Guest User

STM32 uart communication

a guest
Dec 12th, 2019
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import serial
  4. import time
  5. import itertools
  6. import operator
  7.  
  8. from binascii import hexlify
  9.  
  10. NACK = b'\x1f'
  11. ACK = b'\x79'
  12.  
  13. def hex_spaced(bin_str):
  14.     return " ".join(hex(b) for b in bin_str)
  15.  
  16. def select_UART(ser):
  17.     ser.write(b"\x7f") # Select UART
  18.     ack = ser.read()          # read one byte
  19.     print("(N)ACK: ",ack)
  20.  
  21.     if ack == ACK:
  22.         print("UART selection ACKed")
  23.     else:
  24.         raise RuntimeError("UART select failed")
  25.  
  26. def send_command(ser, cmd_bin, expected=None):
  27.     #line = ser.readline()   # read a '\n' terminated line
  28.     xor_byte = bytes(itertools.accumulate(cmd_bin, operator.xor))[-1:]
  29.     print("XOR checksum:", xor_byte)
  30.     ser.write(cmd_bin + xor_byte) # Get
  31.     time.sleep(0.1)
  32.     ack = ser.read(1)[0]
  33.     if (ack == ord(ACK)):
  34.         print("Command Acked")
  35.     elif (ack == ord(NACK)):
  36.         print("Command Nacked")
  37.         raise RuntimeError("Command failed")
  38.     else:
  39.         print("dafuq!", ack)
  40.         raise RuntimeError("Command failed")
  41.  
  42.     if expected is None:
  43.         s = ser.read(ser.in_waiting)        # read available bytes
  44.     else:
  45.         s = ser.read(expected-1)
  46.  
  47.     return s
  48.    
  49. def send_command_print(ser, cmd_bin, expected=None):
  50.     s = send_command(ser, cmd_bin, expected)
  51.     print("Result: %d bytes, %s" % (len(s), hex_spaced(s)))
  52.  
  53. with serial.Serial('/dev/ttyACM0', 38400, timeout=None) as ser:
  54.         select_UART(ser)
  55.  
  56.         try:
  57.             s = send_command_print(ser, b"\x00\xff", 15)
  58.             s = send_command_print(ser, b"\x01\xfe")
  59.         except KeyboardInterrupt:
  60.             print("interrupted")
  61.             pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement