Guest User

Untitled

a guest
Apr 14th, 2020
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. import utime
  2. import machine
  3. from machine import UART
  4.  
  5. rxPin=16
  6. txPin=17
  7.  
  8. tx = machine.Pin(txPin, machine.Pin.OUT)
  9. rx = machine.Pin(rxPin, machine.Pin.IN)
  10. tx.value(0)
  11. utime.sleep_ms(500)
  12. tx.value(1)
  13.  
  14. uart=UART(1,2400)
  15. print("START LISTENING THE HANDSHAKE OF THE SENSOR")
  16. utime.sleep_ms(100)
  17. #Init communication at 2.400 bps
  18. uart.init(2400,bits=8,parity=None,stop=1,rx=rxPin,tx=txPin)
  19.  
  20. #I check for 2 ACK from the sensor
  21. #before send my ACK
  22. i=0
  23. while True:
  24. data = uart.read(uart.any())
  25. a=len(data)
  26. if a > 0:
  27. print(data)
  28. utime.sleep_ms(5)
  29. if data.find(b'\x04') >= 0:
  30. i=i+1
  31. if i==2:
  32. print("OK, SEND ACK TO SENSOR")
  33. utime.sleep_ms(20)
  34. uart.write(b'\x04')
  35. break
  36.  
  37. #Ok, if I am here, the sensor has sent his presentation data
  38. utime.sleep_ms(100)
  39. print("START DATA COMMUNICATION")
  40. #change the speed of communication channel
  41. uart.init(115200,bits=8,parity=None,stop=1,rx=rxPin,tx=txPin)
  42.  
  43. utime.sleep_ms(200)
  44.  
  45. #send SELECT command to swith the sensor in "MODE 8" (color/distance value)
  46. uart.write(b'\x43\x08\xB4\x02')
  47. utime.sleep_ms(50)
  48.  
  49. #send a second SELECT command to swith the sensor in "MODE 8" (color/distance value)
  50. uart.write(b'\x43\x08\xB4\x02')
  51. utime.sleep_ms(50)
  52.  
  53. lastnack= utime.ticks_ms()
  54. selectmode=lastnack
  55. currentime=lastnack
  56. iChangeMode=0
  57. while True:
  58. currentime=utime.ticks_ms()
  59. #Send a change mode after 1,5 second
  60. #(in case of the first two SELECTconmmand dont' work)
  61. #
  62. if (currentime-selectmode) >= 1500:
  63. if (iChangeMode == 0):
  64. print("CHANGE MODE REQUEST")
  65. iChangeMode = 1
  66. uart.write(b'\x43\x08\xB4')
  67. #send a NACK to sensor every 100 ms
  68. if (currentime-lastnack) >= 80:
  69. lastnack=currentime
  70. uart.write(b'\x02')
  71. utime.sleep_ms(10)
  72. data = uart.read(uart.any())
  73. a=len(data)
  74. if a > 0:
  75. print(data)
  76. #pos = data.find(b'\xD0')
  77. if data.find(b'\xD0') >= 0:
  78. print("THERE IS A VALUE")
Add Comment
Please, Sign In to add comment