Beispiel #1
0
def setup():
    global chan_temp
    global chan_LDR

    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D5)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    # Create an analog input channel on pin 0 and 1
    chan_temp = AnalogIn(mcp, MCP.P1)
    chan_LDR = AnalogIn(mcp, MCP.P0)

    # Setup buttons for interupt and input
    GPIO.setup(btn_delay, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(btn_delay,
                          GPIO.FALLING,
                          callback=btn_delay_callback,
                          bouncetime=250)

    GPIO.setup(btn_measure, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(btn_measure,
                          GPIO.FALLING,
                          callback=btn_measure_callback,
                          bouncetime=250)
Beispiel #2
0
def get_canales(mcp):
    # creo canales
    canal1 = AnalogIn(mcp, MCP.P0)
    canal2 = AnalogIn(mcp, MCP.P1)
    canal3 = AnalogIn(mcp, MCP.P2)
    canales = [canal1, canal2, canal3]
    return canales
Beispiel #3
0
def setup():

    global chan_ldr
    global chan_temp

    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D5)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    # create an analog input channel on pin 0
    chan_ldr = AnalogIn(mcp, MCP.P0)
    chan_temp = AnalogIn(mcp, MCP.P1)

    # setup button
    GPIO.setup(btn, GPIO.IN)
    GPIO.setup(btn, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(btn,
                          GPIO.FALLING,
                          callback=btn_pressed,
                          bouncetime=200)
Beispiel #4
0
 def __init__(self):
     # create analog input channels on pins 0 through 5
     self.chan0 = AnalogIn(mcp, MCP.P0)
     self.chan1 = AnalogIn(mcp, MCP.P1)
     self.chan2 = AnalogIn(mcp, MCP.P2)
     self.chan3 = AnalogIn(mcp, MCP.P3)
     self.chan4 = AnalogIn(mcp, MCP.P4)
Beispiel #5
0
def query_hardware():
    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D5)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    # create analog channels for the LDR and potentiometer
    ldr = AnalogIn(mcp, MCP.P0)
    pot = AnalogIn(mcp, MCP.P1)

    last_ldr_val = 0.0
    last_pot_val = 0.0

    while True:
        # normalize
        cur_ldr_val = normalize_value(MIN_LDR_VAL, MAX_LDR_VAL, ldr.value)
        cur_pot_val = normalize_value(MIN_POT_VAL, MAX_POT_VAL, pot.value)
        # if either the LDR or potentiometer values are outside their thresholds
        if (beyond_threshold(last_ldr_val, cur_ldr_val, LDR_THRESHOLD) or beyond_threshold(last_pot_val, cur_pot_val, POT_THRESHOLD)):
            # publish current LDR and potentiometer values
            client.publish("lightSensor", payload=str(cur_ldr_val), qos=2, retain=True)
            client.publish("threshold", payload=str(cur_pot_val), qos=2, retain=True)
        # update values
        last_ldr_val = cur_ldr_val
        last_pot_val = cur_pot_val
        # wait 100 ms
        time.sleep(0.1)
Beispiel #6
0
 def add_channel(self, number):
     if number in self.allocated_channels:
         print("Warning: This channel has already been allocated")
         return AnalogIn(self.mcp, number)
     elif number not in self.available_channels:
         print("Error: Channel number outside available range")
         return
     self.available_channels.remove(number)
     self.allocated_channels.append(number)
     return AnalogIn(self.mcp, number)
Beispiel #7
0
def action():
    # create an analog input channel on pin 0
    moistureSensor = AnalogIn(mcp, MCP.P0)
    # output signal 0-4.2 V
    # 0 ~300    : dry soil :      0~1.33 V
    # 300~700   : humid soil :    1.33~3.09 V
    # 700~950   : in water :      3.09~4.20 V
    write_data('moisture', moistureSensor.voltage, moistureSensor.value)

    # create an analog input channel on pin 1
    liquidlevelSensor = AnalogIn(mcp, MCP.P1)
    write_data('liquidlevel', liquidlevelSensor.voltage,
               liquidlevelSensor.value)
Beispiel #8
0
def readValues():
    # Read all the ADC channel values in a list.
    sh.values = [0] * 8

    # The read_adc function will get the value of the specified channel (0-7).
    ch0 = AnalogIn(mcp, MCP.P0, MCP.P1)
    ch1 = AnalogIn(mcp, MCP.P1, MCP.P0)
    ch2 = AnalogIn(mcp, MCP.P2, MCP.P3)
    ch3 = AnalogIn(mcp, MCP.P3, MCP.P2)
    ch4 = AnalogIn(mcp, MCP.P4, MCP.P5)
    ch5 = AnalogIn(mcp, MCP.P5, MCP.P4)
    ch6 = AnalogIn(mcp, MCP.P6, MCP.P7)
    ch7 = AnalogIn(mcp, MCP.P7, MCP.P6)

    # shift values down by 6 bits
    # https://github.com/adafruit/Adafruit_CircuitPython_MCP3xxx/issues/12
    sh.values[0] = ch0.value >> 6
    sh.values[1] = ch1.value >> 6
    sh.values[2] = ch2.value >> 6
    sh.values[3] = ch3.value >> 6
    sh.values[4] = ch4.value >> 6
    sh.values[5] = ch5.value >> 6
    sh.values[6] = ch6.value >> 6
    sh.values[7] = ch7.value >> 6

    return sh.values
 def __init__(self, numOfChannels, vref, noiseThreshold=350, maxInterval=1, cs=8):
     ''' Create spi connection and initialize lists '''
     
     self.vref = vref
     logging.info("MCP3008 using SPI SCLK:GPIO{0} MISO:GPIO{1} MOSI:GPIO{2} CS:GPIO{3}".format(board.SCK, board.MISO, board.MOSI, cs))
     spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) # create the spi bus
     if cs == 8:
         cs = digitalio.DigitalInOut(board.D8) # create the cs (chip select). Use GPIO8 (CE0) or GPIO7 (CE1)
     elif cs == 7:
         cs = digitalio.DigitalInOut(board.D7) # create the cs (chip select). Use GPIO8 (CE0) or GPIO7 (CE1)
     else:
         logging.info("Chip Select pin must be 7 or 8")
         exit()
     mcp = MCP.MCP3008(spi, cs) # create the mcp object. Can pass Vref as last argument
     self.numOfChannels = numOfChannels
     self.chan = [AnalogIn(mcp, MCP.P0), # create analog input channel on pins
                  AnalogIn(mcp, MCP.P1),
                  AnalogIn(mcp, MCP.P2),
                  AnalogIn(mcp, MCP.P3),
                  AnalogIn(mcp, MCP.P4),
                  AnalogIn(mcp, MCP.P5),
                  AnalogIn(mcp, MCP.P6),
                  AnalogIn(mcp, MCP.P7)]
     self.noiseThreshold = noiseThreshold
     self.numOfSamples = 10             # Number of samples to average
     self.maxInterval = maxInterval  # interval in seconds to check for update
     self.time0 = time()   # time 0
     # Initialize lists
     self.sensorAve = [x for x in range(self.numOfChannels)]
     self.sensorLastRead = [x for x in range(self.numOfChannels)]
     self.adcValue = [x for x in range(self.numOfChannels)]
     self.sensor = [[x for x in range(0, self.numOfSamples)] for x in range(0, self.numOfChannels)]
     for x in range(self.numOfChannels): # initialize the first read for comparison later
         self.sensorLastRead[x] = self.chan[x].value
