sensor.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright 2016 by MPI-SWS and Data-Ken Research.
  2. # Licensed under the Apache 2.0 License.
  3. """Sensors for ThingFlow
  4. Updated to suit the API changes Jeff mentioned, so that the following can be used as follows:
  5. sensor = SensorAsOutputThing(RPISensor())
  6. The following classes allow digital/analogue sensors (which are not connected using I2C) to be connected to a Raspberry Pi/Arduino and used with ThingFlow
  7. """
  8. from thingflow.base import OutputThing, IndirectOutputThingMixin
  9. import RPi.GPIO as GPIO
  10. class RPISensor(OutputThing, IndirectOutputThingMixin):
  11. """Sensor connected to Raspberry Pi. Output of sensor is digital (RPi does not come with an ADC unlike the Arduino)
  12. """
  13. def __init__(self,sensor_id):
  14. """sensor_id is port number
  15. """
  16. super().__init__()
  17. self.sensor_id = sensor_id
  18. GPIO.setmode(GPIO.BOARD)
  19. GPIO.setup(sensor_id,GPIO.IN)
  20. def sample(self):
  21. val = GPIO.input(self.sensor_id)
  22. return val
  23. def __str__(self):
  24. return 'Raspberry Pi Sensor (port=%s)'% self.sensor_id
  25. from nanpy import ArduinoApi,SerialManager
  26. ardApi = ArduinoApi(connection=SerialManager(device = '/dev/ttyACM0'))
  27. class ArduinoSensor(OutputThing, IndirectOutputThingMixin):
  28. """Sensor connected to Arduino. Output is analogue(1/0) or digital output(0 - 1023). Nanpy firmware needs to be flashed onto Arduino.
  29. """
  30. def __init__(self,sensor_id,AD):
  31. """sensor_id is port number, AD is True/False for Analogue/Digital
  32. """
  33. super().__init__()
  34. self.sensor_id = sensor_id
  35. self.AD = AD
  36. ardApi.pinMode(sensor_id,ardApi.INPUT)
  37. def sample(self):
  38. if self.AD:
  39. val = ardApi.digitalRead(self.sensor_id)
  40. else:
  41. val = ardApi.analogRead(self.sensor_id)
  42. return val
  43. def __str__(self):
  44. return 'Arduino Sensor (port=%s, AD=%s)'% (self.sensor_id, self.AD)