imu.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import cv2
  2. import depthai as dai
  3. # Create pipeline
  4. pipeline = dai.Pipeline()
  5. # Define sources and outputs
  6. imu = pipeline.create(dai.node.IMU)
  7. xlinkOut = pipeline.create(dai.node.XLinkOut)
  8. xlinkOut.setStreamName("imu")
  9. # enable ACCELEROMETER_RAW at 500 hz rate
  10. imu.enableIMUSensor(dai.IMUSensor.ACCELEROMETER_RAW, 500)
  11. # enable GYROSCOPE_RAW at 400 hz rate
  12. imu.enableIMUSensor(dai.IMUSensor.GYROSCOPE_RAW, 400)
  13. # it's recommended to set both setBatchReportThreshold and setMaxBatchReports to 20 when integrating in a pipeline with a lot of input/output connections
  14. # above this threshold packets will be sent in batch of X, if the host is not blocked and USB bandwidth is available
  15. imu.setBatchReportThreshold(1)
  16. # maximum number of IMU packets in a batch, if it's reached device will block sending until host can receive it
  17. # if lower or equal to batchReportThreshold then the sending is always blocking on device
  18. # useful to reduce device's CPU load and number of lost packets, if CPU load is high on device side due to multiple nodes
  19. imu.setMaxBatchReports(10)
  20. # Link plugins IMU -> XLINK
  21. imu.out.link(xlinkOut.input)
  22. # Pipeline is defined, now we can connect to the device
  23. with dai.Device(pipeline) as device:
  24. def timeDeltaToMilliS(delta) -> float:
  25. return delta.total_seconds()*1000
  26. # Output queue for imu bulk packets
  27. imuQueue = device.getOutputQueue(name="imu", maxSize=50, blocking=False)
  28. baseTs = None
  29. while True:
  30. imuData = imuQueue.get() # blocking call, will wait until a new data has arrived
  31. imuPackets = imuData.packets
  32. for imuPacket in imuPackets:
  33. acceleroValues = imuPacket.acceleroMeter
  34. gyroValues = imuPacket.gyroscope
  35. acceleroTs = acceleroValues.timestamp.get()
  36. gyroTs = gyroValues.timestamp.get()
  37. if baseTs is None:
  38. baseTs = acceleroTs if acceleroTs < gyroTs else gyroTs
  39. acceleroTs = timeDeltaToMilliS(acceleroTs - baseTs)
  40. gyroTs = timeDeltaToMilliS(gyroTs - baseTs)
  41. imuF = "{:.06f}"
  42. tsF = "{:.03f}"
  43. print(f"Accelerometer timestamp: {tsF.format(acceleroTs)} ms")
  44. print(f"Accelerometer [m/s^2]: x: {imuF.format(acceleroValues.x)} y: {imuF.format(acceleroValues.y)} z: {imuF.format(acceleroValues.z)}")
  45. print(f"Gyroscope timestamp: {tsF.format(gyroTs)} ms")
  46. print(f"Gyroscope [rad/s]: x: {imuF.format(gyroValues.x)} y: {imuF.format(gyroValues.y)} z: {imuF.format(gyroValues.z)} ")
  47. if cv2.waitKey(1) == 27:
  48. break