def __init__(self, rtc):
        self.rtc = rtc

        # Try to access the SD card and make the new path
        try:
            sd = SD()
            os.mount(sd, '/sd')
            self.sensor_file = "/sd/{0}".format(SENSOR_DATA)
            print("INFO: Using SD card for data.")
        except:
            print("ERROR: cannot mount SD card, reverting to flash!")
            self.sensor_file = SENSOR_DATA
        print("Data filename = {0}".format(self.sensor_file))

        # Setup the dictionary for each soil moisture sensor
        adc = ADC(0)
        soil_moisture1 = {
            'sensor': adc.channel(pin='P13', attn=3),
            'power': Pin('P19', Pin.OUT),
            'location': 'Green ceramic pot on top shelf',
            'num': 1,
        }
        soil_moisture2 = {
            'sensor': adc.channel(pin='P14', attn=3),
            'power': Pin('P20', Pin.OUT),
            'location': 'Fern on bottom shelf',
            'num': 2,
        }
        # Setup a list for each sensor dictionary
        self.sensors = [soil_moisture1, soil_moisture2]
        # Setup the alarm to read the sensors
        a = Timer.Alarm(handler=self._read_sensors,
                        s=UPDATE_FREQ,
                        periodic=True)
        print("Plant Monitor class is ready...")
Exemplo n.º 2
0
def main():
    pkt_tx_queue = []

    def audio_frame_ready(data):
        pkt_tx_queue.append(data)

    lora_ctl = lora.LoRaController()
    spk = speaker.Speaker(DAC('P22'))
    adc = ADC()
    apin = adc.channel(pin='P13', attn=ADC.ATTN_11DB)
    uphone = microphone.Microphone(apin, audio_frame_ready)
    tlk_btn = talk_button.TalkButton(uphone)

    print('Started ...')
    flash(0x007f00)  # green

    while True:
        Timer.sleep_us(1000)

        # Handle the RX packets
        # TODO: refactor to use callback mechanism.
        while True:
            data = lora_ctl.recv()
            if data:
                spk.enque(data)
            else:
                break

        # Handle the TX queue
        # TODO: refactor to use Python synchronized Queue.
        while pkt_tx_queue:
            data = pkt_tx_queue.pop(0)
            print('.')
            lora_ctl.send(data)
class BatteryService(object):

    def __init__(self):
        self.powerPin = 0
        self.adc = 0
        self.Battery = 0
        self.vBiasDAC = 0

    def confService(self):
        self.powerPin = Pin('P8', mode=Pin.OUT)
        self.adc = ADC()
        self.adc.vref(1058)
        self.vBiasDAC = DAC('P22')
        self.vBiasDAC.write(0.135) # approximately 0.5 V
        self.Battery = self.adc.channel(pin='P14', attn = ADC.ATTN_11DB)

    def getData(self):
    	self.powerPin(1)
    	time.sleep(0.002)
    	batt = self.Battery.voltage()
        collectMemory()
    	self.powerPin(0)
        return batt

    def connect(self):
        self.confService()
Exemplo n.º 4
0
class Battery_sensor:
    """A  class to handle the Battery sensor.
    """
    def __init__(self):
        self.adc = ADC()
        self.batt = self.adc.channel(pin='P16', attn=ADC.ATTN_2_5DB)

    '''
        The tension is given after resistor : 56k / (56k + 115k)
        So the tension range : [0 * (56/(56+115)) ; 4.1 * (56/(56+115)) ]
                               [0 ; 1.342]
        So with attn of
            2.5 dB the range of the adc is [0 ; 1.334 V]
            6 dB the range of the adc is   [0 ; 1.995 V]

        So we need to use 2.5dB of attenuation

        Table of values is [0 ; 4095] <=> [0 ; 1.334 V]
    '''

    def get_voltage(self, nb_values):
        """
        Returns the voltage value
        """
        sum = 0
        for i in range(1, nb_values):
            sum = sum + self.batt.value()

        voltage = (sum / nb_values) * (1.334 / 4095) * (1 / (56 / (56 + 115)))

        return voltage
