Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
 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
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
    def __init__(self):
        self.x_adc = ADC(1)

        self.btn_speed_up = Pin("P13", mode=Pin.IN, pull=Pin.PULL_UP)
        self.btn_speed_down = Pin("P15", mode=Pin.IN, pull=Pin.PULL_UP)
        self.btn_speed_full = Pin("P14", mode=Pin.IN, pull=Pin.PULL_UP)
        self.btn_speed_off = Pin("P16", mode=Pin.IN, pull=Pin.PULL_UP)

        self.x_mid = 0
        
        self.calibrate()
        self.connect()
        self.loop()
Ejemplo n.º 7
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
Ejemplo n.º 8
0
def get_amb_light():
    adc = ADC(Pin(AMB_LIGHT))
    adc.atten(ADC.ATTN_11DB)
    return adc.read()
Ejemplo n.º 9
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))
def getPaddle(maxvalue=1024):
    return int(ADC(0).read() / (1024 / maxvalue))
Ejemplo n.º 11
0
    #
    # url3 = "https://api.thingspeak.com/update?api_key=CRPM5S9C06JVXFRT&field3=" + str(methane)
    # # print("url3: " + url3)
    # http_get(url3)


def init_IFTTT_timer():
    sensor_update_timer = Timer(1)
    # callback every min.
    sensor_update_timer.init(period=3600000, mode=Timer.PERIODIC, callback=update_sensors_IFTTT)


# main

# ADC pin - A2 - ADC1
methane_adc = ADC(Pin(34))

# ADC pin - A3 - ADC1
CO2_adc = ADC(Pin(39))

# set to measure up to 3.3v
methane_adc.atten(ADC.ATTN_11DB)
methane_adc.width(ADC.WIDTH_12BIT)

CO2_adc.atten(ADC.ATTN_11DB)
CO2_adc.width(ADC.WIDTH_12BIT)

# i2c = SoftI2C(scl=Pin(22), sda=Pin(23))
# hts = hts221.HTS(i2c)

internet_connect()
Ejemplo n.º 12
0
#   Adafruit Feather HUZZAH ESP8266
#   Adafruit Feather HUZZAH ESP32
#   WeMos D1 Mini
#
# User configuration parameters are indicated with "ENTER_".  

import network
import time
from umqtt.robust import MQTTClient
import os
import gc
import sys
from machine import Pin,ADC,PWM

#pin = Pin(2, Pin.OUT, value = 1)
adc = ADC(0)
pwm = PWM(Pin(2))

def cb_03(topic, msg):	
	pwm.duty(int(msg))

# WiFi connection information
WIFI_SSID = 'LG'
WIFI_PASSWORD = '******'

# turn off the WiFi Access Point
ap_if = network.WLAN(network.AP_IF)
ap_if.active(False)

# connect the device device to the WiFi network
wifi = network.WLAN(network.STA_IF)
Ejemplo n.º 13
0
def average_analog_sensor(sensor: ADC, time: int) -> float:
    vals = 0
    for x in range(time):
        vals += sensor.read()
        sleep_ms(1)
    return vals / time
Ejemplo n.º 14
0
# Raspberry Pi Pico connected w/ Pimoroni Pico Display
# This sample program shows some information
# and uses some on-board resources to illustrate their query
# (c) 2021-02-04 Claus Kuehnel ([email protected])

import machine, time, sys, uos
import picodisplay as display

from machine import Timer
from machine import Pin
from machine import ADC

led = Pin(25, Pin.OUT)  # external LED on Pi Pico
t = Timer()

offset = ADC(0)  # use grounded channel 0 for measuring ADC offset
temp = ADC(4)  # use channel 4 for measuring temperature
conversion_factor = 3.3 / (65536)


def blink(Timer):
    led(1)
    time.sleep_ms(20)  # LED on for 20 milliseconds
    led(0)


