Example #1
0
class Battery:
    """
    TODO: Have to calibrate the results voltage using Vref on efuse.
    But the necessary functions seem not to be implemented to MicroPython yet.

      * esp_adc_cal_characterize()
      * esp_adc_cal_raw_to_voltage()

    This module calculate current battery voltage roughly for now.
    """
    def __init__(self, battery_pin, battery_resistance_num, width, atten):
        self._battery_adc = ADC(Pin(battery_pin))
        self._battery_adc.width(width)
        self._battery_adc.atten(atten)

        self._battery_resistance_num = battery_resistance_num

    def get_voltage(self, sampling_count=32, round_count=3):
        raw_value = sum(
            [self._battery_adc.read()
             for _ in range(sampling_count)]) / sampling_count
        voltage = raw_value * self._battery_resistance_num / 1000
        return round(voltage, round_count)

    def deinit(self):
        """ Deinitialize the battery pin ADC """
        self._battery_adc.deinit()
Example #2
0
class A_Pin(D_Pin):
    def __init__(self, pin):
        #self.pin = pin
        self.dac = None
        self.adc = None
        if pin in [25, 26]:
            self.dac = DAC(Pin(pin))
        if pin in [32, 33]:
            self.adc = ADC(Pin(pin))
            self.adc.atten(ADC.ATTN_11DB)
            self.adc.width(ADC.WIDTH_10BIT)
        super().__init__(pin)

    def write_analog(self, value):
        if self.pin not in [25, 26]:
            # print("This pin feature is not supported")
            super().write_analog(value)
        else:
            self.dac.write(value)

    def read_analog(self):
        if self.adc != None:
            return self.adc.read()
        else:
            print('This Pin does not support ADC')
            return None
Example #3
0
class BatReader9:
    def __init__(self, pin=34):
        self.batPin = ADC(Pin(pin))
        self.batPin.atten(ADC.ATTN_11DB)
        self.batPin.width(ADC.WIDTH_12BIT)

    def readBatVoltage(self):
        try:
            volt = round(
                self.batPin.raw_to_voltage(self.batPin.read()) * 2 / 1000.0, 2)
        except AttributeError:
            volt = round(self.batPin.read() * MAX_VOLTAGE / 4096.0, 2)
        if volt < BAT_MIN:
            volt = BAT_MIN
        elif volt > BAT_MAX:
            volt = BAT_MAX

        return volt

    def readBatPercent(self):
        percent = round(
            (self.readBatVoltage() - BAT_MIN) / (BAT_MAX - BAT_MIN) * 100, 2)
        if percent < 0:
            percent = 0
        elif percent > 100:
            percent = 100
        return percent

    def read(self):
        return self.batPin.read()
def run():

    # creates a PWM instance (led) at pin number 32 and with a max frequency of 7800
    led = PWM(Pin(32), freq=78000)

    # creates a ADC instance (sensor) at analogue pin A4 or pin number 36
    sensor = ADC(Pin(36))
    # set attenuation at 11db
    sensor.atten(3)
    #set width to 11 bit
    sensor.width(3)

    # Creates a writeable text file
    f = open('fixedPWM.txt', 'w')
    f.write('FIXED_PWM_VALUE\n')

    print(sensor.read())

    for i in range(100):
        led.duty(200)
        time.sleep_ms(30)
        avgReading = 0
        for j in range(50000):
            avgReading += sensor.read()
        x = str(avgReading / 50000)
        print(x)
        f.write(x + ',')

    f.close()
Example #5
0
def leer_MQ2(pin_adc):
    """ Lectura del canal analogico """
    adc = ADC(Pin(pin_adc))
    adc.atten(ADC.ATTN_11DB)
    adc.width(ADC.WIDTH_10BIT)
    Vo = adc.read()
    return Vo
Example #6
0
def setup():
    #setup light to voltage sensor
    adc = ADC(Pin(34))  # define the pin as an analog-to-digital converter
    adc.atten(ADC.ATTN_11DB)  # set the atten..?
    adc.width(ADC.WIDTH_12BIT)  # set the width of the available bits

    #setup measurement LED for PWM
    dpin = Pin(12)
    pwm = PWM(dpin)
    pwm.freq(78000)  # set frequency
    pwm.duty(0)  # set current

    #setup RGB LED
    red = Pin(15, Pin.OUT)
    green = Pin(32, Pin.OUT)
    blue = Pin(14, Pin.OUT)

    #setup embedded LED
    emb = Pin(13, Pin.OUT)

    #setup button 1
    button = Pin(33, Pin.IN, Pin.PULL_UP)

    # setup button 2
    button2 = Pin(27, Pin.IN, Pin.PULL_UP)

    return (adc, pwm, button, button2, red, green, blue, emb)
Example #7
0
class Mcp9700Temp(SensorBase):

    V_SUPPLY = 3.3
    RANGE_MAX = 1024
    OFFSET = 0.4
    DIV = 0.01

    def __init__(self, temp_pin_nr, en_supply_obj):
        self.TempAdc = ADC(Pin(temp_pin_nr))
        self.TempEn = en_supply_obj
        self.TempAdc.atten(ADC.ATTN_11DB)
        self.TempAdc.width(ADC.WIDTH_10BIT)

    def Read(self):
        val = self.TempAdc.read()
        # val = self._RawToCelsius(val)
        return val

    def Enable(self):
        self.TempEn.Enable()

    def Disable(self):
        self.TempEn.Disable()

    @staticmethod
    def _RawToCelsius(raw_temp):
        cel_temp = raw_temp * (Mcp9700Temp.V_SUPPLY / Mcp9700Temp.RANGE_MAX)
        cel_temp -= Mcp9700Temp.OFFSET
        cel_temp /= Mcp9700Temp.DIV
        return cel_temp
class LightSensorGl5528:
    def __init__(self, name: str, pin_num: int) -> None:
        """
        Analog light sensor GL5528 for the tlvlp.iot project

        Tested on ESP32 MCUs
        :param pin_num: Analog input pin number for reading measurements
        """
        reference = "gl5528|"
        self.id = reference + name
        self.sensor = ADC(Pin(pin_num, Pin.IN, Pin.PULL_DOWN))
        self.sensor.atten(ADC.ATTN_11DB)
        self.sensor.width(ADC.WIDTH_10BIT)

    async def read_percent(self, delay_ms=300) -> tuple:
        """
        :param delay_ms: a set delay before the reading is done
        :return: the percentage of the read value, using integer rounding
        """
        await asyncio.sleep_ms(delay_ms)
        analog_read = self.sensor.read()
        return self.id, self.convert_to_percent(analog_read)

    def convert_to_percent(self, reading) -> int:
        return int((1023 - reading) / 10.23)
Example #9
0
def read_moisture(num_readings=21):
    if num_readings % 2 == 0:
        num_readings += 1

    adc = ADC(SOILpin)
    adc.atten(
        ADC.ATTN_11DB
    )  # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
    adc.width(ADC.WIDTH_9BIT)  # set 9 bit return values (returned range 0-511)
    readings = _get_readings(num_readings, adc)
    if num_readings <= 3:
        return int(sum(readings) / len(readings))
    median_index = int((num_readings - 1) / 2)
    readings = sorted(readings)

    min_index = int(median_index - median_index / 2)
    max_index = int(median_index + median_index / 2)
    sensible_values = readings[min_index:max_index]
    median = readings[median_index]
    average = avg(sensible_values)
    total_average = avg(readings)

    print("all readings: ", readings)
    print("sensible readings: ", sensible_values)
    print("median:%d, mid-50-avg:%d, avg:%d" %
          (median, average, total_average))
    return avg([median, average, total_average])
Example #10
0
class ODSensor:
    # frequency and pins may need to be changed
    def __init__(self,LEDPin, sensorPin): #25,39.   26,36.
        self.DAC_MAX = 255
        self.DAC_Vmax = 3.15
        self.DAC_Vmin = 0.09

        self.led = DAC(Pin(25), bits=8) 
        self.sensor = ADC(Pin(39)) #Green
        #self.sensor.atten(ADC.ATTN_11DB)
        self.sensor.width(ADC.WIDTH_10BIT)

    # return a single measurement
    def measure(self, intensity):
        self.led.write(intensity)
        data = []
        
        #get 120 measurements
        for j in range(120):
            data.append(self.sensor.read())

        data.sort() #sort data increasing
        sum_middle = sum(data[30:90]) #find sum of middle numbers
        avg = sum_middle / 60 #find average of middle numbers
        
        return avg
class VoltageMonitor():
    NUM_READINGS = 10
    READING_PERIOD_MS = 100
    V_BAT_CALIBRATION = 0.001757
    V_USB_CALIBRATION = 0.001419    
    def __init__(self):
        log.info('VMON:init')
        self.vbat_pin = ADC(Pin(35))
        self.vbat_pin.atten(ADC.ATTN_11DB)
        self.vbat_pin.width(ADC.WIDTH_12BIT)
        self.vusb_pin = ADC(Pin(39))
        self.vusb_pin.atten(ADC.ATTN_11DB)
        self.vusb_pin.width(ADC.WIDTH_12BIT)
        loop = asyncio.get_event_loop()
        loop.create_task(self.run_v_monitor()) 
                
    async def run_v_monitor(self):
        v_bat_sample_sum = 0
        v_usb_sample_sum = 0
        
        while True:
            # take average of readings
            for _ in range(VoltageMonitor.NUM_READINGS):
                v_bat_sample_sum += self.vbat_pin.read()
                v_usb_sample_sum += self.vusb_pin.read()
                await asyncio.sleep_ms(VoltageMonitor.READING_PERIOD_MS)
                
            repo.add('vbat', v_bat_sample_sum * VoltageMonitor.V_BAT_CALIBRATION / VoltageMonitor.NUM_READINGS)
            repo.add('vusb', v_usb_sample_sum * VoltageMonitor.V_USB_CALIBRATION / VoltageMonitor.NUM_READINGS)
            
            v_bat_sample_sum = 0
            v_usb_sample_sum = 0
            await asyncio.sleep(0)
Example #12
0
class Battery:
    """
    TODO: Have to calibrate the results voltage using Vref on efuse.
    But the necessary functions seem not to be implemented to MicroPython yet.
      * esp_adc_cal_characterize()
      * esp_adc_cal_raw_to_voltage()

    This module calculate current battery voltage roughly for now.
    """

    _adc1_pin = object()
    _sampling_count = 64
    _battery_resistance_num = 0

    def __init__(self, pin, resistance_num, width, atten):
        self._adc1_pin = ADC(Pin(pin))
        self._adc1_pin.width(width)
        self._adc1_pin.atten(atten)

        self._battery_resistance_num = resistance_num

    def get_voltage(self):
        reading = 0
        for i in range(0, self._sampling_count):
            reading += self._adc1_pin.read()

        reading /= self._sampling_count

        return reading * self._battery_resistance_num / 1000
Example #13
0
class Temperature:
    def __init__(self):
        self.adcP1 = ADC(Pin(33))  # create ADC object on ADC pin
        self.adcP1.atten(
            ADC.ATTN_11DB
        )  # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
        self.adcP1.width(
            ADC.WIDTH_12BIT)  # set 9 bit return values (returned range 0-511)

        self.several = RingBuffer(10)
        self.several.initialize(self.getTemperature)

    def getTemperature(self):
        raw = self.adcP1.read()
        voltage = (
            raw / 1.13
        )  # from observation & calculation. 290mV gives 240 reading but 1.5V gives 1700 reading. 4096 / 3600 also = 1.13 so using that
        tempC = voltage * 0.1

        #if 'several' in vars(Temperature):
        self.several.append(tempC)

        return tempC

    def getAvTemp(self):
        return sum(self.several.get()) / len(self.several.get())
