Advertisement
Guest User

Untitled

a guest
Jul 16th, 2023
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import time
  2. import board
  3. import busio
  4. import adafruit_vl53l0x
  5. import pyqtgraph as pg
  6. from PyQt5.QtWidgets import QApplication
  7. from PyQt5.QtCore import QThread, QTimer, pyqtSignal
  8.  
  9. timestamps = []
  10. distances = []
  11.  
  12. i2c = busio.I2C(board.SCL, board.SDA)
  13. sensor = adafruit_vl53l0x.VL53L0X(i2c)
  14.  
  15. class SensorThread(QThread):
  16. data_ready = pyqtSignal(float, float)
  17.  
  18. def run(self):
  19. try:
  20. while True:
  21. start_time = time.monotonic()
  22.  
  23. # Take a measurement
  24. distance = sensor.range - 15
  25.  
  26. # Get current timestamp
  27. timestamp = time.monotonic()
  28.  
  29. # Emit the data
  30. self.data_ready.emit(timestamp, distance)
  31.  
  32. # Calculate the elapsed time
  33. elapsed_time = time.monotonic() - start_time
  34.  
  35. # Delay between measurements
  36. #time.sleep(0.01) # Adjust the delay as needed
  37.  
  38. except KeyboardInterrupt:
  39. pass
  40.  
  41. def update_plot(timestamp, distance):
  42. timestamps.append(timestamp)
  43. distances.append(distance)
  44.  
  45. # Convert timestamps to milliseconds
  46. timestamps_ms = [ts - timestamps[0] for ts in timestamps]
  47. curve.setData(timestamps_ms, distances)
  48.  
  49. # Adjust x-axis range to display only the latest data
  50. x_range = max(timestamps_ms) - (max(timestamps_ms) - 1)
  51. plot.setXRange(max(timestamps_ms) - x_range, max(timestamps_ms))
  52.  
  53. sensor_thread = SensorThread()
  54. sensor_thread.data_ready.connect(update_plot)
  55. sensor_thread.start()
  56.  
  57. app = QApplication([])
  58.  
  59. win = pg.GraphicsLayoutWidget(title="Real-time Distance Plot")
  60. plot = win.addPlot()
  61. plot.setLabel('left', 'Distance (mm)')
  62. plot.setLabel('bottom', 'Time (ms)')
  63. y_range = 60
  64. plot.setRange(yRange=(0, y_range))
  65. curve = plot.plot(pen='b')
  66.  
  67. timer = QTimer()
  68. timer.timeout.connect(lambda: None) # Empty function to keep the event loop running
  69. timer.start(0)
  70.  
  71. win.show() # Show the plot window
  72.  
  73. app.exec_()
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement