Example #1
0
 def near(self): 
     id = int(str(self)[4:-1]) #unsafe!
     pin15=Pin(15,Pin.OUT)
     pin15.value(1)
     adc=ADC(Pin(id))
     adc.atten(ADC.ATTN_11DB)
     approximate =adc.read()
     pin15.value(0)
     return approximate
Example #2
0
def showVoltage():
    from machine import ADC, Pin

    adc = ADC(Pin(32))

    vref = 1100

    v = adc.read()
    battery_voltage = (float(v) / 4095.0) * 2.0 * 3.3 * (vref / 1000.0)
    # voltage = ("Voltage :" + str(battery_voltage) + "V")
    voltage = ("Voltage: {0:0.2f}v".format(battery_voltage))
    print(voltage)

    ddd = voltage
    return ddd
Example #3
0
def bat():
    from machine import ADC, Pin
    import os
    if os.uname()[0] == "esp8266":
        bat = ADC(0)
    else:
        bat = ADC(Pin(35))
        bat.atten(ADC.ATTN_11DB)
    vl = bat.read()
    mx = vl
    mn = vl
    for _ in range(11):
        v = bat.read()
        vl += v
        if v > mx:
            mx = v
        if v < mn:
            mn = v
    vl = vl - mx - mn
    if os.uname()[0] == "esp8266":
        vl *= 0.573
    else:
        vl *= 0.176
    return int(round(vl))
Example #4
0
class Temperature:
    def __init__(self, port):
        if port == 0:
            self.adc = ADC(5)
        elif port == 1:
            self.adc = ADC(7)
        elif port == 2:
            self.adc = ADC(3)
        else:
            raise Exception("Port# out of range")
        self.table = [[
            0, 2.5173462e1, -1.1662878, -1.0833638, -8.9773540 / 1e1,
            -3.7342377 / 1e1, -8.6632643 / 1e2, -1.0450598 / 1e2,
            -5.1920577 / 1e4
        ],
                      [
                          0, 2.508355e1, 7.860106 / 1e2, -2.503131 / 1e1,
                          8.315270 / 1e2, -1.228034 / 1e2, 9.804036 / 1e4,
                          -4.413030 / 1e5, 1.057734 / 1e6, -1.052755 / 1e8
                      ],
                      [
                          -1.318058e2, 4.830222e1, -1.646031, 5.464731 / 1e2,
                          -9.650715 / 1e4, 8.802193 / 1e6, -3.110810 / 1e8
                      ]]

    def read(self):
        volSum = 0
        for i in range(20):
            volSum += self.adc.read()
        volSum /= 20
        vol = (float(int(volSum) >> 5) / 1023.0 * 5.0 * 1000.0 - 350.0) / 54.16
        kind = -1
        value = 0.0
        if vol >= -6.478 and vol < 0:
            kind = 0
            offset = 8
        elif vol >= 0 and vol < 20.644:
            kind = 1
            offset = 9
        elif vol >= 20.644 and vol <= 54.900:
            kind = 2
            offset = 6
        if kind != -1:
            value = self.table[kind][offset]
            while offset >= 0:
                offset -= 1
                value = vol * value + self.table[kind][offset]
        return value
Example #5
0
class MPythonPin(Pin):
    def __init__(self, pin, mode=PinMode.IN):
        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG]:
            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG'")
        if pin == 3:
            raise TypeError("pin3 is used for resistance sensor")
        if pin == 4:
            raise TypeError("pin4 is used for light sensor")
        if pin == 10:
            raise TypeError("pin10 is used for sound sensor")
        self.id = pins_remap_esp32[pin]
        if mode == PinMode.IN:
            super().__init__(self.id, Pin.IN, Pin.PULL_UP)
        if mode == PinMode.OUT:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            super().__init__(self.id, Pin.OUT)
        if mode == PinMode.PWM:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            self.pwm = PWM(Pin(self.id), duty=0)
        if mode == PinMode.ANALOG:
            if pin not in [0, 1, 2, 3, 4, 10]:
                raise TypeError('the pin can~t be set as analog')
            self.adc = ADC(Pin(self.id))
            self.adc.atten(ADC.ATTN_11DB)
        self.mode = mode

    def read_digital(self):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return super().value()

    def write_digital(self, value):
        if not self.mode == PinMode.OUT:
            raise TypeError('the pin is not in OUT mode')
        super().value(value)

    def read_analog(self):
        if not self.mode == PinMode.ANALOG:
            raise TypeError('the pin is not in ANALOG mode')
        return self.adc.read()

    def write_analog(self, duty, freq=1000):
        if not self.mode == PinMode.PWM:
            raise TypeError('the pin is not in PWM mode')        
        self.pwm.freq(freq)
        self.pwm.duty(duty)
Example #6
0
class Flamingo:
    def __init__(self, machine_config):
        self.battery_reader = ADC(Pin(35))
        self.battery_reader.atten(ADC.ATTN_11DB)
        self.battery_threshold = machine_config['battery_threshold']
        self.battery_led = Pin(machine_config['battery_led'], Pin.OUT)
        self.battery_level = self.batteryCheck()

        #self.led_strip1 = Pin(led_strip1, Pin.OUT)
        #self.led_strip2 = Pin(led_strip2, Pin.OUT)

        self.button1 = Pin(machine_config['button1'], Pin.IN)
        self.button2 = Pin(machine_config['button2'], Pin.IN)
        self.button3 = Pin(machine_config['button3'], Pin.IN)

        self.battery_led.value(0)

        self.power_switch = Pin(machine_config['power_switch'], Pin.IN)
        esp32.wake_on_ext0(pin=self.power_switch, level=esp32.WAKEUP_ANY_HIGH)

    def batteryCheck(self):
        self.battery_level = (self.battery_reader.read() /
                              4095) * 2 * 3.3 * 1.1
        warning = False
        if (self.battery_level < self.battery_threshold):
            warning = True
        return self.battery_level

    def toggleLed(self, led):
        led.value(not (led.value()))

    def putToSleep(self):
        deepsleep()

    async def flashLed(self, json):
        json = ujson.loads(json)
        self.led_strip1.value(1)
        self.led_strip2.value(1)
        print("strips on")
        try:
            on_for = int(json['on_for'])
        except Exception:
            on_for = 1200
            print("invalid json: on_for")
        await asyncio.sleep_ms(on_for)
        self.led_strip1.value(0)
        self.led_strip2.value(0)
        print("strips off")
Example #7
0
class MPythonPin(Pin):
    def __init__(self, pin, mode=PinMode.IN):
        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG]:
            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG'")
        if pin == 3:
            raise TypeError("pin3 is used for resistance sensor")
        if pin == 4:
            raise TypeError("pin4 is used for light sensor")
        if pin == 10:
            raise TypeError("pin10 is used for sound sensor")
        self.id = pins_remap_esp32[pin]
        if mode == PinMode.IN:
            super().__init__(self.id, Pin.IN, Pin.PULL_UP)
        if mode == PinMode.OUT:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            super().__init__(self.id, Pin.OUT)
        if mode == PinMode.PWM:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            self.pwm = PWM(Pin(self.id), duty=0)
        if mode == PinMode.ANALOG:
            if pin not in [0, 1, 2, 3, 4, 10]:
                raise TypeError('the pin can~t be set as analog')
            self.adc = ADC(Pin(self.id))
            self.adc.atten(ADC.ATTN_11DB)
        self.mode = mode

    def read_digital(self):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return super().value()

    def write_digital(self, value):
        if not self.mode == PinMode.OUT:
            raise TypeError('the pin is not in OUT mode')
        super().value(value)

    def read_analog(self):
        if not self.mode == PinMode.ANALOG:
            raise TypeError('the pin is not in ANALOG mode')
        return self.adc.read()

    def write_analog(self, duty, freq=1000):
        if not self.mode == PinMode.PWM:
            raise TypeError('the pin is not in PWM mode')
        self.pwm.freq(freq)
        self.pwm.duty(duty)
Example #8
0
class Oven:
    def __init__(self):
        self.ignore = 50  # potentiometer offset
        self.pot = ADC(0)
        self.grill = PWM(Pin(14), 5000)
        self.top = 0

    def update_temp(self):
        pot_value = self.pot.read()
        print(pot_value)
        if pot_value > self.ignore:
            self.top = pot_value
        else:
            self.top = 0

        self.grill.duty(self.top)
Example #9
0
class Current:
    def __init__(self, port):
        if port == 0:
            self.adc = ADC(0)
        elif port == 1:
            self.adc = ADC(4)
        elif port == 2:
            self.adc = ADC(6)
        else:
            raise Exception("Port# out of range")

    def read(self):
        currentSum = 0
        for i in range(100):
            currentSum += (self.adc.read() * 3.3 / 4096 * 1000 - 1355) * 5
        return currentSum / 100
Example #10
0
class PM():
    def __init__(self):
        self.pin = [16, 5, 4, 0, 2, 14, 12, 13, 15, 3, 1, 9, 10]  #GPIO->pin
        self.pin1 = Pin(self.pin[1], Pin.OUT)
        self.pin8 = Pin(self.pin[8], Pin.OUT)
        self.pin8.value(1)
        self.adc = ADC(0)

    def pm_value(self):
        self.pin1.value(0)
        time.sleep_us(280)
        value = self.adc.read()
        time.sleep_us(40)
        self.pin1.value(1)
        time.sleep_us(9680)
        return value + 270
Example #11
0
def water_reader():
    """ Give the status of rain (True or False) """
    
    digital_input = ADC(0)
    water_level = digital_input.read()
    status = 0

    if water_level <= 100:
      status = 0
    else:
      status = 1

    return { 
      "status" : status,
      "level" : water_level
    }
def generate_seed(readings=20):
    """Generates a seed using noise from the analog pin.

    Args:
        readings (int): number of readings to take from the analog pin

    Returns:
        (str): number to use as a seed for the random generator
    """
    adc = ADC(0)
    seed = 0
    for s in range(readings):
        seed += adc.read()
        time.sleep_ms(10)
    print(''.join(['random seed: ', str(seed)]))
    return seed
Example #13
0
class soilADC:
    def __init__(self, pin):
        self.pin = pin
        try:
            #check if pin is available for input by checking dictionary of GPIOs
            if pin in adcDict:
                self.soil = ADC(Pin(pin))
            else:
                raise OSError
        except OSError:
            print('GPIO', pin, 'not suitable for ADC')
            print('Choose from:', adcDict)

    def moistureLevel(self):
        moisture = self.soil.read()
        return moisture
Example #14
0
def leer_dato_uv(pin_adc):
    """ Esta funcion es para leer los
    datos provenientes de los canales del ADC
    ademas esta la caracterizacion del sensor UV ML8511
    caracterizacion y = 0.1625x + 1.0
    x = (y - 1.0)/0.1625  mW/cm^2
    """
    adc = ADC(Pin(pin_adc))
    adc.atten(ADC.ATTN_11DB)
    adc.width(ADC.WIDTH_10BIT)
    y = adc.read() * 3.3 / 1024
    if y < 1:
        x = 0
    else:
        x = (y - 1.0) / 0.1625
    return x
Example #15
0
class Thumbslide:
    x_center = 1580
    y_center = 1769

    def __init__(self, pinx, piny, atten=ADC.ATTN_11DB, width=ADC.WIDTH_12BIT, tolerance=300):
        self._pinX = pinx
        self._pinY = piny
        self._tolerance = tolerance

        ADC.vref(vref=1150)

        self._x = ADC(Pin(self._pinX))
        self._x.atten(atten)
        self._x.width(width)

        self._y = ADC(Pin(self._pinY))
        self._y.atten(atten)
        self._y.width(width)

        self._angle = 0

    @property
    def X(self):
        return self._x

    @property
    def Y(self):
        return self._y

    def read(self):
        return array('i', self._x.read(), self._y.read())

    def readX(self):
        return self._x.read()

    def readY(self):
        return self._y.read()

    def _get_internal_calc_xy_dist(self, x, y):
        x = x if x else self._x.read()
        y = y if y else self._y.read()

        x_dist = x - Thumbslide.x_center
        y_dist = y - Thumbslide.y_center

        return x_dist, y_dist

    def moved(self, x=None, y=None):
        x_dist, y_dist = self._get_internal_calc_xy_dist(x, y)
        dist = math.sqrt(math.pow(x_dist, 2) + math.pow(y_dist, 2))
        return dist >= self._tolerance

    def angle(self, x=None, y=None):
        x_dist, y_dist = self._get_internal_calc_xy_dist(x, y)
        return math.atan2(y_dist, x_dist)
Example #16
0
def photo_resistor():
    client = MQTTClient(CLIENT_ID, SERVER)
    client.connect()
    sensor = ADC(0)

    while True:
        try:
            value = sensor.read()
            if isinstance(value, int):
                value = str(value)
                msg = value
                print("Message:", msg)
                client.publish(TOPIC, msg)
        except OSError:
            print("System Error")
        # sleep(3600) # one hour
        sleep(10)  # for testing
Example #17
0
class VoltMeter:
    """
    Driver measure DC battery voltage.
    """
    def __init__(self,
                 pin,
                 factor: float = 0.00718,
                 nSamples=100,
                 interval=100):
        """
        pin: Input pin number
        factor: Calibration coefficient
        nSamples: Number of averaged samples
        interval: Time interval in milliseconds between samples
        """

        self._pin = ADC(Pin(pin))
        self._pin.atten(ADC.ATTN_11DB)

        self._nSamples = nSamples
        self._interval = interval
        self._factor = factor

        self._sum: float = 0

        # Start the main task
        self.pulse_task = asyncio.create_task(self._run())

    async def _run(self):
        """
        Read the analog input and average the samples
        """
        while True:
            value = 0
            for _ in range(self._nSamples):
                value += self._pin.read()
                await asyncio.sleep_ms(self._interval)

            self._sum = value

    # ----------------------------------------------------------
    def getVoltage(self):
        """
        Returns the voltage (V) 
        """
        return self._sum / self._nSamples * self._factor
class BatteryVoltage:
    def __init__(self):
        # Setup ADC:
        self.batv = ADC(Pin(35))  # Analog A13 -- battery monitor

        # Set attenuation and bit width:
        self.batv.atten(ADC.ATTN_11DB)
        self.batv.width(ADC.WIDTH_12BIT)

    def read(self):
        return self.batv.read()

    def get_volt(self, val):
        return val * _SCALE

    def read_volt(self):
        return self.get_volt(self.read())
Example #19
0
def leer_polvo(DPIN, APIN):
    """Definici0n de pines
    para el sensor de polvo GP2Y1010AU0F
    """
    p13 = Pin(DPIN, Pin.OUT)
    adc = ADC(Pin(APIN))
    adc.atten(ADC.ATTN_11DB)
    adc.width(ADC.WIDTH_10BIT)
    #proceso de lectura para el sensor
    p13.off()
    utime.sleep_us(280)
    V1 = adc.read() * 3.3 / 1024
    utime.sleep_us(40)
    p13.on()
    utime.sleep_us(9680)
    dust_density = 0.17 * V1 - 0.1
    return dust_density
Example #20
0
class SaltData:
    def __init__(self, salt_pin=34, samples=120):
        self.SALT_PIN = Pin(salt_pin)
        self.SAMPLES = samples
        self.SALT_ADC = ADC(self.SALT_PIN)

    def salt_data(self):
        data_cumulative = []
        salt = 0
        for i in range(self.SAMPLES):
            data_cumulative.append(self.SALT_ADC.read())
            sleep_ms(20)
        for item in data_cumulative:
            if item == 0 or item == (self.SAMPLES - 1):
                pass
            else:
                salt += item
        return salt / (self.SAMPLES - 2)
Example #21
0
class linear_encoder:
    def __init__(self, adc_pin, a, b):

        from machine import ADC, Pin

        self.a = a
        self.b = b
        self.adc_in = ADC(Pin(adc_pin))
        self.adc_in.atten(ADC.ATTN_11DB)
        self.adc_in.width(ADC.WIDTH_12BIT)

    def read(self):
        x = self.adc_in.read()
        y = self.a * x + self.b
        return y

    def deinit(self):
        self.adc_in.deinit()
Example #22
0
def readMoistureSensor(CONFIG):
    import gc
    gc.collect()
    from machine import ADC
    gc.collect()

    # Set up ADC conversion
    adc = ADC(CONFIG['MOISTURE_PIN'])

    # Read Sensor and return value as %
    moisture = map_values(adc.read(), CONFIG['MOISTURE_SENSOR_AIR_VALUE'],
                          CONFIG['MOISTURE_SENSOR_WATER_VALUE'], 0, 100)
    if moisture > 100:
        moisture = 100
    elif moisture < 0:
        moisture = 0

    return moisture
Example #23
0
def leer_MQ(pin_adc, A, b, Ro):
    """ Esta funcion es para leer los
    datos de los sensores MQ que tienen un comportamiento
    ppm = ARo/Rs**(1/b)"""
    Rl = 1000  # Ohms
    Vref = 5  # Volts
    """ Lectura del canal analogico """
    adc = ADC(Pin(pin_adc))
    adc.atten(ADC.ATTN_11DB)
    adc.width(ADC.WIDTH_10BIT)
    Vo = adc.read() * 3.3 / 1024
    if Vo == 0:
        Rs = 0.0000000000000000001
        """ Conversion del voltaje a ppm"""
    else:
        Rs = Rl * (Vref - Vo) / Vo
    ppm = (A * Ro / Rs)**(1 / b)
    return ppm
class Temp():
    def __init__(self, pin):
        from machine import ADC, Pin
        self.adc = ADC(Pin(pin, Pin.IN))
        self.adc.atten(ADC.ATTN_11DB)  # 0-3.9V

    def value(self):
        adc_val = self.adc.read()
        Vout = (adc_val) * 3.9 / 4095.0
        if 0 < Vout and Vout < 3.9:  # -26.9 and 160.5
            Rt = int(((3.28 / Vout) - 1) *
                     51) / 100  # Sampling Resistance is 5.1K ohm * 51 / self.R
            # print(Rt)
            import math
            T1 = 1 / (_T + math.log(Rt) / B) - Tp
            return T1
        print('ADC Value Error!')
        return None
Example #25
0
class AnalogIn(object):
    """Basic analog input."""
    def __init__(self, pin, attn=ATTN_11DB, width=WIDTH_12BIT):
        self._pin = ADC(Pin(pin))
        self._pin.atten(ATTN[attn])
        self._pin.width(WIDTH[width])
        self._max_adc = 2**(9 + WIDTH[width]) - 1

    def deinit(self):
        self._pin = None

    @property
    def value(self):
        return self._pin.read()

    @property
    def max_adc(self):
        return self._max_adc
Example #26
0
class BatteryReader(Sensor):
    def __init__(self, pin_num=33, calibration_func=lambda x: x):
        """
        Initiate the battery reader algorithm
        :param pin_num: The pin number on the ESP32 to read off the battery voltage from
        :param calibration_func: A function to transform this class's best guess at the
        battery voltage into something closer. Accepts and returns a float.
        ESP32 ADC pins)
        """
        # Resistor values in the voltage divider design here:
        # https://www.notion.so/Preliminary-Design-Report-2d0a06e271614ae886e7a2b3f88f93aa
        self.R1 = 33.2
        self.R2 = 100

        self.calibration_func = calibration_func

        self.battery_pin = Pin(pin_num)

        # Set up variables to calculate battery voltage
        self.adc_battery_pin = ADC(self.battery_pin)
        self.adc_resolution = 1024

        # Set maximum voltage readable by ADC pin to 3.6V
        self.adc_battery_pin.atten(ADC.ATTN_11DB)
        self.max_readable_voltage = 3.6

    def read(self):
        """
        Calculates the voltage of the battery attached
        :return: A dictionary containing the battery voltage
        """
        adc_value = self.adc_battery_pin.read()
        print("ADC value for the battery pin: " + str(adc_value))

        voltage_at_adc_pin = (self.max_readable_voltage *
                              adc_value) / self.adc_resolution
        print("Voltage at pin: " + str(voltage_at_adc_pin))

        voltageDivFactor = (self.R1 + self.R2) / self.R2
        battery_voltage = self.calibration_func(voltage_at_adc_pin *
                                                voltageDivFactor)
        print("Battery voltage calibrated: " + str(battery_voltage))

        return {"voltage": battery_voltage}
Example #27
0
def getBattery():
    MAX_BATTERY_VOLTAGE = 4400  # 1.1V / 100kOhm * 400kOhm
    LOW_BATTERY_VOLTAGE = 3250
    MIN_BATTERY_VOLTAGE = 3005

    adc = ADC(Pin(34))          # create ADC object on ADC pin
    adc.atten(ADC.ATTN_6DB)     # set 6 dB input attenuation (voltage range roughly 0.0v - 2 v)
    adc.width(ADC.WIDTH_12BIT)  # set 12 bit return values (returned range 0-4095)

    count = adc.read()          # read value using the newly configured attenuation and width
    Vbat = count*1000/512
    print ('Battery Voltage = {} mV'.format(int(round(Vbat,0))))

    if Vbat > LOW_BATTERY_VOLTAGE:
        dot(7, 7, GREEN)
    elif Vbat >= MIN_BATTERY_VOLTAGE and Vbat <= LOW_BATTERY_VOLTAGE:
        dot(7, 7, YELLOW)
    else:
        dot(7, 7, RED)
Example #28
0
class Analog(homie.Property):
    maxes=[1,1.34,2,3.6]
    def __init__(self, prop_id, prop_name, pin, period, bits=10, attn=0):
        super(Analog, self).__init__(prop_id, prop_name, "float", None, "0:{}".format(Analog.maxes[attn]), 0)
        if config["esp32"]:
            pin = Pin(pin)
        self.adc = ADC(pin)
        if config["esp32"]:
            self.adc.atten(attn)
            self.adc.width(bits-9)
        self.period = period
        self.range = (2**bits)-1
        self.max = Analog.maxes[attn]

    def periodic(self, cur_time):
        if (cur_time % self.period) == 0:
            value = self.adc.read()
            print(value)
            self.send_value(str(self.max*value/self.range))
Example #29
0
def __get_resistance():
    """
    Returns the resistance of the sensor in kOhms // -1 if not value got in pin
    10.0 - 'RLOAD' The load resistance on the board
    """
    global __ADC, __ADC_PROP
    if __ADC is None:
        if 'esp8266' in platform:
            __ADC = ADC(physical_pin('co2'))  # 1V measure range
            __ADC_PROP = (1023, 1.0)
        else:
            __ADC = ADC(Pin(physical_pin('co2')))
            __ADC.atten(ADC.ATTN_11DB)  # 3.6V measure range
            __ADC.width(ADC.WIDTH_10BIT)  # Default 10 bit ADC
            __ADC_PROP = (1023, 3.6)
    value = __ADC.read()
    if value == 0:
        return -1
    return (float(__ADC_PROP[0]) / value - 1.) * 10.0
