Python machine.ADC Examples

The following are 28 code examples of machine.ADC(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module machine , or try the search function .
Example #1
Source File: __init__.py    From platypush with MIT License 7 votes vote down vote up
def adc_read(self, pin: int = 0, **kwargs) -> int:
        """
        Read an analog value from a PIN. Note that the ESP8266 only has one analog PIN, accessible on
        the channel ``0``. If you are interested in the actual voltage that is measured then apply
        ``V = Vcc * (value/1024)``, where ``Vcc`` is the supply voltage provided to the device (usually 3V if
        connected to the Vcc PIN of an ESP8266).

        :param pin: GPIO PIN number (default: 0).
        :param kwargs: Parameters to pass to :meth:`platypush.plugins.esp.EspPlugin.execute`.
        :return: A value between ``0`` and ``1024``.
        """
        code = '''
import machine
adc = machine.ADC({pin})
adc.read()
'''.format(pin=pin)

        response = self.execute(code, **kwargs)
        return int(response.output) 
Example #2
Source File: system.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, settings):
        """
        Initialized ADC unit.
        """

        super().__init__(settings)

        # ADC Pin to sample from.
        self.pin = None

        # Main resistor value (R1).
        self.resistor_r1 = None

        # Resistor between input pin and ground (R2).
        self.resistor_r2 = None

        # Reference to platform ADC object.
        self.adc = None

        self.setup() 
Example #3
Source File: amux.py    From pysmartnode with MIT License 5 votes vote down vote up
def __init__(self, s0, s1, s2, s3=None, mux=None, adc=None, return_voltages=False):
        """ It is possibile to initialize with:
            - pin numbers (or string on esp8266)
            - mux object and pin numbers (of mux pins)
            - Pin objects (either from machine or mux Pin objects [no mux object needed], or Arduino)
            :type return_voltages: bool, True returns voltages on .read() else raw adc value
            :type mux: Mux object if a multiplexer is used
            :type adc: ADC pin number (esp32) or None (esp8266) or Arduino ADC object or any ADC object
            Amux uses default return values of ADC in .read()
            --> On esp8266/esp32 raw, on esp32_LoBo voltage
            s3 is optional, only needed if 16 pins are used, 8 pins possible with s0-s2.
            Amux can be read like a list: value=amux[2]
        """
        if mux:
            # MUX pin numbers, not pin objects
            self._s0 = s0
            self._s1 = s1
            self._s2 = s2
            self._s3 = s3
            self._mux = mux
        else:
            # Pin will take care of returning the correct object
            self._s0 = Pin(s0, machine.Pin.OUT)
            self._s1 = Pin(s1, machine.Pin.OUT)
            self._s2 = Pin(s2, machine.Pin.OUT)
            if s3:
                self._s3 = Pin(s3, machine.Pin.OUT)
        if s3:
            self.__size = 16
        else:
            self.__size = 8
        self._return_voltages = return_voltages
        self._adc = _ADC(
            adc)  # no matter what adc is, _ADC will return an object with the unified ADC API 
Example #4
Source File: system.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def power_off(self):
        """Shut down ADC."""
        log.info('Turning off ADC')
        self.adc.deinit() 
Example #5
Source File: system.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def setup(self):
        """
        - Configure the appropriate resistor values for computing the voltage.
        - Setup ADC for sampling.
        """

        self.pin = self.settings.get('pin')
        self.resistor_r1 = self.settings.get('resistor_r1')
        self.resistor_r2 = self.settings.get('resistor_r2')
        self.adc_attenuation_db = self.settings.get('adc_attenuation_db', 6.0)
        self.reading_key = self.settings.get('type')

        assert type(self.pin) is str, 'VCC Error: Voltage divider ADC pin invalid'
        assert type(self.resistor_r1) is int, 'VCC Error: Voltage divider resistor value "resistor_r1" invalid'
        assert type(self.resistor_r2) is int, 'VCC Error: Voltage divider resistor value "resistor_r2" invalid'
        assert type(self.adc_attenuation_db) is float, 'VCC Error: ADC attenuation value "adc_attenuation_db" invalid'

        # ADC channel used for sampling the raw value.
        if self.platform_info.vendor == self.platform_info.MICROPYTHON.Vanilla:
            from machine import ADC, Pin
            self.adc = ADC(Pin(int(self.pin[1:])))

        elif self.platform_info.vendor == self.platform_info.MICROPYTHON.Pycom:
            from machine import ADC
            self.adc = ADC(id=0)

        else:
            raise NotImplementedError('machine.ADC support is not implemented on this platform')

        # Configure attenuation.
        if self.adc_attenuation_db == 0.0:
            self.adc_atten = ADC.ATTN_0DB
        elif self.adc_attenuation_db == 2.5:
            self.adc_atten = ADC.ATTN_2_5DB
        elif self.adc_attenuation_db == 6.0:
            self.adc_atten = ADC.ATTN_6DB
        elif self.adc_attenuation_db == 11.0:
            self.adc_atten = ADC.ATTN_11DB
        else:
            raise ValueError('ADC attenuation value (adc_attenuation_db) not allowed : {}'.format(self.adc_attenuation_db)) 
Example #6
Source File: AnalogSensor.py    From illuminOS with MIT License 5 votes vote down vote up
def __init__(self, pin, vhigh, vlow):
        self.sensor = machine.ADC(pin)
        self.vhigh = vhigh
        self.vlow = vlow 
Example #7
Source File: adctest.py    From micropython-async with MIT License 5 votes vote down vote up
def adctest():
    asyncio.create_task(signal())
    adc = AADC(ADC(pyb.Pin.board.X1))
    await asyncio.sleep(0)
    adc.sense(normal=False)  # Wait until ADC gets to 5000
    value =  await adc(5000, 10000)
    print('Received', value, adc.read_u16(True))  # Reduce to 12 bits
    adc.sense(normal=True)  # Now print all changes > 2000
    while True:
        value = await adc(2000)  # Trigger if value changes by 2000
        print('Received', value, adc.read_u16(True)) 
Example #8
Source File: adctest.py    From micropython-async with MIT License 5 votes vote down vote up
def signal():  # Could use write_timed but this prints values
    dac = pyb.DAC(1, bits=12, buffering=True)
    v = 0
    while True:
        if not v & 0xf:
            print('write', v << 4)  # Make value u16 as per ADC read
        dac.write(v)
        v += 1
        v %= 4096
        await asyncio.sleep_ms(50) 
Example #9
Source File: batmon.py    From py-mpu6050 with GNU General Public License v3.0 5 votes vote down vote up
def battery():
    vcc = machine.ADC(1)
    return vcc.read() 
Example #10
Source File: batmon.py    From py-mpu6050 with GNU General Public License v3.0 5 votes vote down vote up
def set_adc_mode(mode):
    sector_size = bdev.SEC_SIZE
    flash_size = esp.flash_size() # device dependent
    init_sector = int(flash_size / sector_size - 4)
    data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
    if data[107] == mode:
        return  # flash is already correct; nothing to do
    else:
        data[107] = mode  # re-write flash
        esp.flash_erase(init_sector)
        esp.flash_write(init_sector * sector_size, data)
        print("ADC mode changed in flash; restart to use it!")
        return 
Example #11
Source File: analog.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, name, precision=1, threshold=None,
                 on_change=None, report_change=True, filter=None):
        self.precision = precision
        self.threshold = None
        if threshold is not None:
            self.threshold = max(1, min(threshold, 1023))
        self.last_value = None
        Device.__init__(self, name, ADC(0), on_change=on_change,
                        report_change=report_change, filter=filter) 
Example #12
Source File: analog.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, name, precision=1, threshold=None,
                 on_change=None, report_change=True, filter=None):
        self.precision = precision
        self.threshold = None
        if threshold is not None:
            self.threshold = max(1, min(threshold, 1023))
        self.last_value = None
        Device.__init__(self, name, ADC(0), on_change=on_change,
                        report_change=report_change, filter=filter) 
Example #13
Source File: analog.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, name, precision=1, threshold=None,
                 on_change=None, report_change=True, filter=None):
        self.precision = precision
        self.threshold = None
        if threshold is not None:
            self.threshold = max(1, min(threshold, 1023))
        self.last_value = None
        Device.__init__(self, name, ADC(0), on_change=on_change,
                        report_change=report_change, filter=filter) 