def initDisplay():
    width = display.get_width()
    height = display.get_height()

    display_buffer = bytearray(width * height *
Ejemplo n.º 15
0
from machine import Pin, ADC, DAC
from board import ADC3, ADC6
from time import sleep

adc = ADC(Pin(ADC6))
adc2 = ADC(Pin(ADC3))
adc2.atten(ADC.ATTN_11DB)
adc.atten(ADC.ATTN_11DB)
for i in range(1000):
	sleep(.1)
	val = adc.read()
	val1 = adc2.read()
	print(val, val1)
Ejemplo n.º 16
0
# main.py
import socket
import time
from machine import ADC, Pin
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.2.9', 1234))

tempSensor = ADC(Pin(32))
tempSensor.atten(ADC.ATTN_6DB)
tempSensor.width(ADC.WIDTH_10BIT)
led = Pin(12, Pin.OUT)
while True:
    temp = (tempSensor.read()/1024 * 2 - .5)*100
    print(temp)
    s.send(bytes(str(temp),'utf-8'))
    command = s.recv(1024).decode('utf-8')
    print(command)
    if command == 'led_on':
        led.on()
    elif command == 'led_off':
        led.off()
    time.sleep(2)
Ejemplo n.º 17
0
from machine import ADC
from machine import Pin
import time

LightSensorPin = 'P16' # sensor connected to P16. Valid pins are P13 to P20.

lightPin = Pin(LightSensorPin, mode=Pin.IN)  # set up pin mode to input
#
adc = ADC(bits=10)             # create an ADC object bits=10 means range 0-1024 the lower value the less light detected
apin = adc.channel(attn=ADC.ATTN_11DB, pin=LightSensorPin)   # create an analog pin on P16;  attn=ADC.ATTN_11DB measures voltage from 0.1 to 3.3v
                 

while True:
    val = apin() # read an analog value
    print("Value", val)
    time.sleep(1)  # wait 1 sec
Ejemplo n.º 18
0
from machine import Pin, PWM, ADC, DAC
from time import sleep
from _thread import start_new_thread as thread
import json, network, urequests

ssid = 'exceed16_8'
pwd = '12345678'
station = network.WLAN(network.STA_IF)
station.active(True)

statBuzzer = 'off'
statDoor = 'close'

infra = Pin(26, Pin.OUT)
ldr = ADC(Pin(32))
R = Pin(21, Pin.OUT)
G = Pin(19, Pin.OUT)
B = Pin(18, Pin.OUT)
SW = Pin(27, Pin.IN)
switch1 = Pin(25, Pin.IN)
servo = PWM(Pin(22), freq=50, duty=77)
count = 0


def door():
    global servo
    global statDoor
    statDoor = 'close'
    servo.duty(120)
    sleep(0.5)
    global count
Ejemplo n.º 19
0
def create_voltage_reader():
    adc = ADC(Pin(_ADC_PIN))
    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)
    voltage_reader = VoltageReader(adc, _ADC_UPPER_LIMIT)
    return voltage_reader
Ejemplo n.º 20
0
    while upper > pwr2:
        pwr2 <<= 1
        bits += 1
    while True:
        r = getrandbits(bits)
        if r < upper:
            break
    return r + start


def randint(start, stop):
    return randrange(start, stop + 1)


# from adc value to keyname --------------
adc = ADC(0)


def getKey(adc):
    key = 'n'
    if adc < 80:
        key = 'n'
    elif abs(adc - 922) < 50:
        key = 'u'
    elif abs(adc - 740) < 50:
        key = 'd'
    elif abs(adc - 555) < 80:
        key = 'l'
    elif abs(adc - 370) < 50:
        key = 'r'
    elif abs(adc - 188) < 80:
Ejemplo n.º 21
0
class PowerUp3:
    def __init__(self):
        self.x_adc = ADC(1)

        self.btn_speed_up = Pin("P13", mode=Pin.IN, pull=Pin.PULL_UP)
        self.btn_speed_down = Pin("P15", mode=Pin.IN, pull=Pin.PULL_UP)
        self.btn_speed_full = Pin("P14", mode=Pin.IN, pull=Pin.PULL_UP)
        self.btn_speed_off = Pin("P16", mode=Pin.IN, pull=Pin.PULL_UP)

        self.x_mid = 0
        
        self.calibrate()
        self.connect()
        self.loop()
        
    def read_stick_x(self):
        return self.x_adc.value()
        
    def button_speed_up(self):
        return not bool(self.btn_speed_up.value())

    def button_speed_down(self):
        return not bool(self.btn_speed_down.value())

    def button_speed_full(self):
        return not bool(self.btn_speed_full.value())

    def button_speed_off(self):
        return not bool(self.btn_speed_off.value())

    def calibrate(self):
        self.x_mid = self.read_stick_x()

    def __str__(self):
        return "calibration x: %i, y: %i" % (self.x_mid)

    def map_chars(self):
        s = self.p.getServices()

        service_batt = s[3]
        service_control = s[4]

        self.char_batt_lvl = service_batt.getCharacteristics()[0]
        self.char_control_speed = service_control.getCharacteristics()[0]
        self.char_control_angle = service_control.getCharacteristics()[2]

    def battery_level(self):
        return int(self.char_batt_lvl.read()[0])

    def speed(self, new_speed=None):
        if new_speed == None:
            return int(self.char_control_speed.read()[0])
        else:
            self.char_control_speed.write(bytearray([new_speed]))

    def angle(self, new_angle=None):
        if new_angle == None:
            return int(self.char_control_angle.read()[0])
        else:
            self.char_control_angle.write(bytearray([new_angle]))

    def connect(self):
        dev = None

        # connect to the airplane
        while not dev:
            dev = find_device_by_name("TailorToys PowerUp")
            if dev:
                self.p = Peripheral()
                self.p.connect(dev.addr())

        # locate interesting characteristics
        self.map_chars()

    def rudder_center(self):
        if self.old_angle != 0:
            self.old_angle = 0
            self.angle(0)

    def rudder_left(self, angle):
        steps = (angle // self.interval_size_left)
        new_angle = 60 - steps

        if self.old_angle != new_angle:
            self.angle(new_angle)
            self.old_angle = new_angle

    def rudder_right(self, angle):
        steps = (angle // self.interval_size_right)
        new_angle = -steps

        if self.old_angle != new_angle:
            self.angle(new_angle)
            self.old_angle = new_angle

    def throttle(self, speed):
        if (speed > 200):
            speed = 200
        elif (speed < 0):
            speed = 0

        if self.old_speed != speed:
            self.speed(speed)
            self.old_speed = speed

    def loop(self):
        adc_threshold = 10
        right_threshold = self.x_mid + adc_threshold
        left_threshold = self.x_mid - adc_threshold

        self.interval_size_left = self.x_mid // 60
        self.interval_size_right = (255 - self.x_mid) // 60

        self.old_angle = 0
        self.old_speed = 0

        while True:

            time.sleep_ms(100)

            # read out new angle
            new_angle = self.read_stick_x()
            if (new_angle < 256):
                if (new_angle > right_threshold):
                    self.rudder_right(new_angle - self.x_mid)
                elif (new_angle < left_threshold):
                    self.rudder_left(new_angle)
                else:
                    self.rudder_center()

            # read out new speed
            new_speed = self.old_speed

            if self.button_speed_up():
                new_speed += 25
            elif self.button_speed_down():
                new_speed -= 25
            elif self.button_speed_full():
                new_speed = 200
            elif self.button_speed_off():
                new_speed = 0
            else:
                pass

            self.throttle(new_speed)
# This code Created by Inventing Phoenix
# 1 FEB 2021
from machine import Pin, PWM, ADC  # This will help you access these pins using the Pin class of the machine module
# and PWM and ADC class of the machine module. ADC class will help us use analog pins
import time

pwm = PWM(
    Pin(15)
)  # Pin number 15 has been assigned to our LED and it as also initated as PWM component
adc = ADC(
    Pin(26)
)  # Pin number 26 has been assigned to our potentiometer and its initated as analog component

pwm.freq(
    1000
)  # tells Raspberry Pi Pico how often to switch the power between on and off for the LED.

while True:  # runs the loop forever
    duty = adc.read_u16(
    )  # analog values read by the analog pin assigned to the potentiometer will be save in duty variable
    print(duty)  # will print the analog value on the screen
    pwm.duty_u16(
        duty)  # will pass one the analog value to the LED as a PWM input
    time.sleep(1)  # delay for 1 second

#Thank you for watching the video! Please subscribe to our youtube channel and click on the bell notification
Ejemplo n.º 23
0
 def __init__(self):
     self.adc = ADC()
     self.battery_raw = self.adc.channel(pin='GP3')
Ejemplo n.º 24
0
from machine import Pin, ADC
from time import sleep

horadc = ADC(Pin(34))  # create ADC object on ADC pin 34
horadc.atten(ADC.ATTN_11DB)
veradc = ADC(Pin(33))  # create ADC object on ADC pin 33
veradc.atten(ADC.ATTN_11DB)
while True:
    print("Horizontal: ",horadc.read())
    print("Vertical: ",veradc.read())
    sleep(1)
Ejemplo n.º 25
0
###  Released into the public domain.
###

import time
from machine import ADC

print("Thinxtra Pycom SiPy test - Distance detection")

# Variables and i/o definition
PIN_SENSOR = 'P13'  #G5 on expansion board

# Get the distance every 1sec
while (True):

    adc = ADC()
    adc_c = adc.channel(attn=ADC.ATTN_11DB, pin=PIN_SENSOR)
    distance = adc_c()
    if 4095 > distance >= 2850:
        print("d = 7 to 10cm (", distance, ")")
    elif 2850 > distance >= 1610:
        print("d = 10 to 20cm (", distance, ")")
    elif 1610 > distance >= 1120:
        print("d = 20 to 30cm (", distance, ")")
    elif 1120 > distance >= 930:
        print("d = 30 to 40cm (", distance, ")")
    elif 930 > distance >= 800:
        print("d = 40 to 50cm (", distance, ")")
    elif 800 > distance >= 620:
        print("d = 50 to 60cm (", distance, ")")
    elif 620 > distance >= 560:
#.modes - a = writing appended (a+ writing/reading) .#
#.        w = writing from beginning of file.  Will create file (w+ writing/reading) .#
#.        r+ = reading/writing from beginning of file. Raises I/O error if doesn't exist .#
#.        b means binary

dataFile = "esp32-joystick.csv"
mode = "wb" if dataFile in uos.listdir() else "r+" #. Create data file and write out header .#
with open(dataFile, "wb") as f:
  f.write("file,sensor,type,data\n")


#. vref = 3.3 .#
numOfChannels = 2
chan = [x for x in range(numOfChannels)]   #. use two channels, 1 for X and 1 for Y direction .#
chan[0] = ADC(Pin(35))
chan[1] = ADC(Pin(34))
chan[0].atten(ADC.ATTN_11DB) #. Full range: 3.3V .#
chan[1].atten(ADC.ATTN_11DB) #. Full range: 3.3V    .#
numOfSamples = 10
sensorAve = [x for x in range(numOfChannels)]
sensorLastRead = [x for x in range(numOfChannels)]
for x in range(numOfChannels): #. initialize the first read for comparison later .#
    sensorLastRead[x] = chan[x].read()
adcValue = [x for x in range(numOfChannels)]
sensor = [[x for x in range(0, numOfSamples)] for x in range(0, numOfChannels)]

    
def valmap(self, value, istart, istop, ostart, ostop):
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))
Ejemplo n.º 27
0
from machine import ADC, Pin
from servo import Servo
import time

