arduino.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Copyright 2016 by MPI-SWS and Data-Ken Research.
  2. # Licensed under the Apache 2.0 License.
  3. """Sensors for AntEvents
  4. Uses the nanpy library (https://github.com/nanpy/nanpy), which controls
  5. a slave Arduino processor. The sensors are connected to the Arduino.
  6. Both digital (1/0 output) and analogue (0-1023 ouput) sensors may be
  7. be connected to the Arduino. To use this, Nanpy firmware needs to be
  8. flashed onto the Arduino to allow Python to be used.
  9. Note -This sensor class can only be used with sensors which send their output
  10. straight to the Arduino pins. For sensors which use I2C or SPI, with their
  11. own registers, a library to use them has to be written separately.
  12. """
  13. from thingflow.base import OutputThing, IndirectOutputThingMixin
  14. from nanpy import ArduinoApi,SerialManager
  15. ardApi = ArduinoApi(connection=SerialManager(device = '/dev/ttyACM0'))
  16. class ArduinoSensor(OutputThing, IndirectOutputThingMixin):
  17. """Sensor connected to Arduino. Output is analogue(1/0) or digital output(0 - 1023). Nanpy firmware needs to be flashed onto Arduino.
  18. """
  19. def __init__(self,sensor_id,AD):
  20. """sensor_id is port number, AD is True/False for Analogue/Digital
  21. """
  22. super().__init__()
  23. self.sensor_id = sensor_id
  24. self.AD = AD
  25. ardApi.pinMode(sensor_id,ardApi.INPUT)
  26. def sample(self):
  27. if self.AD:
  28. val = ardApi.digitalRead(self.sensor_id)
  29. else:
  30. val = ardApi.analogRead(self.sensor_id)
  31. return val
  32. def __str__(self):
  33. return 'Arduino Sensor (port=%s, AD=%s)'% (self.sensor_id, self.AD)