Example #14
Source File: analog.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, name, precision=1, threshold=None,
                 on_change=None, report_change=True, filter=None):
        self.precision = precision
        self.threshold = None
        if threshold is not None:
            self.threshold = max(1, min(threshold, 1023))
        self.last_value = None
        Device.__init__(self, name, ADC(0), on_change=on_change,
                        report_change=report_change, filter=filter) 
Example #15
Source File: analog.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def __init__(self, name, precision=1, threshold=None,
                 on_change=None, report_change=True, filter=None):
        self.precision = precision
        self.threshold = None
        if threshold is not None:
            self.threshold = max(1, min(threshold, 1023))
        self.last_value = None
        Device.__init__(self, name, ADC(0), on_change=on_change,
                        report_change=report_change, filter=filter) 
Example #16
Source File: adc_esp8266.py    From thingflow-python with Apache License 2.0 5 votes vote down vote up
def __init__(self, sensor_id='adc', min_rd=0, max_rd=1024,
                 min_val=0, max_val=1):
        '''Initialize sensor

           min_rd and max_rd are used in sample for sensor calibration
           min_val and max_val are the sample limits
        '''
        self.sensor_id = sensor_id
        self.min_rd = min_rd
        self.max_rd = max_rd
        self.min_val = min_val
        self.max_val = max_val
        self.coef = (max_val - min_val) / (max_rd - min_rd)
        self.adc = ADC(0) 
Example #17
Source File: adc.py    From pysmartnode with MIT License 5 votes vote down vote up
def ADC(pin, atten=None, *args, **kwargs) -> pyADC:
    if type(pin) == str:
        raise TypeError("ADC pin can't be string")
    if isinstance(pin, pyADC):
        # must be a completely initialized ADC otherwise it wouldn't be a subclass of pyADC
        # could be machineADC, Arduino ADC or even Amux or Amux ADC object
        return pin
    if type(pin) == machine.ADC:
        # using a hacky way to re-instantiate an object derived from machine.ADC by
        # reading the used pin from machine.ADC string representation and creating it again.
        # This does not retain the set atten value sadly.
        # It is however needed so that isinstance(adc, machine.ADC) is always True for hardware ADCs.
        astr = str(pin)
        if platform == "esp32_Lobo":  # ADC(Pin(33): unit=ADC1, chan=5, width=12 bits, atten=0dB (1.1V), Vref=1100 mV)
            pin = int(astr[astr.rfind("ADC(Pin(") + 8:astr.find("):")])
        elif platform == "esp8266":  # esp8266 only has one ADC
            pin = 0
        elif platform == "esp32":  # ADC(Pin(33))
            pin = int(astr[astr.rfind("(") + 1:astr.rfind("))")])
        else:
            raise NotImplementedError("Platform {!s} not implemented".format(platform))
    if type(pin) == int:
        if platform == "esp32" or platform == "esp32_LoBo":
            adc = machineADC(machine.Pin(pin), *args, **kwargs)
            adc.atten(adc.ATTN_11DB if atten is None else atten)
            return adc
        elif platform == "esp8266":
            return machineADC(pin, *args, **kwargs)  # esp8266 does not require a pin object
        else:
            raise NotImplementedError(
                "Platform {!s} not implemented, please report".format(platform))
    raise TypeError("Unknown type {!s} for ADC object".format(type(pin))) 
Example #18
Source File: adc.py    From pysmartnode with MIT License 5 votes vote down vote up
def width(self, *args, **kwargs):
        raise NotImplementedError("Width not supported")


# machineADC = type("ADC", (machine.ADC, pyADC), {})  # machine.ADC subclass 
Example #19
Source File: adc.py    From pysmartnode with MIT License 5 votes vote down vote up
def maxVoltage() -> float:
        return 3.3  # esp standard voltage

    # The following methods are overwritten by machineADC, the machine.ADC class, by the proper hardware methods
    # In other subclasses they have to be implemented 
