Guest User

Untitled

a guest
Nov 18th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. import serial
  2. ser= serial.serial("COM10", 9600)
  3. ser.write("Hello worldn")
  4. x = ser.readline()
  5. print(x)
  6.  
  7. import serial
  8. ser=serial.serial("COM10", 9600)
  9. while 1:
  10. if ser.inwaiting():
  11. val = ser.readline(ser.inwaiting())
  12. print(val)
  13.  
  14. # On micro
  15. data = b"[Hello,1234]"
  16. serial.write(data)
  17.  
  18. def read_data(ser, buf=b'', callback=None):
  19. if callback is None:
  20. callback = print
  21.  
  22. # Read enough data for a message
  23. buf += ser.read(ser.inwaiting()) # If you are using threading +10 or something so the thread has to wait for more data, this makes the thread sleep and allows the main thread to run.
  24. while b"[" not in buf or b"]" not in buf:
  25. buf += ser.read(ser.inwaiting())
  26.  
  27. # There may be multiple messages received
  28. while b"[" in buf and b']' in buf:
  29. # Find the message
  30. start = buf.find(b'[')
  31. buf = buf[start+1:]
  32. end = buf.find(b']')
  33. msg_parts = buf[:end].split(",") # buf now has b"Hello, 1234"
  34. buf = buf[end+1:]
  35.  
  36. # Check the checksum to make sure the data is valid
  37. if msg_parts[-1] == b"1234": # There are many different ways to make a good checksum
  38. callback(msg_parts[:-1])
  39.  
  40. return buf
  41.  
  42. running = True
  43. ser = serial.serial("COM10", 9600)
  44. buf = b''
  45. while running:
  46. buf = read_data(ser, buf)
  47.  
  48. import time
  49. import threading
  50.  
  51. running = threading.Event()
  52. running.set()
  53. def thread_read(ser, callback=None):
  54. buf = b''
  55. while running.is_set():
  56. buf = read_data(ser, buf, callback)
  57.  
  58. def msg_parsed(msg_parts):
  59. # Do something with the parsed data
  60. print(msg_parsed)
  61.  
  62. ser = serial.serial("COM10", 9600)
  63. th = threading.Thread(target=thread_read, args=(ser, msg_parsed))
  64. th.start()
  65.  
  66.  
  67. # Do other stuff while the thread is running in the background
  68. start = time.clock()
  69. duration = 5 # Run for 5 seconds
  70. while running.is_set():
  71. time.sleep(1) # Do other processing instead of sleep
  72. if time.clock() - start > duration
  73. running.clear()
  74.  
  75. th.join() # Wait for the thread to finish up and exit
  76. ser.close() # Close the serial port
Add Comment
Please, Sign In to add comment