Example #30
0
class GP2D12:
    def __init__(self, pin):
        self.pin = Pin(pin)
        self.adc = ADC(self.pin)
        self.adc.atten(self.adc.ATTN_6DB)

    def get_dist(self):
        """Retourne la distance en centimètres. La formule a été
        calculée a partir de mesures manuelles et d'interpolation
        polynomiale avec numpy.
        """

        x = self.adc.read()
        d = -1.525*10**-8*x**3+8.809*10**-5*x**2-0.1596*x+112.6
        if d > 90:
            return 100
        elif d < 25:
            return 0
        return d
Example #31
0
class SoilSensor:
    def __init__(self, adc_pin, air_value, water_value):
        self._adc = ADC(Pin(adc_pin))
        self._adc.atten(ADC.ATTN_11DB)

        self._air_value = air_value
        self._water_value = water_value

    def read_data(self):
        moisture_value = self._adc.read()
        moisture_level = self._to_percent(moisture_value)
        category = self._categorize_moisture_value(moisture_value)

        return array('i', (moisture_value, moisture_level, category))

    def _to_percent(self, moisture_value):
        if moisture_value < self._water_value:
            converted_value = 0
        elif moisture_value > self._air_value:
            converted_value = 100
        else:
            delta = self._air_value - moisture_value
            divisor = self._air_value - self._water_value
            converted_value = int((delta / divisor) * 100)

        return converted_value

    def _categorize_moisture_value(self, moisture_value):
        intervals = int((self._air_value - self._water_value) / 3)
        upper_water_value = self._water_value + intervals
        lower_air_value = self._air_value - intervals

        if self._water_value <= moisture_value < upper_water_value:
            category = VERY_WET
        elif upper_water_value <= moisture_value < lower_air_value:
            category = WET
        elif lower_air_value <= moisture_value <= self._air_value:
            category = DRY
        else:
            category = UNCATEGORIZED

        return category
Example #32
0
class Battery:
    def __init__(self, transport=None):
        self.ID = 5
        self.transport = transport
        self.adc = None
        self._setup()

    def _setup(self):
        self.adc = ADC(Pin(battery_pins['adc']))
        self.adc.atten(ADC.ATTN_11DB)

    def _format(self, reading):
        return "{},{},{:.2f}".format(location_id, self.ID,
                                     self._convert_to_percentage(reading))

    def _send(self, payload):
        # If has transnport then send
        if self.transport is None:
            print('Cannot send battery reading without a defined transport')
            return

        self.transport.broadcast(payload)

    def _convert_to_percentage(self, reading):
        percent = int((reading - 0) * (100 - 0) / (4095 - 0) + 0)

        if percent < 0:
            return 0

        if percent > 100:
            return 100

        return percent

    def read(self, autosend=True, autosleep=True):
        raw_reading = self.adc.read()

        if autosend:
            payload = self._format(raw_reading)
            self._send(payload)

        return raw_reading
# Complete project details at https://RandomNerdTutorials.com
# Created by Rui Santos

from machine import Pin, ADC, PWM
from time import sleep

led = Pin(2, Pin.OUT)
button = Pin(15, Pin.IN)

#Configure ADC for ESP32
pot = ADC(Pin(34))
pot.width(ADC.WIDTH_10BIT)
pot.atten(ADC.ATTN_11DB)

#Configure ADC for ESP8266
#pot = ADC(0)

led_pwm = PWM(Pin(4),5000)

while True:
  button_state = button.value()
  led.value(button_state)

  pot_value = pot.read()
  led_pwm.duty(pot_value)

  sleep(0.1)
Example #34
0
class ADCSensor:
    def __init__(self,pin):
        self.adc=ADC(Pin(pin))
        self.adc.atten(ADC.ATTN_11DB) 
    def read(self):
        return self.adc.read()