Example #14
0
    def _read_adc():
        # exit if adc resolution was not set
        if not sharp1080.INIT:
            return 0

        from machine import ADC, Pin

        conversion_factor = 3.3 / ((2**sharp1080.ADC_RES) - 1)

        # raspberry pico
        if sharp1080.INIT == sharp1080.PICO:
            adc = ADC(Pin(sharp1080.ADC_PIN))
            raw = adc.read_u16()

        # esp8266
        if sharp1080.INIT == sharp1080.ESP8266:
            adc = ADC(0)
            raw = adc.read()

        # esp32
        if sharp1080.INIT == sharp1080.ESP32:
            adc = ADC(Pin(sharp1080.ADC_PIN))
            adc.atten(ADC.ATTN_11DB)
            adc.width(ADC.WIDTH_12BIT)
            raw = adc.read()

        volt = raw * conversion_factor
        if sharp1080.DEBUG: print("adc_read: " + str(volt) + "V")
        return volt
Example #15
0
def light():
    adc = ADC(Pin(36))
    adc.atten(ADC.ATTN_11DB)
    adc.width(ADC.WIDTH_12BIT)
    value = int(100 - ((adc.read() - MIN_VALUE) /
                       (MAX_VALUE - MIN_VALUE) * 100))
    value = 100 if value > 100 else value
    value = 0 if value < 0 else value
    return value
Example #16
0
def leer_dato(pin_adc):
    """ Esta funcion es para leer los
    datos provenientes de los canales del
    ADC"""
    adc = ADC(Pin(pin_adc))
    adc.atten(ADC.ATTN_11DB)
    adc.width(ADC.WIDTH_10BIT)
    adc_pot = adc.read() * 3.0 / 1024
    return adc_pot
Example #17
0
def getBatV():
    adc = ADC(Pin(34))  # create ADC object on ADC pin
    #adc.read()                  # read value, 0-4095 across voltage range 0.0v - 1.0v

    adc.atten(
        ADC.ATTN_11DB
    )  # set 11dB input attentuation (voltage range roughly 0.0v - 3.6v)
    adc.width(ADC.WIDTH_9BIT)  # set 9 bit return values (returned range 0-511)
    return round(adc.read() / 512 * 3.6 * 2, 2)
Example #18
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)
def get_scaled_adc(_pin):
    adc = ADC(Pin(_pin))  # create ADC object on ADC pin
    adc.atten(
        ADC.ATTN_11DB
    )  # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
    adc.width(
        ADC.WIDTH_11BIT)  # set 9 bit return values (returned range 0-511)
    return scale(
        adc.read(), (0, 520),
        (0,
         100))  # read value using the newly configured attenuation and width
Example #20
0
class VBatData:
    def __init__(self, vbat_pin=33):
        self.VBAT_PIN = Pin(vbat_pin)
        self.VBAT_ADC = ADC(self.VBAT_PIN)
        self.VBAT_ADC.atten(ADC.ATTN_11DB)
        self.VBAT_ADC.width(ADC.WIDTH_12BIT)
        self.VBAT_REF = 1100

    def read_bat(self):
        vbat_raw = self.VBAT_ADC.read() / 4095 * 2 * 3.3 * self.VBAT_REF
        return vbat_raw
Example #21
0
def get_ground_humidity(pin=34):
    adc = ADC(Pin(pin))
    adc.atten(ADC.ATTN_11DB)
    adc.width(ADC.WIDTH_9BIT)
    min = 156  # water
    max = 422  # air
    val = adc.read()
    if val <= min:  # water
        return 100.0
    if val >= max:  # air
        return 0.0
    return 100 - ((val - min) / (max - min)) * 100
Example #22
0
File: o.py Project: uraich/mpy_ucad
 async def heartbeat(self):
     while True:
         adc = ADC(Pin(ADC_PIN))
         adc.atten(ADC.ATTN_11DB)
         adc.width(ADC.WIDTH_12BIT)
         self.led(not self.led())
         print(adc.read())
         sleep_ms(200)
         self.led(not self.led())
         print(adc.read())
         sleep_ms(200)
         await asyncio.sleep_ms(0)
