magneticSensor.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import queue
  2. from struct import calcsize
  3. import numpy as np
  4. import time
  5. import threading # ?
  6. import random # ?
  7. from sensors.connection import globalArduinoSlave
  8. import logHandler
  9. conn = globalArduinoSlave()
  10. class MagneticSensor:
  11. def __init__(self, conf):
  12. self.conf = conf
  13. self.queue = queue.Queue()
  14. self.success = False
  15. self.mpu_array = []
  16. self.mpu_gyro_offsets = [0.0,0.0,0.0]
  17. self.log_handler = logHandler.get_log_handler()
  18. def start(self):
  19. if not conn.isConnected():
  20. conn.open()
  21. conn.addRecvCallback(self._readCb)
  22. self.calibrate()
  23. #self.dummyActive = True
  24. #dummyThread = threading.Thread(target=self._readCb_dummy)
  25. #dummyThread.start()
  26. def _readCb(self, raw):
  27. #print("mag: ", conn.getMagneticField())
  28. #print("accel: ", conn.getAccelValues())
  29. print("gyro: ", conn.getGyroValues())
  30. def calibrate(self, conf):
  31. # Gyroscope Calibration
  32. self.mpu_array = [] # clear Array for next calibration
  33. while True:
  34. try:
  35. gyro_x, gyro_y, gyro_z = conn.getGyroValues()
  36. except:
  37. continue
  38. self.mpu_gyro_array.append([gyro_x,gyro_y,gyro_z])
  39. if np.shape(self.mpu_array)[0] == conf.measurements_gyro:
  40. for qq in range(0,3):
  41. self.mpu_gyro_offsets[qq] = np.mean(np.array(self.mpu_array)[:,qq]) # average
  42. break
  43. print('Gyro Calibration Complete')
  44. return self.mpu_gyro_offsets
  45. # Accelerometer Calibration
  46. self.mpu_array = [] # clear array for next calibration
  47. accel_x, accel_y, accel_z = conn.getAccelValues()
  48. # Magnetometer Calibration
  49. self.mpu_array = [] # clear array for next calibration
  50. magneto_x, magneto_y, magneto_z = conn.getMagneticField()
  51. def read(self):
  52. return conn.getMagneticField()
  53. def stop(self):
  54. self.log_handler.log_and_print("stop magnetic sensor")
  55. conn.close()
  56. def pass_to_gui(self, data):
  57. self.queue.put(("data", data))