Example #20
Source File: adc.py    From pysmartnode with MIT License 5 votes vote down vote up
def readRaw(self) -> int:
        # just loboris fork compatibility although support officialy dropped.
        if isinstance(self, machine.ADC):
            # Subclass of hardware ADC
            return self.read() if platform != "esp32_Lobo" else self.readraw()
        return self.read()  # on non-hardware ADCs read() always returns raw values 
Example #21
Source File: util.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def vcc():
    import machine
    mv = machine.ADC(0)
    return mv.read() * 1.024 
Example #22
Source File: tinypico.py    From tinypico-micropython with MIT License 5 votes vote down vote up
def get_battery_voltage():
    """
    Returns the current battery voltage. If no battery is connected, returns 3.7V
    This is an approximation only, but useful to detect of the charge state of the battery is getting low.
    """
    adc = ADC(Pin(BAT_VOLTAGE))  # Assign the ADC pin to read
    measuredvbat = adc.read()  # Read the value
    measuredvbat /= 4095  # divide by 4095 as we are using the default ADC voltage range of 0-1V
    measuredvbat *= 3.7  # Multiply by 3.7V, our reference voltage
    return measuredvbat


# Return the current charge state of the battery - we need to read the value multiple times
# to eliminate false negatives due to the charge IC not knowing the difference between no battery
# and a full battery not charging - This is why the charge LED flashes 
Example #23
Source File: tinypico.py    From tinypico-micropython with MIT License 5 votes vote down vote up
def get_battery_voltage():
    """
    Returns the current battery voltage. If no battery is connected, returns 3.7V
    This is an approximation only, but useful to detect of the charge state of the battery is getting low.
    """
    adc = ADC(Pin(BAT_VOLTAGE))  # Assign the ADC pin to read
    measuredvbat = adc.read()  # Read the value
    measuredvbat /= 4095  # divide by 4095 as we are using the default ADC voltage range of 0-1V
    measuredvbat *= 3.7  # Multiply by 3.7V, our reference voltage
    return measuredvbat


# Return the current charge state of the battery - we need to read the value multiple times
# to eliminate false negatives due to the charge IC not knowing the difference between no battery
# and a full battery not charging - This is why the charge LED flashes 
Example #24
Source File: tinypico.py    From tinypico-micropython with MIT License 5 votes vote down vote up
def get_battery_voltage():
    """
    Returns the current battery voltage. If no battery is connected, returns 3.7V
    This is an approximation only, but useful to detect of the charge state of the battery is getting low.
    """
    adc = ADC(Pin(BAT_VOLTAGE))  # Assign the ADC pin to read
    measuredvbat = adc.read()  # Read the value
    measuredvbat /= 4095  # divide by 4095 as we are using the default ADC voltage range of 0-1V
    measuredvbat *= 3.7  # Multiply by 3.7V, our reference voltage
    return measuredvbat


# Return the current charge state of the battery - we need to read the value multiple times
# to eliminate false negatives due to the charge IC not knowing the difference between no battery
# and a full battery not charging - This is why the charge LED flashes 
Example #25
Source File: esp_8266.py    From python_banyan with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_mode_analog_input(self,payload):
  if 'change_diff' in payload:
   self.adc_diff_report=payload['change_diff']
  self.adc=ADC(0) 
Example #26
Source File: esp_8266Full.py    From python_banyan with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_mode_analog_input(self, payload):
        """
        create an adc object
        :param payload:
        :return:
        """

        if 'change_diff' in payload:
            self.adc_diff_report = payload['change_diff']
        self.adc = ADC(0) 
Example #27
Source File: adc_esp8266.py    From thingflow-python with Apache License 2.0 5 votes vote down vote up
def sample(self) -> float:
        '''Get an ADC interpolated reading using ThingFlow sensor API

           Return min_val~max_val
        '''
        reading = self.read()
        return self.min_val + (reading - self.min_rd) * self.coef 
Example #28
Source File: adc_esp8266.py    From thingflow-python with Apache License 2.0 5 votes vote down vote up
def read(self) -> int:
        '''Get a sensor reading using Micropython API

           Return 0-1024 direct ADC (0~3.3v) reading
        '''
        return self.adc.read()