#ledPin = Pin(2, Pin.OUT)
adc = ADC(0)
s = Servo(0)
s.rotate(0)

while True:
    val = adc.read()

    if val < 200:
        s.rotate(90)
        time.sleep(0.5)
        s.rotate(0)
    else:
        pass

    time.sleep(0.5)
Ejemplo n.º 28
0
motorPowerPin = Pin(13, Pin.OUT) #ENA pin, not picked out yet Pin(2, Pin.OUT)
motorPowerPWM = PWM(motorPowerPin)
motorPowerPWM.freq(500) #undecided
motorPowerPWM.duty(0) #undecided

dutyCycle = 800 # value between 0 and 023

#onPin1 sends a signal to the motor controller, pin N!, to move the motor one way 
onPin1 = Pin(12, Pin.OUT) #N1, undecided Pin(2, Pin.OUT)
#onPin2 sends a signal to the motor controller, pin N2, to move the motor one way 
onPin2 = Pin(14, Pin.OUT) #N2, undecided Pin(2, Pin.OUT)

#For solar sensors
rightSolarSensorPin = machine.Pin(36)
leftSolarSensorPin = machine.Pin(39)
solarSensorRight = ADC(rightSolarSensorPin)
solarSensorLeft = ADC(leftSolarSensorPin)

solarSensorRight.atten(ADC.ATTN_11DB)
solarSensorLeft.atten(ADC.ATTN_11DB)
#End Pin Setup

#motorTest will test the bi directional motor control
def motorTest():
    motorPowerPWM.duty(950)
    onPin1.value(1)
    time.sleep(1)
    onPin1.value(0)
    onPin2.value(1)
    time.sleep(1)
    onPin2.value(0)
SCREEN_WIDTH = const(128)
SCREEN_HEIGHT = const(64)
paddle_width = 22
btnL = Pin(12, Pin.IN, Pin.PULL_UP)
btnR = Pin(13, Pin.IN, Pin.PULL_UP)
btnU = Pin(14, Pin.IN, Pin.PULL_UP)
btnD = Pin(2, Pin.IN, Pin.PULL_UP)
btnA = Pin(0, Pin.IN, Pin.PULL_UP)
btnB = Pin(3, Pin.IN, Pin.PULL_UP)
buzzer = Pin(15, Pin.OUT)
# configure oled display I2C SSD1306
i2c = I2C(-1, Pin(5), Pin(4))  # SCL, SDA
display = ssd1306.SSD1306_I2C(128, 64, i2c)
# ESP8266 ADC A0 values 0-1023
adc = ADC(0)


def getBtn():
    pass


def pressed(btn, wait_release=False):
    if not btn.value():
        if btn.value():
            return False
        #wait for key release
        while wait_release and not btn.value():
            sleep_ms(5)
        return True
    return False
Ejemplo n.º 30
0
WIDTH  = 128 # oled display width
HEIGHT = 32  # oled display height

sda=machine.Pin(16) # bus 0 data
scl=machine.Pin(17) # bus 0 clock

# should be 400000, 1000 prints some text
i2c=machine.I2C(0, sda=sda, scl=scl, freq=400000)
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)

# this is the built-in LED on the Pico
led = Pin(25, Pin.OUT)

# ADC0 is GPIO 26.  Connect to row 10 the right side
pot = ADC(26)

MAX_DELAY = .5 # seconds

# global variables
delay = 0

def update_display(pot_value, delay):
    oled.fill(0)
    oled.rect(0, 0, WIDTH, HEIGHT, 1)
    oled.fill_rect(1, 1, pot_value, HEIGHT - 1, 1)
    oled.text(str(pot_value), 1, 1, 0)
    oled.text(str(delay), 1, 10, 1)
    oled.text(str(delay), 1, 20, 0)
    oled.show()
Ejemplo n.º 31
0
from machine import Pin, DAC, ADC
from time import sleep_ms
import uos

adc = ADC(Pin(35))
adc.atten(ADC.ATTN_11DB)
dac = DAC(Pin(25))

# Checking if data directory exists
try:
    uos.stat("/data")
except OSError:
    print("/data does not exist, creating it...")
    uos.mkdir('/data')

# Creating the file
file = open("/data/adc.txt", 'w')
# print(dac.write(255))
# print(dac.read())
for i in range(256):
    dac.write(i)
    x = str(adc.read())
    y = str(i)
    file.write(x)
    file.write(" , ")
    file.write(y)
    file.write('\n')
    print(adc.read())
    sleep_ms(2)

file.close()
Ejemplo n.º 32
0
    def __init__(self, samples, samplingFrequency, pin):
        global vReal, vImag
        self.samples = samples  #設定採樣數
        vReal = [0] * self.samples  #設定儲存資料陣列
        vImag = [0] * self.samples  #設定儲存資料陣列

        self.samplingFrequency = samplingFrequency  #設定採樣頻率
        self.pin = pin  #設定讀取資料腳位
        '''設定讀取腳位'''
        adc = ADC(Pin(pin))
        adc.width(ADC.WIDTH_10BIT)  # 設定ADC解析度
        adc.atten(ADC.ATTN_11DB)  # 設定最大電壓為3.6V

        #data -> windowing function (hamming) -> fft kernel -> get magnitude
        '''採樣資料'''
        microseconds = time.ticks_us()
        samplingPeriod = round(1000000 * (1.0 / self.samplingFrequency))
        for i in range(self.samples):
            vReal[i] = adc.read()  #收集感測器資料
            #vImag[i]=0 , 第10行已建立
            while (time.ticks_us() - microseconds) < samplingPeriod:
                pass  #確保採樣時間固定, 每 1/採樣頻率 秒收集一次資料
            microseconds += samplingPeriod
        '''窗函數'''
        samplesMinusOne = self.samples - 1.0
        for i in range(self.samples >> 1):
            indexMinusOne = i / 1.0
            ratio = indexMinusOne / samplesMinusOne
            weighingFactor = 0.54 - (0.46 * math.cos(2 * math.pi * ratio)
                                     )  #HAMMING窗函數
            vReal[i] *= weighingFactor  #採樣資料逐一乘上窗函數
            vReal[self.samples - (i + 1)] *= weighingFactor
        '''對資料進行FFT'''

        j = 0
        for i in range(self.samples):
            if j > i:
                vReal[i], vReal[j] = vReal[j], vReal[i]
                vImag[i], vImag[j] = vImag[j], vImag[i]
            m = self.samples >> 1
            while j >= m and m > 0:
                j -= m
                m >>= 1
            j += m

        mmax = 1
        while self.samples > mmax:
            istep = mmax << 1
            theta = -2.0 * math.pi / istep
            wtemp = math.sin(0.5 * theta)
            wpr = -2.0 * wtemp * wtemp
            wpi = math.sin(theta)
            wr = 1.0
            wi = 0.0
            for m in range(mmax):
                for i in range(m, self.samples, istep):
                    j = i + mmax
                    tempr = wr * vReal[j] - wi * vImag[j]
                    tempi = wr * vImag[j] + wi * vReal[j]
                    vReal[j] = vReal[i] - tempr
                    vImag[j] = vImag[i] - tempi
                    vReal[i] += tempr
                    vImag[i] += tempi
                wtemp = wr
                wr = wr * wpr - wi * wpi + wr
                wi = wi * wpr + wtemp * wpi + wi
            mmax = istep
        '''轉換為頻率強度'''
        for i in range(self.samples):
            vReal[i] = math.sqrt((vReal[i])**2 + (vImag[i])**2)