Beispiel #10
0
 def __init__(self,
              numOfChannels,
              vref,
              sampleInterval=1,
              noiseThreshold=350,
              numOfSamples=10):
     self.vref = vref
     spi = busio.SPI(clock=board.SCK, MISO=board.MISO,
                     MOSI=board.MOSI)  # create the spi bus
     cs = digitalio.DigitalInOut(board.D22)  # create the cs (chip select)
     mcp = MCP.MCP3008(spi, cs)  # create the mcp object
     self.numOfChannels = numOfChannels
     self.chan = [
         AnalogIn(mcp, MCP.P0),  # create analog input channel on pins
         AnalogIn(mcp, MCP.P1),
         AnalogIn(mcp, MCP.P2),
         AnalogIn(mcp, MCP.P3),
         AnalogIn(mcp, MCP.P4),
         AnalogIn(mcp, MCP.P5),
         AnalogIn(mcp, MCP.P6),
         AnalogIn(mcp, MCP.P7)
     ]
     self.noiseThreshold = noiseThreshold
     self.sensorChanged = False
     self.numOfSamples = numOfSamples
     self.sensorAve = [x for x in range(self.numOfChannels)]
     self.sensorLastRead = [x for x in range(self.numOfChannels)]
     for x in range(self.numOfChannels
                    ):  # initialize the first read for comparison later
         self.sensorLastRead[x] = self.chan[x].value
     self.adcValue = [x for x in range(self.numOfChannels)]
     self.sensor = [[x for x in range(0, self.numOfSamples)]
                    for x in range(0, self.numOfChannels)]
     self.sampleInterval = sampleInterval  # interval in seconds to check for update
     self.time0 = time()  # time 0