Exemplo n.º 5
0
class TMP36App():
    def __init__(self, pin):
        self._adc = ADC()  # create ADC object
        # create an analog pin on 'pin' & connect TMP36
        self._adc_c = self._adc.channel(pin=pin)
        self._pin = pin
        self._display = None

    @property
    def tmp36(self):
        """ return sensor/channel object"""
        return self._adc_c

    @property
    def setDisplay(self):
        return self._display

    # 2019-0917 if setter is defined, you must also define a getter
    @setDisplay.setter
    def setDisplay(self, display=None):
        """ setter for display attribute.
            Example: app.setDisplay = oled """
        self._display = display

    def calculate_temperature(self, value):
        """calculate_temperature(value): return temperature from value."""
        # LoPy  has 1.1 V input range for ADC
        # datasheet TMP36
        # TODO: use adc_c.vRef instead of hard-coded "1100"?
        return ((value * 1100) / 4096 - 500) / 10

    # print data on console
    def showOnConsole(self, temperature):
        """ show temperature from TMP36 on console."""
        msg = 'Temperature = {:5.1f}'.format(temperature)
        print(msg)

    # print data on attached display
    def showOnDisplay(self, temperature):
        """ show value from TMP36 as temperature on console."""
        header = 'Temperature'
        msg = '{:5.1f}'.format(temperature)
        self._display.fill(0)
        self._display.text(header, 0, 0)
        self._display.text(msg, 0, 10)
        self._display.show()

    # ADC - get readings from TMP36 and display data
    def showValues(self, dt=1):
        while True:
            value = self._adc_c()  # read ADC count
            temperature = self.calculate_temperature(value)
            if self._display is not None:
                self.showOnDisplay(temperature)
            if USE_DEBUG:
                self.showOnConsole(temperature)
            time.sleep(dt)

    def run(self, dt=10):
        _thread.start_new_thread(self.showValues, (dt, ))
Exemplo n.º 6
0
 def __init__(self, pin):
     adc = ADC(bits=12)
     self.apin = adc.channel(pin=pin)
     self.values = [0 for i in range(5)]
     self.volt = 4200
     self.chrg = 100
     self.idx = 0
Exemplo n.º 7
0
def _moist_sensor(testCase=None):
    voltage_ref = 4.096
    adc = ADC()
    apin = adc.channel(pin='P15',attn=ADC.ATTN_11DB)
    p_out = Pin('P9', mode = Pin.OUT, pull = Pin.PULL_DOWN)

    try:
        if isinstance(testCase, Exception):
            raise testCase
        p_out.value(1)
        volts = apin.value() / voltage_ref
        p_out.value(0)
    except Exception as e:
        return 143

    if testCase is not None:
        volts = testCase
    if volts < 0:
        return 143

    if volts >= 760:
        return 100
    else:
        perc = int((volts / 760.0) * 100)
    return perc
Exemplo n.º 8
0
def main():
    # Use the RGB LED as an indicator of WiFi status
    pycom.heartbeat(False)
    wlan = WLAN()
    if wlan.isconnected():
        pycom.rgbled(0x000f00)
    else:
        pycom.rgbled(0x0f0000)

    # Set up the onboard ADC and establish a channel for each thermistor
    adc = ADC()
    adc.vref(config.VREF_ACTUAL_IN_MILLIAMPS)
    oven_channel = adc.channel(pin=config.OVEN_THERM_ADC_PIN, attn=ADC.ATTN_11DB)
    food_channel = adc.channel(pin=config.FOOD_THERM_ADC_PIN, attn=ADC.ATTN_11DB)

    # Modify config.py with your thermistor values from the datasheet
    oven = Thermistor(oven_channel,
                      config.THERM_NOMINAL_TEMP,
                      config.THERM_NOMINAL_RES,
                      config.THERM_BETA,
                      config.SERIES_RESISTOR_1,
                      12.0)
    food = Thermistor(food_channel,
                      config.THERM_NOMINAL_TEMP,
                      config.THERM_NOMINAL_RES,
                      config.THERM_BETA,
                      config.SERIES_RESISTOR_2,
                      12.0)

    dinner_tracker = LosantDinnerTracker(oven, food, status_led=config.STATUS_LED_PIN)
    dinner_tracker.start()
Exemplo n.º 9
0
    def __init__(self, air_voltage, water_voltage, p_analog_id):
        self.air_voltage = air_voltage
        self.water_voltage = water_voltage

        adc = ADC()  # create an ADC object
        self.p_analog = adc.channel(pin=p_analog_id,
                                    attn=ADC.ATTN_11DB)  # create an analog pin
Exemplo n.º 10
0
def voltage():
    volts = 0
    from machine import ADC
    adc = ADC()
    vpin = adc.channel(pin='P13')
    for i in range(0, 999):
        volts += vpin.voltage() / 0.24444 / 1000
    return volts / i