class SystemBatteryLevel:
    """
    Read the battery level by sampling the ADC on a pin connected
    to a voltage divider. As the Pycom expansion board is using
    Pin 16, this is also used on other boards as kind of a convention.

    Implementation
    ==============
    Written by Dominik Kapusta <https://github.com/ayoy>. Thanks!
    Improved by Andreas Motl <https://github.com/amotl>.

    License
    =======
    The MIT License (MIT)

    Copyright (c) 2018 Dominik Kapusta

    - https://kapusta.cc/2018/02/02/air-quality-monitor-revisited/
    - https://github.com/ayoy/upython-aq-monitor/blob/lora/lib/adc.py

    Documentation
    =============
    - https://docs.pycom.io/firmwareapi/pycom/machine/adc
    - https://docs.pycom.io/tutorials/all/adc

    More resources
    ==============
    - https://forum.pycom.io/topic/3776/adc-use-to-measure-battery-level-vin-level
    - https://github.com/hiveeyes/hiveeyes-micropython-firmware/issues/5
    - https://community.hiveeyes.org/t/batterieuberwachung-voltage-divider-und-attenuation-fur-microypthon-firmware/2128

    """

    # How many times to sample the ADC for making a reading.
    adc_sample_count = const(1000)

    def __init__(self):
        """
        Initialized ADC unit.
        """

        # 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

    def setup(self, settings):

        self.pin = settings.get('sensors.system.vcc.pin')
        self.resistor_r1 = settings.get('sensors.system.vcc.resistor_r1')
        self.resistor_r2 = settings.get('sensors.system.vcc.resistor_r2')

        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'

        # ADC channel used for sampling the raw value.
        try:
            self.adc = ADC(id=0)
        except TypeError:
            from machine import Pin
            self.adc = ADC(Pin(self.pin))

    def read(self):
        """
        Acquire vbatt reading by sampling ADC.
        """

        # Power on ADC.
        self.adc.init()

        log.debug('Reading battery level on pin {} with voltage divider {}/{}'.
                  format(self.pin, self.resistor_r1, self.resistor_r2))

        # Sample ADC a few times.
        # Todo: Make attenuation factor configurable.
        adc_channel = self.adc.channel(attn=ADC.ATTN_6DB, pin=self.pin)
        adc_samples = [0.0] * self.adc_sample_count
        adc_mean = 0.0
        i = 0
        irq_state = disable_irq()
        while i < self.adc_sample_count:
            sample = adc_channel()
            adc_samples[i] = sample
            adc_mean += sample
            i += 1
        enable_irq(irq_state)

        adc_mean /= self.adc_sample_count
        adc_variance = 0.0
        for sample in adc_samples:
            adc_variance += (sample - adc_mean)**2
        adc_variance /= (self.adc_sample_count - 1)

        raw_voltage = adc_channel.value_to_voltage(4095)
        mean_voltage = adc_channel.value_to_voltage(int(adc_mean))
        mean_variance = (adc_variance * 10**6) // (adc_mean**2)

        # log.debug("ADC readings. count=%u:\n%s" %(self.adc_sample_count, str(adc_samples)))
        log.debug(
            "SystemBatteryLevel: Mean of ADC readings (0-4095) = %15.13f" %
            adc_mean)
        log.debug(
            "SystemBatteryLevel: Mean of ADC voltage readings (0-%dmV) = %15.13f"
            % (raw_voltage, mean_voltage))
        log.debug("SystemBatteryLevel: Variance of ADC readings = %15.13f" %
                  adc_variance)
        log.debug(
            "SystemBatteryLevel: 10**6*Variance/(Mean**2) of ADC readings = %15.13f"
            % mean_variance)

        resistor_sum = self.resistor_r1 + self.resistor_r2
        voltage_millivolt = (adc_channel.value_to_voltage(
            int(adc_mean))) * resistor_sum / self.resistor_r2
        voltage_volt = voltage_millivolt / 1000.0

        # Shut down ADC channel.
        adc_channel.deinit()

        log.debug('Battery level: {}'.format(voltage_volt))

        reading = {'system.voltage': voltage_volt}
        return reading

    def power_off(self):
        """
        Shut down ADC.
        """
        log.info('Turning off ADC')
        self.adc.deinit()
Ejemplo n.º 34
0
from machine import Pin
import utime
import gc
from urequests import get

from machine import I2C
i2c = I2C(sda=Pin(23), scl=Pin(22), freq=400000)

from machine import ADC
adc = ADC(Pin(32))  # create ADC object on ADC pin
adc.read()  # read value, 0-1024

print('Hello world! I can count to 10:')
for i in range(1, 11):
    print(i)


def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('ACME', 'roadrunner')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())


def retrieve_url(url):
    #gc.collect()