Beispiel #11
0
    def __init__(self, pigpioHandle, adcHandle):
        self.pi = pigpioHandle
        self.pi.set_mode(Windmills.DRIVE_POSITIVE_PIN, pigpio.OUTPUT)
        self.pi.set_mode(Windmills.DRIVE_NEGATIVE_PIN, pigpio.OUTPUT)

        self.driveWindmills = False
        self.timeOfLastChange = 0
        self.halfPeriod = 1000 / Windmills.DRIVE_FREQUENCY

        self.windmill1 = AnalogIn(adcHandle, MCP.P1)
        self.windmill2 = AnalogIn(adcHandle, MCP.P2)
        self.windmill3 = AnalogIn(adcHandle, MCP.P3)
        self.windmill4 = AnalogIn(adcHandle, MCP.P4)
        self.windmill5 = AnalogIn(adcHandle, MCP.P5)
Beispiel #12
0
    def __init__(self, pin_adc=None):

        # ADC channel value, be careful to not use one channel for more than one device!
        self._channel = None

        # Create an analog input channel on the MCP3008 according to pin_adc value
        if pin_adc is None:
            raise ValueError("pin_adc needs to be informed.")
        elif pin_adc == 0:
            self._channel = AnalogIn(type(self)._mcp, MCP.P0)
        elif pin_adc == 1:
            self._channel = AnalogIn(type(self)._mcp, MCP.P1)
        elif pin_adc == 2:
            self._channel = AnalogIn(type(self)._mcp, MCP.P2)
        elif pin_adc == 3:
            self._channel = AnalogIn(type(self)._mcp, MCP.P3)
        elif pin_adc == 4:
            self._channel = AnalogIn(type(self)._mcp, MCP.P4)
        elif pin_adc == 5:
            self._channel = AnalogIn(type(self)._mcp, MCP.P5)
        elif pin_adc == 6:
            self._channel = AnalogIn(type(self)._mcp, MCP.P6)
        elif pin_adc == 7:
            self._channel = AnalogIn(type(self)._mcp, MCP.P7)
        else:
            raise ValueError(
                "Invalid pin value. Pin value must be an integer value between 0 and 7"
            )
Beispiel #13
0
    def __init__(self):
        Sensor.__init__(self)

        self.moisture_min = float(self.config["soil"]["min"])
        self.moisture_max = float(self.config["soil"]["max"])

        # create SPI bus
        spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

        # create the cs (chip select)
        cs = digitalio.DigitalInOut(board.D8)

        # create the mcp object
        mcp = MCP.MCP3008(spi, cs)

        # create an analog input channel
        self.pin = []
        self.pin.append(AnalogIn(mcp, MCP.P0))
        self.pin.append(AnalogIn(mcp, MCP.P1))
        self.pin.append(AnalogIn(mcp, MCP.P2))
        self.pin.append(AnalogIn(mcp, MCP.P3))
        self.pin.append(AnalogIn(mcp, MCP.P4))
        self.pin.append(AnalogIn(mcp, MCP.P5))
        self.pin.append(AnalogIn(mcp, MCP.P6))
        self.pin.append(AnalogIn(mcp, MCP.P7))
