send.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/python3
  2. import time
  3. import threading
  4. import math
  5. # pip3 install smbus ->PCF8591芯片
  6. import smbus
  7. class SENDSERVER(threading.Thread):
  8. def __init__(self, sock):
  9. threading.Thread.__init__(self)
  10. self.setDaemon(True)
  11. self.sock = sock
  12. self.relay = None
  13. self.webcam = None
  14. # 初始化smbus 1表示scl.1 0表示scl.0
  15. self.BUS = smbus.SMBus(1)
  16. # 寄存器地址
  17. self.ADR = 0x48
  18. # 电位器地址->对应模块in1,in2
  19. self.P1 = 0x41
  20. self.P2 = 0x42
  21. self.P3 = 0x43
  22. self.P4 = 0x44
  23. # 方向值
  24. self.CENTER = 0
  25. # 最终方向
  26. self.CON = 'Center'
  27. # 方向误差
  28. self.VD = 10
  29. def __del__(self):
  30. self.sock.close()
  31. pass
  32. def run(self):
  33. # 数模初始值
  34. self.BUS.write_byte(self.ADR, self.P1)
  35. self.CENTER = self.BUS.read_byte(self.ADR)
  36. while True:
  37. data = self.Orientation()
  38. self.sock.sendall(data)
  39. time.sleep(0.04)
  40. # 电压值误差根据实际情况调整
  41. def Residual(self, v):
  42. # 中间值
  43. vs = self.CENTER
  44. # 误差值
  45. vd = self.VD
  46. if math.fabs(v - vs) > vd:
  47. return v
  48. elif math.fabs(v - vs) < vd:
  49. return vs
  50. else:
  51. return vs
  52. # 区分方向
  53. def Orientation(self):
  54. self.BUS.write_byte(self.ADR, self.P1)
  55. v0 = self.BUS.read_byte(self.ADR)
  56. time.sleep(0.02)
  57. self.BUS.write_byte(self.ADR, self.P2)
  58. v1 = self.BUS.read_byte(self.ADR)
  59. time.sleep(0.02)
  60. self.BUS.write_byte(self.ADR, self.P3)
  61. v2 = self.BUS.read_byte(self.ADR)
  62. time.sleep(0.02)
  63. self.BUS.write_byte(self.ADR, self.P4)
  64. v3 = self.BUS.read_byte(self.ADR)
  65. # 接入socket 发送数据
  66. db = '{"type":"conctrl","data":{"v0":%s,"v1":%s,"v2":"%s","v3":"%s"}}' % (v0, v1, v2, v3)
  67. data = str.encode(db)
  68. return data