Exemplo n.º 11
0
    def start(self):
        try:
            from machine import ADC
            adc = ADC()
            self.channel = adc.channel(pin=self.pins['adc_in'], attn=ADC.ATTN_11DB)
            #p_out = Pin('P9', mode=Pin.OUT, pull=Pin.PULL_DOWN)

        except Exception as ex:
            log.exception('ADC hardware driver failed')
            raise
Exemplo n.º 12
0
def tensionBatterie():
    adc = ADC()
    batt = adc.channel(
        attn=c.attn, pin=c.pinBatt
    )  # attenuation = 1, correspond à 3dB: gamme 0-1412 mV, pont diviseur (115k et 56k) sur expansion board V2.1A de 3.05, ADC 12 bits : 4096
    v = batt.value()
    if v == c.resolutionADC - 1:
        v = -1
    v = int(v * c.range / c.resolutionADC * c.coeff_pont_div)  #mV
    return v
Exemplo n.º 13
0
def moist_sensor(p_in, p_out):
    adc = ADC()
    apin = adc.channel(pin=p_in, attn=ADC.ATTN_11DB)
    p_out = Pin(p_out, mode=Pin.OUT, pull=Pin.PULL_DOWN)
    p_out.value(1)
    time.sleep(2)
    volts = apin.value()
    p_out.value(0)
    time.sleep(2)
    return volts
Exemplo n.º 14
0
    def __init__(self, pin_rx, pin_am):
        super(MB7092, self).__init__()

        # pin to enable/disable measurement
        self.rx = Pin('P' + str(pin_rx), mode=Pin.OUT)
        self.rx(1)

        # setting up the Analog/Digital Converter with 10 bits
        adc = ADC()

        # create an analog pin on P16 for the ultrasonic sensor
        self.am = adc.channel(pin='P' + str(pin_am))
Exemplo n.º 15
0
    def __init__(self, bat_pin='P16', bat_capacity=1000):
        self.bat_capacity = bat_capacity

        #Configure ADC for battery voltage sensing
        adc = ADC()
        #Configure 2.5dB attenuator to be able to capture full range of battery
        #voltages
        self.bat_adc = adc.channel(pin=bat_pin, attn=ADC.ATTN_2_5DB)

        #Battery voltage is sensed through a voltage divider with
        #115kOhm and 56kOhm, such that V_ADC = V_batt * 56/(115+56)
        self.a = 171.0 / 56.0
Exemplo n.º 16
0
def adc():
    adc = ADC()
    adc.init(bits=12)
    #adc_c = adc.channel(pin='P13',attn=ADC.ATTN_11DB)  #ADC pin input range is 0-3.3V with 11DB.
    adc_c = adc.channel(pin='P13')                      #ADC pin input range is 0-1.1V.
    for cycles in range(10): # stop after 10 cycles
        #pycom.rgbled(0x007f00) # green
        Vx= adc_c.value()
        #pycom.rgbled(0x7f7f00) # yellow
        print("ADC value:", Vx)
        time.sleep(1)
    adc.deinit()
    return Vx
Exemplo n.º 17
0
 def __init__(self, sda="P3", scl="P4", als="P20", frequency=1, mode=0, debug=0):
     if not (mode == 0 or mode == 1):
         self.__exitError("Please initialize this module in either mode 0 or mode 1.")
     self.mode = mode
     self.rtc = RTC()
     self.debug = debug
     self.wlan = WLAN(mode=WLAN.STA)
     self.UDPactive = False
     self.loraActive = False
     if (mode == 0):
         adc = ADC()
         self.bme280 = bme280.BME280(i2c=I2C(pins=(sda, scl)))
         self.l_pin = adc.channel(pin=als)
         self.frequency = frequency
Exemplo n.º 18
0
def getBatVoltage():
  global adc_bat
  if adc_bat == None:
    global config, MyConfig
    if not 'accuPin' in config.keys():
      accuPin = 'P17'
      try: from Config import accuPin
      except: pass
      MyConfig.dump('accuPin',accuPin); config['accupin'] = accuPin
    else: accuPin = config['accuPin']
    from machine import ADC
    adc = ADC(0)
    adc_bat = adc.channel(pin=accuPin, attn=ADC.ATTN_11DB)
  return adc_bat.value()*0.004271845
Exemplo n.º 19
0
class AnalogSensor:
    def __init__(self, pin, attn=ADC.ATTN_0DB, vref=3300):
        global analog_counter
        self.pin = pin

        self.adc = ADC(analog_counter)
        self.adc.vref(vref)
        self.adc_channel = self.adc.channel(pin=pin, attn=attn)

        analog_counter += 1

    def read(self):
        self.adc_channel()
        value = self.adc_channel.value()
        return value
Exemplo n.º 20
0
def get_batt_mV():
    numADCreadings = const(100)

    adc = ADC(0)
    adcread = adc.channel(pin='P16')
    samplesADC = [0.0]*numADCreadings; meanADC = 0.0
    i = 0
    while (i < numADCreadings):
        adcint = adcread()
        samplesADC[i] = adcint
        meanADC += adcint
        i += 1
    meanADC /= numADCreadings

    mV = ((meanADC*1100/4096)*(680+100)/100)
    mV_int = int(mV)
    return mV_int
Exemplo n.º 21
0
def get_battery_voltage(show=0):
    """
	typedef enum {
		ADC_ATTEN_0DB = 0,
		ADC_ATTEN_3DB, // 1
		ADC_ATTEN_6DB, // 2
		ADC_ATTEN_12DB, // 3
		ADC_ATTEN_MAX, // 4
	} adc_atten_t;
	"""
    number_of_adc_readings = const(100)
    adc = ADC(0)
    adcread = adc.channel(attn=2, pin='P19')
    samples_adc = [0.0] * number_of_adc_readings
    mean_adc = 0.0
    i = 0
    while i < number_of_adc_readings:
        adcint = adcread()
        samples_adc[i] = adcint
        mean_adc += adcint
        i += 1
    mean_adc /= number_of_adc_readings
    variance_adc = 0.0
    for adcint in samples_adc:
        variance_adc += (adcint - mean_adc)**2
    variance_adc /= (number_of_adc_readings - 1)
    vbatt = ((mean_adc / 3) * 1400 / 1024) * 171 / (
        56 * 1000)  # Vbatt=Vmeasure*((115+56)/56)
    if show:
        print("%u ADC readings :\n%s" %
              (number_of_adc_readings, str(samples_adc)))
        print("Mean of ADC readings (0-4095) = %15.13f" % mean_adc)
        print("Mean of ADC readings (0-1846 mV) = %15.13f" %
              (mean_adc * 1846 / 4096))  # Calibrated manually
        print("Variance of ADC readings = %15.13f" % variance_adc)
        print("Standard Deviation of ADC readings = %15.13f" %
              sqrt(variance_adc))
        if mean_adc:
            print("10**6*Variance/(Mean**2) of ADC readings = %15.13f" %
                  ((variance_adc * 10**6) // (mean_adc**2)))
        else:
            print("10**6*Variance/(Mean**2) of ADC readings = %15.13f" %
                  mean_adc)
        print("Battery voltage = %15.13f" % vbatt)
    return vbatt
Exemplo n.º 22
0
class MQ131:
    #Sensor datasheet has a graphical representation of ppm of gas by Rs/R0. By obtaining this ratio and using the graphical funcion one can obtain the gas density in ppm
    #Rs is the resistance of the sensor that changes depending on the concentration of gas
    #R0 is the resistance of the sensor at a know concentration without the presence of gases (fresh air)
    #Rs/R0 of fresh air is 1 so R0=Rs/1
    #2 points of the gas function are selected (1.2 at 10ppm) and (8 at 1000ppm)
    #another point is used to find the intersect (6 at 500ppm)
    READ_SAMPLE_INTERVAL = const(500)
    READ_SAMPLE_TIMES = const(10)

    def __init__(self, pin, R0):
        self.pin = pin
        self.R0 = R0
        self.adc = ADC(bits=12)
        self.adc.vref_to_pin('P22')
        self.apin = self.adc.channel(pin=self.pin, attn=ADC.ATTN_11DB)

    def deinit(self):
        self.apin.deinit()
        self.adc.deinit()

    def MQRead(self):
        v=float(0)
        for i in range(READ_SAMPLE_TIMES):
            v += self.apin()
            sleep(READ_SAMPLE_INTERVAL/1000)
        return ((v/READ_SAMPLE_TIMES)*3.3/4096) #3.3v - ATTN_11DB & 4096 - 12bits

    def MQCalibrate_R0(self, volts):
        #Rs = (Vc * RL)/VRL - RL
        if (volts==0):
            return 0
        RS_air = ((5.0*10.0)/volts)-10.0
        R0_air = RS_air/1   #from graph, needs to be replaced with real data
        return R0_air

    def MQGet_PPB(self, volts):
        if (volts==0):
            return 0
        Rs = ((5.0*10.0)/volts)-10.0
        m=AdvMath.log10(1.2/10)/AdvMath.log10(8/1000)
        b=AdvMath.log10(6)-(m*AdvMath.log10(500))
        if (Rs==0):
            return 0
        return pow(10,(((AdvMath.log10(Rs/self.R0))-b)/m))
Exemplo n.º 23
0
class Actility:
    def __init__(self, activation=LoRa.OTAA, adr=False):
        self.lora = LoRa(mode=LoRa.LORAWAN, adr=adr)
        self.activation = activation

        self._join()

        self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 3)
        self.s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False)
        self.s.setblocking(False)

        self.adc = ADC()
        self.adc_c = self.adc.channel(pin='P13')

    def _join(self):
        if self.activation == LoRa.OTAA:
            dev_eui = binascii.unhexlify(DEV_EUI.replace(' ', ''))
            app_eui = binascii.unhexlify(APP_EUI.replace(' ', ''))
            app_key = binascii.unhexlify(APP_KEY.replace(' ', ''))
            self.lora.join(activation=LoRa.OTAA,
                           auth=(dev_eui, app_eui, app_key),
                           timeout=0)
        else:
            dev_addr = struct.unpack(
                ">l", binascii.unhexlify(DEV_ADDR.replace(' ', '')))[0]
            nwk_swkey = binascii.unhexlify(NWK_SWKEY.replace(' ', ''))
            app_swkey = binascii.unhexlify(APP_SWKEY.replace(' ', ''))
            self.lora.join(activation=LoRa.ABP,
                           auth=(dev_addr, nwk_swkey, app_swkey))

        # wait until the module has joined the network
        while not self.lora.has_joined():
            time.sleep(5)
            print("Joining...")

        print("Network joined!")

    def run(self):
        while True:
            time.sleep(10)
            tx_data = '%d' % self.adc_c()
            print('Sending', tx_data)
            self.s.send(tx_data)