Beispiel #14
0
 def __init__(self):
     self.spi = busio.SPI(
         clock=board.SCK,
         MISO=board.MISO,
         MOSI=board.MOSI
     )
     self.cs = digitalio.DigitalInOut(board.D22)
     self.mcp = MCP.MCP3008(self.spi, self.cs)
     self.pins = [
         AnalogIn(self.mcp, MCP.P0),
         AnalogIn(self.mcp, MCP.P1),
         AnalogIn(self.mcp, MCP.P2),
     ]
     self.values = [0, 0, 0]
     self.read_pot_values()
Beispiel #15
0
def initialize_photoresistor(mcp):
    global photoresistor_channel, photoresistor_error
    try:
        photoresistor_channel = AnalogIn(mcp, MCP.P0)
    except Exception as error:
        print(error.args[0])
        photoresistor_error = True
Beispiel #16
0
def initialize_soil_sensor(mcp):
    global soil_moisture_channel, soil_sensor_error
    try:
        soil_moisture_channel = AnalogIn(mcp, MCP.P2)
    except Exception as error:
        print(error.args[0])
        soil_sensor_error = True
Beispiel #17
0
 def get_voltage(self) -> float:
     # This will throw exceptions in the event of a hardware issue
     if not self.mcp:
         self.setupMcp()
     # create an analog input channel on pin 0
     chan = AnalogIn(self.mcp, mcp3008.P0)
     return chan.voltage
def setup():
    # the following variables must be global
    global spi, cs, mcp, chan, buzzer

    #region Setup ADC
    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D5)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    # create an analog input channel on pin 1
    chan = AnalogIn(mcp, MCP.P1)
    #endregion Setup ADC

    # the pin to start/stop printing to the console
    start_stop_pin = 24  # this is pin 18 in BOARD MODE

    # setting GPIO 24 (BCM) as an input
    GPIO.setup(start_stop_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    #region Setup buzzer
    GPIO.setup(buzzer_pin, GPIO.OUT, initial=GPIO.LOW)

    # adding a callback for when the start/stop button is clicked
    GPIO.add_event_detect(start_stop_pin,
                          GPIO.FALLING,
                          callback=start_stop,
                          bouncetime=300)
def get_air_temp():
    airtemp = 0
    for i in range(0, 5):
        airsensor = AnalogIn(mcp, MCP.P1)
        airtemp += (airsensor.voltage * 100) - 273
    airtemp = airtemp / 5
    return airtemp
def voltage() -> float:
    """
    Gets the analog voltage from pin 0 on the MCP3008

    Arguments: None

    Returns:
        - The analog voltage
    """

    try:
        # create the spi bus
        spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

        # create the cs (chip select)
        cs = digitalio.DigitalInOut(board.D5)

        # create the mcp object
        mcp = MCP.MCP3008(spi, cs)

        # create an analog input channel on pin 0
        chan = AnalogIn(mcp, MCP.P0)

        return chan
    except:
        sys.exit(1)
Beispiel #21
0
def setup():
    # the following variables must be global
    global spi, cs, mcp, chan

    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D5)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    # create an analog input channel on pin 1
    chan = AnalogIn(mcp, MCP.P1)

    # the button pin (in BCM mode)
    button_pin = 23

    # setting GPIO 23 (BCM) as an input
    GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # adding a callback for when the button is clicked
    GPIO.add_event_detect(button_pin,
                          GPIO.FALLING,
                          callback=toggle_rate,
                          bouncetime=300)
Beispiel #22
0
def main():
    """
    Print the water level and temperature every second
    :return:
    """
    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D22)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    # create an analog input channel on pin 0
    water_level_sensor = AnalogIn(mcp, MCP.P0)

    # create temperature sensor
    temp_sensor = W1ThermSensor()

    while True:
        temperature = temp_sensor.get_temperature()
        print(f"The temperature is {temperature} C, {celsius_to_fahrenheit(temperature)} F")
        print(f"ADC Voltage: {round(water_level_sensor.voltage, 2)}V")
        print(f"Water Level: {get_water_level_inches(water_level_sensor.voltage)} inches")
        print("\n")
        time.sleep(1)