Ejemplo n.º 35
0
'''

from machine import ADC
import os

mch = os.uname().machine
if 'LaunchPad' in mch:
    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)
from machine import Signal, Pin, ADC
import time

ledPin2 = machine.Pin(2, machine.Pin.OUT)
Led2 = Signal(ledPin2, invert=True)

adc = ADC(0)
sensor_max = 500  # This is the max reading for my sensor, you'll need to find your max reading
while True:
    stretch = sensor_max - (
        adc.read() * 10
    )  #assign stretch to the maximum less our sensor reading
    Led2.on()
    time.sleep_ms(stretch)
    Led2.off()
    time.sleep_ms(stretch)
Ejemplo n.º 37
0
 def setupADC(self):
     self.adc = ADC()
     self.adcPin = self.adc.channel(pin = 'GP3')
Ejemplo 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()
from machine import Pin, I2C, ADC
import ssd1306
from math import sqrt
from umqttsimple import MQTTClient

# ESP8266 Pin assignment
i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
voltage_in = ADC(0)

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)


def oled_print(value):
    oled.fill(0)
    oled.text('La corriente es', 0, 20)
    oled.text(str(value) + ' A', 0, 30)
    oled.show()


def connect():
    global client_id, mqtt_server, topic_sub
    client = MQTTClient(client_id, mqtt_server)
    client.connect()
    return client


def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(5)
Ejemplo n.º 40
0
 def __init__(self,pin):
     self.adc=ADC(Pin(pin))
     self.adc.atten(ADC.ATTN_11DB) 
Ejemplo n.º 41
0
 def __init__(self, pin_name):
     adc = ADC()
     self.pin = adc.channel(pin=pin_name, attn=ADC.ATTN_11DB, bits=12)
     self.threshold = None
Ejemplo n.º 42
0
#importing the required libraries
from machine import Pin, ADC, PWM 
from time import sleep

# defining the pin arrangement
led_red = Pin(39, Pin.OUT)
button_red= Pin(36, Pin.IN)

#Configure ADC for ESP32
pot_green = ADC(Pin(2))
pot_green.width(ADC.WIDTH_10BIT)
pot_green.atten(ADC.ATTN_11DB)

green_pwm = PWM(Pin(26),5000) #frequency=5000Hz

while True:
  button_state = button_red.value()
  led_red.value(button_state)

  pot_value = pot_green.read()
  green_pwm.duty(pot_value)

  sleep(0.1) #delay
Ejemplo n.º 43
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()
Ejemplo n.º 44
0
import time
import sys
import os
import gc
from machine import Pin
from machine import ADC
#detect pin from esp32
adc = ADC(0)
led = Pin(14, Pin.OUT)

#func ldr
def readLdr():
    lumPerct = (adc.read())
    return lumPerct

def sub_cb(topic, msg):
    print((topic, msg))
    if topic == b'notification' and msg == b'received':
        print('ESP received hello message')

def connect_and_subscribe():
    global client_id, mqtt_server, topic_sub
    client = MQTTClient(client_id, mqtt_server)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic_sub)
    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (mqtt_server, topic_sub))
    return client
Ejemplo n.º 45
0
        else:
            indicatorLed.value(1)
        if int(msg.value) == 1:
            print("Switching indicator led on");
        else:
            print("Switching indicator led off");
    elif msg.channel == illuminationLedChannel:
        if int(msg.value) == 1:
            print("Switching illumination led on");
        else:
            print("Switching illumination led off");
        illuminationLed.value(int(msg.value))
    return

# create adc and the led object
adc = ADC(0)
count=0
ledValue=0
# switch LED off
illuminationLed.value(0)             # active high
indicatorLed.value(1)                # active low

client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, loglevel=logging.INFO)
# register callback
client.on_message=on_message
timestamp = 0

while True:
    client.loop()
    lightIntensity = adc.read()
Ejemplo n.º 46
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)
# 1st GREEN: WiFi connected
# blinking YELLOW: syncing time
# 4x GREEN: boot process done
######################################

# Set up neopixel and turn off
np = Neopixel(Pin(26), 1, 0)
np.set(0,0,0,0)

for _ in range(2):
    np.set(0,B,0,0)
    time.sleep(0.1)
    np.set(0,0,0,0)

# Set up ADC for ACS712 sensor
acs712 = ADC(Pin(ADC5))
acs712.atten(ADC.ATTN_11DB)

# Capture start time
startTime = round(time.time())

# Check network connection
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
ip = wlan.ifconfig()[0]
if ip == '0.0.0.0':
    print("no wifi connection")
    for _ in range(10):
        np.set(0,R,0,0)
        time.sleep(0.1)
        np.set(0,0,0,0)
# 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)