Exemplo n.º 24
0
def adc_battery():
    # initialise adc hardware
    adc = ADC(0)
    #create an object to sample ADC on pin 16 with attenuation of 11db (config 3)
    adc_c = adc.channel(attn=3, pin='P16')
    # initialise the list
    adc_samples = []
    # take 100 samples and append them into the list
    for count in range(100):
        adc_samples.append(int(adc_c()))
    # sort the list
    adc_samples = sorted(adc_samples)
    # take the center list row value (median average)
    adc_median = adc_samples[int(len(adc_samples) / 2)]
    # apply the function to scale to volts
    adc_median = adc_median * 2 / 4095 / 0.3275
    print(adc_samples)

    return adc_median
Exemplo n.º 25
0
class WaterSensor:
    def __init__(self, pin='P17'):
        self.adc = ADC()
        self.pin = self.adc.channel(pin=pin, attn=ADC.ATTN_11DB)
        self.data = []

    def read(self, measurementAvg=10):
        avg = 0
        if measurementAvg <= 0:
            return -1

        for x in range(0, measurementAvg):
            avg += self.pin.value()

        avg = int(avg / measurementAvg)

        self.data.append(avg)

        return avg
Exemplo n.º 26
0
def audio_loopback():
    def handle_audio(data):
        spk.enque(data)

    int_mode = False
    spk = speaker.Speaker(DAC('P22'), int_mode=int_mode, debug=False)
    adc = ADC()
    apin = adc.channel(pin='P13', attn=ADC.ATTN_11DB)
    uphone = microphone.Microphone(apin, handle_audio, int_mode=int_mode)
    tlk_btn = talk_button.TalkButton(uphone)

    print('Audio playpack ...')
    flash(0x000010)  # Dark blue

    while True:
        if int_mode:
            Timer.sleep_us(1000000)
        else:
            uphone.loop()
            spk.loop()
Exemplo n.º 27
0
def getTemperature():
	global ADC_PIN_TMP36
	global T_MAX_MV
	global V_TO_MV
	global ADC_MAX_VAL
	global PRECISION_SCALE
	global OFFSET_MV
	global SCALE_FACTOR

	adc_tmp36 = ADC(0)
	apin_tmp36 = adc_tmp36.channel(pin=ADC_PIN_TMP36)
	rawTemp = 0
	for x in range(0, 100):
		adc_value = apin_tmp36.value()
		# read value (0~1024) then converted in mV then scaled to get more precision
		tMV = adc_value * (T_MAX_MV /  ADC_MAX_VAL)* PRECISION_SCALE
		# convert th mV received to temperature
		rawTemp += (tMV - OFFSET_MV) / 10

	return (rawTemp/100)
Exemplo n.º 28
0
 def status():
     import machine
     from machine import ADC
     adc = ADC(0)
     adcread = adc.channel(attn=3, pin='P16')
     samplesADC = [0.0] * numADCreadings
     meanADC = 0.0
     count = 0
     while (count < numADCreadings):
         adcint = adcread()
         samplesADC[count] = adcint
         meanADC += adcint
         count += 1
     meanADC /= numADCreadings
     varianceADC = 0.0
     for adcint in samplesADC:
         varianceADC += (adcint - meanADC)**2
     varianceADC /= (numADCreadings - 1)
     mV = meanADC * 1400 / 1024
     return mV
Exemplo n.º 29
0
class ADCCLASS:
    def __init__(self, readPin, N):
        self.N = N  # Number of readings per measure
        self.adc = ADC()  # Call the constructor
        self.readPin = self.adc.channel(
            pin=readPin, attn=ADC.ATTN_11DB)  # Assign the analog pin
        # Allocate memory for some relevant variables
        self.value = 0  # ADC counts
        self.stdDev = 0  # Standard deviation of N readings
        self.voltage = 0  # Voltage
        self.deltaV = 0  # Voltage's Standard deviation

    def measure(self, vBias):
        # Compute value as the mean of N readings
        measureSum = 0
        measureSum2 = 0
        for i in range(self.N):
            measure = self.readPin()
            measureSum += measure  # Accumulate readings
            measureSum2 += measure * measure
            sleep_us(
                200
            )  # Wait 200 us before reading the next value (ESP32's ADC has a sampling rate of 6 KHz)

        self.value = measureSum / self.N  # Compute the mean
        self.stdDev = sqrt((measureSum2 / self.N) - (self.value * self.value))

        # Compute voltage according to the ADC's transfer curve and bias voltage
        self.voltage = ADCCLASS.__countsToVolts(self.value) - vBias  # [V]
        self.deltaV = self.stdDev * self.voltage / self.value  # [V]

        # Print results
        # print('Value: {:4.3f}'.format(self.value, self.stdDev))
        # print('Voltage: {:1.3f} +- {:1.3f}'.format(self.voltage, self.deltaV))

    # Function that computes a voltage from ADC counts
    def __countsToVolts(counts):
        return ((counts + 164.059) / 1249.436)  # [V]
Exemplo n.º 30
0
class Battery(object):
    """
    Expansion board has battery on GP3
    The ADC measures between 0-1.4V
    It is 12bit (0-4095)
    It is measuring off a 56k/(56k+115k) voltage divider - 0.32
    """
    MINIMUM = 3180 # 3.64V measured
    CHARGED = 3600 # Using 4.15V
    RANGE = (CHARGED - MINIMUM)

    def __init__(self):
        self.adc = ADC()
        self.battery_raw = self.adc.channel(pin='GP3')

    def __del__(self):
        self.battery_raw.deinit()
        self.adc.deinit()

    def safe(self):
        """
        Is battery at operating voltage?
        :return: True/False
        """
        return self.battery_raw() >= Battery.MINIMUM

    def value(self):
        """
        Battery percentage
        :return: 0-100
        """
        val = (self.battery_raw() - Battery.MINIMUM) * 100
        val = val // Battery.RANGE
        if val > 100:
            val = 100
        if val < 0:
            val = 0
        return val
Exemplo n.º 31
0
def GetBattVolt():

    adc = ADC(0)
    BattVol = adc.channel(pin='P15',  attn=3)   # create an analog pin on P16
 
    realVoltage = 0

    # Average Count
    ADCCnt = 75
    for  idx in range(ADCCnt):
        realVoltage += BattVol.value()
        print(BattVol())
        time.sleep_ms(50)

    realVoltage = realVoltage / ADCCnt
    realVoltage = (realVoltage * 200) / 100
    realVoltage = realVoltage * 4.25 # Linear scaling (was 3.35)
    realVoltage = realVoltage / 4096
    
    print("Real Voltage is " + str(realVoltage))
    
    Level = 0
    
    if(realVoltage >= 3.8):
        Level = 6
    elif(realVoltage >= 3.7 and realVoltage < 3.8):
        Level = 5
    elif(realVoltage >= 3.6 and realVoltage < 3.7):
        Level = 4
    elif(realVoltage >= 3.5 and realVoltage < 3.6):
        Level = 3
    elif(realVoltage >= 3.4 and realVoltage < 3.5):
        Level = 2
    elif(realVoltage >= 3.0 and realVoltage < 3.4):
        Level = 1
    
    return Level,  realVoltage