def get_water_temp():
    watertemp = 0
    for i in range(0, 5):
        watersensor = AnalogIn(mcp, MCP.P0)
        watertemp += (watersensor.voltage * 100) - 273
    watertemp = watertemp / 5
    return watertemp
Beispiel #24
0
    def Start(self, event):
        print("Starting sensor...")

        # create the spi bus
        spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

        # create the cs (chip select)
        cs = digitalio.DigitalInOut(board.D5)

        # create the mcp object
        mcp = MCP.MCP3008(spi, cs)

        # create an analog input channel on pin 0
        channel = AnalogIn(mcp, MCP.P3)

        reading = Reading(value=channel.value, voltage=channel.voltage)
        self.new_reading_event.notify(reading.value, reading.voltage,
                                      reading.percentage)
        # SensorRepository.SaveReading(percentage=reading.percentage, value=reading.value, voltage=reading.voltage)

        while True:
            avg = [0] * 2
            for x in range(50):
                avg[0] = avg[0] + channel.value
                avg[1] = avg[1] + channel.voltage
                time.sleep(0.5)
                # print('{} | {}'.format(x, str(channel.value)))

            avgValue = avg[0] / 50
            avgVoltage = avg[1] / 50

            reading = Reading(value=avgValue, voltage=avgVoltage)
            self.new_reading_event.notify(reading.value, reading.voltage,
                                          reading.percentage)
Beispiel #25
0
def getTemps():
    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.CE0)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    channels = [MCP.P0, MCP.P1, MCP.P2]

    temps = []

    for channel in channels:

        # create an analog input channel on pin 0
        chan = AnalogIn(mcp, channel)
        value = chan.value

        if DEBUG:
            print('Value: {0} Voltage: {1}'.format(value, chan.voltage))

        if value != 0:
            temp = temp_calc(chan.voltage)
            temps.append(float(temp))
            if DEBUG:
                print("value: {0} {1} {2}".format(value, temp, channel))

        #log temperature of 0 if sensor is not connected
        if value == 0:
            temps.append(float(value))
            if DEBUG:
                print("value: {0} {1}".format(value, channel))
    return temps
Beispiel #26
0
def main(argv):
    del argv

    # Setup up board
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
    cs = digitalio.DigitalInOut(board.CE0)
    mcp = MCP.MCP3008(spi, cs)

    # Setup up metrics
    gauge = prom.Gauge("moisture_percent", "Moisture percentage", ["sensor_id"])
    logging.info("Starting http server...")
    prom.start_http_server(8080)
    logging.info("Started http server on port 8080")

    meters = []
    for pin, getter in id_getter.items():
        id = getter()
        if id:
            logging.info("Measuring pin " + str(pin) + " with id " + id)
            meter = MoistureMeter(id, AnalogIn(mcp, pin), gauge)
            meters.append(meter)
        else:
            logging.info("Not measuring pin " + str(pin))

    if not meters:
        logging.error("no pins are being measured")
        return

    while True:
        for m in meters:
            m.measure()
        logging.debug("Sleeping for " + str(FLAGS.poll_ms) + "ms")
        time.sleep(0.001 * FLAGS.poll_ms)
    def __init__(self,
                 n_channels=1,
                 ref_voltage=3.3,
                 threshold=.6,
                 charger_off_callback=None,
                 charger_on_callback=None):

        self.n_channels = n_channels
        self.ref_voltage = ref_voltage
        self.threshold = threshold
        self.charger_off_callback = charger_off_callback
        self.charger_on_callback = charger_on_callback

        # Init serial port
        self.spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

        # This pin doesn't seem to matter?!?
        self.cs = digitalio.DigitalInOut(board.D24)
        self.mcp = MCP.MCP3008(self.spi, self.cs, self.ref_voltage)
        self.channels = [
            AnalogIn(self.mcp, getattr(MCP, 'P{}'.format(i)))
            for i in range(self.n_channels)
        ]

        # Init Thread
        self._read_thread = threading.Thread(target=self._read_charger_loop)
        self._read_thread_isalive = False
        self._charger_states = None