Example #23
0
class VoltageSensor(SensorBase):

    RANGE_MAX = const(1024)

    NUM_VOLTAGES = const(4)
    VoltageList = [1.0, 1.34, 2.0, 3.6]
    AttenuationList = [
        ADC.ATTN_0DB, ADC.ATTN_2_5DB, ADC.ATTN_6DB, ADC.ATTN_11DB
    ]

    def __init__(self,
                 pin_nr: int,
                 en_supply_obj=None,
                 max_voltage: float = 3.3):
        self.VoltAdc = ADC(Pin(pin_nr))
        self.Supply = en_supply_obj

        self.VoltAdc.atten(self._VoltageToAttenuation(max_voltage))
        self.VoltAdc.width(ADC.WIDTH_12BIT)

    def Read(self):
        val = self.VoltAdc.read()
        # val = self._RawToVoltage(val)
        return val

    def Enable(self):
        self._EnableSupply()

    def Disable(self):
        self._DisableSupply()

    def _RawToVoltage(self, raw):
        volt = raw * (3.3 / self.RANGE_MAX)
        return volt

    def _EnableSupply(self):
        if self.Supply is not None:
            self.Supply.Enable()

    def _DisableSupply(self):
        if self.Supply is not None:
            self.Supply.Disable()

    def _VoltageToAttenuation(self, voltage: float):
        for i in range(0, self.NUM_VOLTAGES):
            if voltage <= self.VoltageList[i]:
                print("[VoltSensor] Selected attenuation {}, max voltage {}".
                      format(self.AttenuationList[i], self.VoltageList[i]))
                return self.AttenuationList[i]
        raise Exception(
            "Voltage too high for ADC input. No attenuation level found.")
Example #24
0
class battery:
    def __init__(self, vadc=35):
        self.VBAT = ADC(Pin(vadc))
        self.VBAT.width(ADC.WIDTH_12BIT)
        self.VBAT.atten(ADC.ATTN_11DB)
        self.CALIB = 3.6 * 2
        self.VMIN = round(3.4 / self.CALIB * 4096)
        self.VMAX = round(4.3 / self.CALIB * 4096)

    def voltage(self):
        return self.VBAT.read() / 4096 * self.CALIB

    def percentage(self):
        return (self.VBAT.read() - self.VMIN) / (self.VMAX - self.VMIN)
Example #25
0
def setup_pins():
    """
    PIN_OUT so we can toggle power to ADC device
    PIN_IN to read ADC value
    """
    # Start accepting input from ADC device
    pin_in = Pin(PIN_IN, Pin.IN)
    adc = ADC(pin_in)
    # Calibrate ADC
    # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
    adc.atten(ADC.ATTN_11DB)
    # set bit return values (returned range 0-4095)
    adc.width(ADC.WIDTH_12BIT)
    pin_out = Pin(PIN_OUT, Pin.OUT)
    return adc, pin_out
Example #26
0
def __init_ADC():
    """
    Setup ADC
    read        0(0V)-1024(1,2-3,3V)
    """
    global __ADC, __ADC_PROP
    if __ADC is None:
        if 'esp8266' in platform:
            __ADC = ADC(physical_pin('ph'))  # 1V measure range
            __ADC_PROP = (1023, 1.0)
        else:
            __ADC = ADC(Pin(physical_pin('ph')))
            __ADC.atten(ADC.ATTN_11DB)  # 3.6V measure range
            __ADC.width(ADC.WIDTH_10BIT)  # Default 10 bit ADC
            __ADC_PROP = (1023, 3.6)
    return __ADC
Example #27
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 #28
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 #29
0
def __init_ADC():
    """
    Setup ADC
    """
    global __ADC
    if __ADC is None:
        from machine import ADC, Pin
        from LogicalPins import get_pin_on_platform_by_key
        if 'esp8266' in platform:
            __ADC = ADC(get_pin_on_platform_by_key('adc_2'))
        else:
            __ADC = ADC(Pin(get_pin_on_platform_by_key('adc_2')))
            # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
            __ADC.atten(ADC.ATTN_11DB)
            # set 9 bit return values (returned range 0-511)
            __ADC.width(ADC.WIDTH_9BIT)
    return __ADC
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())
# 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)