class SEN0219:
    #Sensor datasheet has a graphical representation of ppm of gas by V in a linear function. By using the graphical funcion one can obtain the gas density in ppm
    #2 points of the gas function are used to find the slope of the linear function (2V at 5000ppm) and (0.4 at 0ppm)
    #To Calibrate the Sensor by Hardware, one should place it in a CO2 free enviroment and then wire to ground both pin 8 and 20 of the Sensor for 7 seconds
    #To Calibrate the Sensor by Software, one should place it in a enviroment close to average CO2 (400ppm), measure the voltage output, and use that value as R0
    READ_SAMPLE_INTERVAL = const(500)
    READ_SAMPLE_TIMES = const(10)

    def __init__(self, pin, offset):
        self.pin = pin
        self.offset = offset
        self.adc = ADC(bits=12)
        self.apin = self.adc.channel(pin=self.pin, attn=ADC.ATTN_11DB)

    def deinit(self):
        self.apin.deinit()
        self.adc.deinit()

    def SENRead(self):
        v=float(0)
        for i in range(READ_SAMPLE_TIMES):
            v += self.apin()
            sleep(READ_SAMPLE_INTERVAL/1000)
        return ((v/READ_SAMPLE_TIMES)*3.3/4096)   #3.3v - ATTN_11DB & 4096 - 12bits

    def SENCalibrate_offset(self, volts):
        # 0,528V -> 400 ppm
        if (volts<=0.528):
            return 0
        offset = (((volts-0.4)*5000)/1.6) - 400
        return offset

    def SENGet_PPM(self, volts):
        if (volts<=0.4):
            return False
        ppm=(((volts-0.4)*5000)/1.6)-self.offset   #0.4 = Zero & (5000-0)/(2-0.4) = Linear Function
        return ppm
Exemplo n.º 33
0
class ISTFS7:

    n = 0.46
    k = 0.5905
    Uo = 2.1612

    def __init__(self, pin: str):
        self.adc = ADC()
        self.apin = self.adc.channel(pin=pin, attn=ADC.ATTN_11DB)

    def _get_pin_voltage(self) -> float:
        try:
            return self.apin.voltage() / 1000

        except Exception as e:
            return 0

    def _velocity(self) -> float:
        try:
            U = self._get_pin_voltage()

            num = ((U - self.Uo) * (U + self.Uo))**(1 / self.n)
            den = ((self.k)**(1 / self.n)) * ((self.Uo)**(2 / self.n))
            return abs(num) / den

        except Exception as e:
            return 0

    def get_measurement(self) -> dict:
        try:
            return {
                "velocity": round(self._velocity(), 3),
                "velocity_unit": "m/s"
            }

        except Exception as e:
            return {"velocity": 0.0, "velocity_unit": "m/s"}
Exemplo n.º 34
0
 def __init__(self, pin_name):
     adc = ADC()
     self.pin = adc.channel(pin=pin_name, attn=ADC.ATTN_11DB, bits=12)
     self.threshold = None
Exemplo n.º 35
0
    adc_pin = 'GP5'
    adc_channel = 3
elif 'WiPy' in mch:
    adc_pin = 'GP3'
    adc_channel = 1
else:
    raise Exception('Board not supported!')

adc = ADC(0)
print(adc)
adc = ADC()
print(adc)
adc = ADC(0, bits=12)
print(adc)

apin = adc.channel(adc_channel)
print(apin)
apin = adc.channel(id=adc_channel)
print(apin)
apin = adc.channel(adc_channel, pin=adc_pin)
print(apin)
apin = adc.channel(id=adc_channel, pin=adc_pin)
print(apin)

print(apin.value() > 3000)
print(apin() > 3000)

