magneticSensor.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.measurements_gyro = float(conf["mag_sensor"]["measurements_gyro"])
  17. self.measurements_accel = float(conf["mag_sensor"]["measurements_accel"])
  18. self.mpu_gyro_offsets = [0.0,0.0,0.0]
  19. self.log_handler = logHandler.get_log_handler()
  20. def start(self):
  21. if not conn.isConnected():
  22. conn.open()
  23. conn.addRecvCallback(self._readCb)
  24. #self.dummyActive = True
  25. #dummyThread = threading.Thread(target=self._readCb_dummy)
  26. #dummyThread.start()
  27. def _readCb(self, raw):
  28. #print("mag: ", conn.getMagneticField())
  29. #print("accel: ", conn.getAccelValues())
  30. print("gyro: ", conn.getGyroValues())
  31. def calibrate(self):
  32. # Gyroscope Calibration (TESTING!)
  33. self.mpu_array = [] # clear Array for next calibration
  34. while True:
  35. try:
  36. gyro_x, gyro_y, gyro_z = conn.getGyroValues()
  37. except:
  38. continue
  39. self.mpu_array.append([gyro_x,gyro_y,gyro_z])
  40. if np.shape(self.mpu_array)[0] == self.measurements_gyro:
  41. for qq in range(0,3):
  42. self.mpu_gyro_offsets[qq] = np.mean(np.array(self.mpu_array)[:,qq]) # average
  43. break
  44. print('Gyro Calibration Complete')
  45. print(self.mpu_gyro_offsets)
  46. return self.mpu_gyro_offsets
  47. # Accelerometer Calibration
  48. self.mpu_array = [] # clear array for next calibration
  49. accel_x, accel_y, accel_z = conn.getAccelValues()
  50. # Magnetometer Calibration
  51. self.mpu_array = [] # clear array for next calibration
  52. magneto_x, magneto_y, magneto_z = conn.getMagneticField()
  53. def read(self):
  54. return conn.getMagneticField()
  55. def stop(self):
  56. self.log_handler.log_and_print("stop magnetic sensor")
  57. conn.close()
  58. def pass_to_gui(self, data):
  59. self.queue.put(("data", data))