Beispiel #28
0
def setup():
    #ADC and Temp sensor setup
    global chan, start, start_stop, k
    GPIO.setmode(GPIO.BCM)
    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D5)
    # create the mcp object
    mcp = MCP.MCP3008(spi, cs);
    # create an analog input channel on pin 0
    chan = AnalogIn(mcp, MCP.P0);
    # Setup Button
    GPIO.setup(button_stop_start,GPIO.IN,pull_up_down=GPIO.PUD_UP);
    # Setup debouncing and callbacks
   # GPIO.add_event_detect(button_stop_start,GPIO.FALLING,callback=btn_startstop,bouncetime=300);
    start=time.time();
    start_stop=1;
    print("Time:\t\t\tRuntime\t\tTemperature:")
    #EEPROM setup
    # Setup PWM channels
    GPIO.setup(buzzer, GPIO.OUT)
    k=GPIO.PWM(buzzer,1000)
    k.start(0)
    # Setup debouncing and callbacks
    GPIO.add_event_detect(button_stop_start,GPIO.FALLING,callback=btn_startstop,bouncetime=300)
    return chan #object of analog input channel for ADC returned.
Beispiel #29
0
def animate (i,xs,ys):
    
    import busio
    import digitalio
    import board
    import adafruit_mcp3xxx.mcp3008 as MCP
    from adafruit_mcp3xxx.analog_in import AnalogIn
    import time

    while True:
        spi = busio.SPI(clock=board.SCK_1, MISO=board.MISO_1, MOSI=board.MOSI_1)

        cs = digitalio.DigitalInOut(board.D5)

        mcp = MCP.MCP3008(spi, cs)

        chan = AnalogIn(mcp, MCP.P0)
    
    volt = print("Raw ADC Value: ", chan.value)

    xs.append(dt.datetime.now().strftime('%H:%M:%S'))
    ys.append(volt)



    ax.clear()
    ax.plot(xs,ys)

    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.title('BPM test')
    plt.ylabel('Voltage')
Beispiel #30
0
def main():

    # mcp3008 button reader setup
    # create software spi
    spi = bitbangio.SPI(board.D11, MISO=board.D9, MOSI=board.D10)
    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D22)
    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)
    # create analog input channels on pins 6 and 7 of the mcp3008
    chan1 = AnalogIn(mcp, MCP.P6)
    chan2 = AnalogIn(mcp, MCP.P7)

    # setup rotary encoder in pigpio
    pi = pigpio.pi()  # init pigpio deamon
    pi.set_mode(Enc_A, pigpio.INPUT)
    pi.set_pull_up_down(Enc_A, pigpio.PUD_UP)
    pi.set_mode(Enc_B, pigpio.INPUT)
    pi.set_pull_up_down(Enc_B, pigpio.PUD_UP)
    pi.callback(Enc_A, pigpio.EITHER_EDGE, rotary_interrupt)
    pi.callback(Enc_B, pigpio.EITHER_EDGE, rotary_interrupt)

    # main loop
    while True:
        # read button states
        if 0 <= chan1.value <= 1000:
            button_interrupt("Timer")
        if 5900 <= chan1.value <= 7000:
            button_interrupt("Time Adj")
        if 12000 <= chan1.value <= 13000:
            button_interrupt("Daily")
        if 0 <= chan2.value <= 1000:
            button_interrupt("Power")
        if 5800 <= chan2.value <= 6100:
            button_interrupt("Band")
        if 13000 <= chan2.value <= 14000:
            button_interrupt("Function")
        if 26000 <= chan2.value <= 27000:
            button_interrupt("Enter")
        if 19000 <= chan2.value <= 21000:
            button_interrupt("Info")
        if 39000 <= chan2.value <= 41000:
            button_interrupt("Auto Tuning")
        if 33000 <= chan2.value <= 34000:
            button_interrupt("Memory")
        if 44000 <= chan2.value <= 46000:
            button_interrupt("Dimmer")