# de-init must work
apin.deinit()
print(apin)
Exemplo n.º 36
0
class DAQ_Unit(object):
    def __init__(self):#, freqVal=10000, numpnts = 1000):
        if RDB.ping():
            self.daqDict = pullRedisJson(RDB, DAQPARAMKEY)
            gc.collect()
        else:
            self.daqDict = DAQPARAMS
        self.setDaqParams()
        self.curPos = 0
        self.setupADC()
        self.setupTimer()

    def updateDaqParams(self):
        if RDB.ping():
            self.daqDict = pullRedisJson(RDB, DAQPARAMKEY)
            gc.collect()
        else:
            print("Redis DAQ Param Pull Failed\n\tReverting to defaults...")
        self.setDaqParams()

    def setDaqParams(self):
        self.gpw = self.daqDict['gpw']
        self.numPnts = self.daqDict['numPnts']
        self.acqSpeed = self.daqDict['acqSpeed']
        self.freq = self.daqDict['freq']#40000#1//(self.acqSpeed*1000)#acqSpeed is in microseconds
        self.acqType = self.daqDict['acqType']
        self.numAves = self.daqDict['numAves']
        self.multiplexParam = self.daqDict['multiplexParam']
        self.dataArray = array.array('H', range(self.numPnts))#initialize data array
        self.dataID = uniqid()
        self.daqDict['dataCode'] = self.dataID
        self.filePath = self.dataID+'.txt'
        self.daqDict['filePath'] = self.filePath
        self.daqDict['data'] = self.dataArray
        gc.collect()

    def pushData(self, writeSD = False):
        t = time.time()
        RDB.rpush(self.dataID, self.dataID)
        RDB.rpush(self.dataID, self.numPnts)
        RDB.rpush(self.dataID, self.numAves)
        RDB.rpush(self.dataID, self.gpw)
        RDB.rpush(self.dataID, self.acqSpeed)
        RDB.rpush(self.dataID, self.freq)
        RDB.rpush(self.dataID, self.filePath)
        RDB.rpush(self.dataID, self.acqType)
        RDB.rpush(self.dataID, self.multiplexParam)
        print(time.time()-t)
        j = 0#Break and send data (Not optimum but better than one by one)
        for i in range(1+len(self.dataArray)//INDEXVAL):
            RDB.rpush(self.dataID, str(self.dataArray[j:j+INDEXVAL]))
            j+=INDEXVAL
        RDB.rpush('activeData', self.dataID)
        if writeSD:
            self.writeData()
        gc.collect()
        print("Push Time")
        t = time.time()-t
        print(t)

    def stopTimer(self):
        self.tim.deinit()

    def setupTimer(self):
        '''
        Need to look at the following:
        But how to average? (Do we need two buffers)
        http://docs.micropython.org/en/latest/pyboard/library/pyb.ADC.html
        '''
        #How to stop timer?
        self.tim = Timer(0, mode = Timer.PERIODIC, width = 32)#what is this width? Timer resolution?
        self.timChannel = self.tim.channel(Timer.A, freq = self.freq)
        #What is the function of the trigger, do we need to implement external vs internal?
        self.timChannel.irq(handler=self._addData_, trigger = Timer.TIMEOUT)

    def setupADC(self):
        self.adc = ADC()
        self.adcPin = self.adc.channel(pin = 'GP3')

    def _addData_(self, timer, saveData = False):
        self.dataArray[self.curPos] = self.adcPin()
        self.curPos+=1
        self.curPos%=self.numPnts#this value can ultimately help us with the number of aves.
        
    def writeData(self):
        t = time.time()
        curDir = os.getcwd()
        os.chdir("/sd")#change directory to SD card
        try:
            f = open(self.filePath, 'w')
            # json.dump(self.daqDict, f)#assumes the data has already been converted to a string-Redis doesn't like arrays
            f.write("%s\n"%self.dataID)
            f.write("%s\n"%str(self.numPnts))
            f.write("%s\n"%str(self.numAves))
            f.write("%s\n"%str(self.gpw))
            f.write("%s\n"%str(self.acqSpeed))
            f.write("%s\n"%str(self.freq))
            f.write("%s\n"%self.filePath)
            f.write("%s\n"%str(self.acqType))
            f.write("%s\n"%str(self.multiplexParam))
            for d in self.dataArray:
                f.write("%s,\n"%str(d))
            f.close()
            os.chdir(curDir)
        except:
            os.chdir(curDir)
            print("Saving to %s failed"%fileName)
        gc.collect()
        print("Write Time: %s"%(time.time()-t))
Exemplo n.º 37
0
from machine import ADC
import time

adc = ADC(0)
adc_c = adc.channel(pin='P13')

while True:
    value = adc_c.value()
    print("ADC value:" + str(value))
    time.sleep(1)
Exemplo n.º 38
0
rtclock = RTC()
clock_adjust()

# set the regex for the uart answers
re = ure.compile("\r\nOK\r\n")
er = ure.compile("\r\nERROR\r\n")

# config the uart and see if somethings answers
uart = UART(1, baudrate=115200, pins=(TX_PIN, RX_PIN))  # uart #, baudrate, pins tx,rx
uart.write('+++')
uart.write('AT+COPS?\r\n')
time.sleep(1)
while uart.any() != 0:
    print(uart.readall())

# get the battery
adc = ADC()
bat = adc.channel(pin=BAT_PIN)

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH, server=BLYNK_SERVER)

# register virtual pin 4 (the button on the blynk that sends the temp sms right away)
blynk.add_virtual_pin(4, write=v4_write_handler)

# register my task
blynk.set_user_task(sendData, 60000)

# start Blynk (this call should never return)
blynk.run()