Esempio n. 1
0
 def near(self): 
     id = int(str(self)[4:-1]) #unsafe!
     pin15=Pin(15,Pin.OUT)
     pin15.value(1)
     adc=ADC(Pin(id))
     adc.atten(ADC.ATTN_11DB)
     approximate =adc.read()
     pin15.value(0)
     return approximate
Esempio n. 2
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)
Esempio n. 3
0
    # check MQTT_SERVER, MQTT_USER, MQTT_PSWD
    led_error(step=2)

# chargement des bibliotheques
try:
    from ccs811 import CCS811
    from machine import Pin
except Exception as e:
    print(e)
    led_error(step=3)

# créer les capteurs
try:
    i2c = get_i2c()
    adc = ADC(Pin(TMP36_PIN))
    adc.atten(ADC.ATTN_2_5DB)  # 1.5V max
    # Capteur temp CCS811
    ccs = CCS811(i2c)
    if ccs.check_error:
        raise Exception("CCS811 ERROR_ID = %s" % ccs.error_id.as_text)
except Exception as e:
    print(e)
    led_error(step=4)

try:
    # annonce connexion objet
    sMac = hexlify(WLAN().config('mac')).decode()
    q.publish("connect/%s" % CLIENT_ID, sMac)
    # Annonce l'état
except Exception as e:
    print(e)
Esempio n. 4
0
def upd_send(data):
    print(data)
    s.sendto(data, ADD)
    return None


s = socket(AF_INET, SOCK_DGRAM)
BUFF = 1024
HOST = "192.168.1.109"
PORT = 4001
ADD = (HOST, PORT)

#Links Joystick
p_l = Pin(33, Pin.IN)
x_l = ADC(Pin(35))
x_l.atten(ADC.ATTN_11DB)
x_l.width(ADC.WIDTH_12BIT)
y_l = ADC(Pin(32))
y_l.atten(ADC.ATTN_11DB)
y_l.width(ADC.WIDTH_12BIT)

#Rechts Joystick
p_r = Pin(34, Pin.IN)
x_r = ADC(Pin(36))
x_r.atten(ADC.ATTN_11DB)
x_r.width(ADC.WIDTH_12BIT)
y_r = ADC(Pin(39))
y_r.atten(ADC.ATTN_11DB)
y_r.width(ADC.WIDTH_12BIT)
#Loop
while True:
Esempio n. 5
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()
Esempio n. 6
0
def read_battery_voltage(pin=35):
    adc = ADC(Pin(pin))
    adc.atten(ADC.ATTN_11DB)
    return 2 * ADC_to_voltage(adc, 11)
class gameOGO():
    max_vol = 6
    duty = {0: 0, 1: 0.05, 2: 0.1, 3: 0.5, 4: 1, 5: 2, 6: 70}
    tones = {
        'c4': 262,
        'd4': 294,
        'e4': 330,
        'f4': 349,
        'f#4': 370,
        'g4': 392,
        'g#4': 415,
        'a4': 440,
        "a#4": 466,
        'b4': 494,
        'c5': 523,
        'c#5': 554,
        'd5': 587,
        'd#5': 622,
        'e5': 659,
        'f5': 698,
        'f#5': 740,
        'g5': 784,
        'g#5': 831,
        'a5': 880,
        'b5': 988,
        'c6': 1047,
        'c#6': 1109,
        'd6': 1175,
        ' ': 0
    }

    def __init__(self):
        # True =  SPI display, False = I2C display

        self.ESP32 = True
        self.useSPI = True
        self.displayTimer = ticks_ms()
        self.vol = int(self.max_vol)
        seed(ticks_us())
        self.btnU = 1 << 1
        self.btnL = 1 << 2
        self.btnR = 1 << 3
        self.btnD = 1 << 4
        self.btnA = 1 << 5
        self.btnB = 1 << 6
        self.btnMenu = 1 << 7
        self.btnVol = 1 << 8
        self.btnSel = 1 << 9
        self.btnSt = 1 << 10

        self.btnUval = 0
        self.btnDval = 0
        self.btnLval = 0
        self.btnRval = 0
        self.btnAval = 0
        self.btnBval = 0
        self.btnMenuval = 0
        self.btnVolval = 0
        self.btnSelval = 0
        self.btnStval = 0
        self.frameRate = 30
        self.maxBgm = 1
        self.bgm = 1
        self.songIndex = 0
        self.songStart = -1
        self.songEnd = -2
        self.songLoop = -3
        self.silence = 0
        self.songSpeed = 1
        self.timeunit = 1
        self.notes = False
        self.songBuf = []
        self.Btns = 0
        self.lastBtns = 0

        self.dac_pin = Pin(25, Pin.OUT, value=1)  # switch speaker on
        self.PinBuzzer = Pin(26, Pin.OUT)
        self.beeper = PWM(self.PinBuzzer, 500, duty=0)
        self.beeper2 = PWM(self.PinBuzzer, 500, duty=0)
        self.timerInitialized = False
        self.tft = display.TFT()
        self.tft.init(self.tft.ILI9341,
                      width=240,
                      height=320,
                      speed=40000000,
                      backl_pin=14,
                      backl_on=1,
                      miso=19,
                      mosi=23,
                      clk=18,
                      cs=5,
                      dc=21,
                      hastouch=False)
        self.tft.clear(self.tft.BLACK)
        self.tft.orient(self.tft.LANDSCAPE_FLIP)
        self.screenW, self.screenH = self.tft.screensize()
        ''' fonts available in ili9341
        tft.FONT_Small, 8x12
        tft.FONT_Default, 13x13
        tft.FONT_7seg, 18x31
        tft.FONT_Ubuntu, 15x16
        tft.FONT_Comic, 25x28
        tft.FONT_Tooney, 32x37
        tft.FONT_Minya, 20x24
        '''
        self.tft.font(self.tft.FONT_Ubuntu, rotate=0)

        self.PinBtnA = Pin(BUTTON_A_PIN, Pin.IN, Pin.PULL_UP)
        self.PinBtnB = Pin(BUTTON_B_PIN, Pin.IN, Pin.PULL_UP)
        self.PinBtnMenu = Pin(BUTTON_MENU_PIN, Pin.IN, Pin.PULL_UP)
        self.PinBtnVol = Pin(BUTTON_VOLUME_PIN, Pin.IN, Pin.PULL_UP)
        self.PinBtnSel = Pin(BUTTON_SELECT_PIN, Pin.IN, Pin.PULL_UP)
        self.PinBtnSt = Pin(BUTTON_START_PIN, Pin.IN)

        self.adcX = ADC(BUTTON_JOY_X_PIN)
        self.adcY = ADC(BUTTON_JOY_Y_PIN)
        #self.adc = ADC(PADDLE_PIN)
        self.adcX.atten(ADC.ATTN_11DB)
        self.adcY.atten(ADC.ATTN_11DB)
        #self.adc.atten(ADC.ATTN_11DB)

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

        self.beeper.deinit()
        self.beeper2.deinit()
        self.adcX.deinit()
        self.adcY.deinit()
        self.tft.deinit()
        self.songIndex = 0
        if self.timerInitialized:
            self.timer.deinit()

    def getPaddle(self):
        return 512
        # ESP32 - 142 to 3155
        # return max ( min (int (self.adc.read() / 2.935) - 48, 1023),0)

    def pressed(self, btn):
        return (self.Btns & btn)

    def justPressed(self, btn):
        return (self.Btns & btn) and not (self.lastBtns & btn)

    def justReleased(self, btn):
        return (self.lastBtns & btn) and not (self.Btns & btn)

    def getBtn(self):

        self.btnAval = not self.PinBtnA.value()
        self.btnBval = not self.PinBtnB.value()
        self.btnMenuval = not self.PinBtnMenu.value()
        self.btnVolval = not self.PinBtnVol.value()
        self.btnSelval = not self.PinBtnSel.value()
        self.btnStval = not self.PinBtnSt.value()

        val = self.adcX.read()
        self.btnLval = 1 if val > 2500 else 0
        self.btnRval = 1 if 1500 < val < 2000 else 0

        val = self.adcY.read()
        self.btnUval = 1 if val > 2500 else 0
        self.btnDval = 1 if 1500 < val < 2000 else 0

        self.lastBtns = self.Btns
        self.Btns = 0
        self.Btns = self.Btns | self.btnUval << 1 | self.btnLval << 2 | self.btnRval << 3 | self.btnDval << 4 | self.btnAval << 5 | self.btnBval << 6
        self.Btns = self.Btns | self.btnMenuval << 7 | self.btnVolval << 8 | self.btnSelval << 9 | self.btnStval << 10

        return self.Btns

    def setVol(self):
        if self.pressed(self.btnVol):
            if self.justPressed(self.btnU):
                self.vol = min(self.vol + 1, self.max_vol)
                self.playTone('c4', 100)
                return True
            elif self.justPressed(self.btnD):
                self.vol = max(self.vol - 1, 0)
                self.playTone('d4', 100)
                return True

        return False

    def setFrameRate(self):
        if self.pressed(self.btnSel):
            if self.justPressed(self.btnU):
                self.frameRate = self.frameRate + 5 if self.frameRate < 120 else 5
                self.playTone('e4', 100)
                return True
            elif self.justPressed(self.btnD):
                self.frameRate = self.frameRate - 5 if self.frameRate > 5 else 120
                self.playTone('f4', 100)
                return True
        return False

    def center_msg(self, msg, color_fg, color_bg):
        self.tft.set_bg(color_bg)
        self.tft.textClear((self.screenW - self.tft.textWidth(msg)) // 2,
                           self.screenH // 2, msg, color_bg)
        self.tft.text((self.screenW - self.tft.textWidth(msg)) // 2,
                      self.screenH // 2, msg, color_fg)

    def display_msg(self, x, y, msg, color_fg, color_bg):
        self.tft.set_bg(color_bg)
        self.tft.textClear(x, y, msg, color_bg)
        self.tft.text(x, y, msg, color_fg)

    def display_vol(self):
        fontW, fontH = self.tft.fontSize()
        self.tft.rect(self.screenW - fontW * self.max_vol, 0,
                      self.max_vol * fontW, fontH, self.tft.GREEN,
                      self.tft.BLACK)
        self.tft.rect(self.screenW - fontW * self.max_vol + 1, 1,
                      self.vol * fontW - 2, fontH - 2, self.tft.RED,
                      self.tft.RED)

    def playTone(self, tone, tone_duration, rest_duration=0):

        self.beeper = PWM(self.PinBuzzer, self.tones[tone],
                          self.duty[self.vol])
        sleep_ms(tone_duration)
        self.beeper.deinit()
        sleep_ms(rest_duration)

    def playSound(self, freq, tone_duration, rest_duration=0):

        self.beeper = PWM(self.PinBuzzer, freq, self.duty[self.vol])
        sleep_ms(tone_duration)
        self.beeper.deinit()
        sleep_ms(rest_duration)

    def handleInterrupt(self, timer):
        self.beeper2.deinit(
        )  # note has been played logn enough, now stop sound

        if self.songBuf[self.songIndex] == self.songLoop:
            self.songIndex = 3  # repeat from first note

        if self.songBuf[self.songIndex] >= 0:
            if self.songBuf[self.songIndex] == 0:
                self.beeper2 = PWM(self.PinBuzzer, 100, 0)
            elif self.notes:
                self.beeper2 = PWM(self.PinBuzzer,
                                   self.tones[self.songBuf[self.songIndex]],
                                   self.duty[self.vol])
            else:
                self.beeper2 = PWM(self.PinBuzzer,
                                   self.songBuf[self.songIndex],
                                   self.duty[self.vol])
            self.timer.init(period=int(self.songBuf[self.songIndex + 1] *
                                       self.timeunit * self.songSpeed),
                            mode=Timer.ONE_SHOT,
                            callback=self.handleInterrupt)
            self.songIndex += 2

    def startSong(self, songBuf=None):
        if self.bgm:
            if songBuf != None:
                self.songBuf = songBuf
            if self.songBuf[0] != self.songStart:
                print("Cannot start Song, Invalid songBuf")
                return False
            self.notes = self.songBuf[1]
            self.timeunit = self.songBuf[2]
            self.songIndex = 3
            if not self.timerInitialized:
                self.timerInitialized = True
                self.timer = Timer(1)
            self.timer.init(period=100,
                            mode=Timer.ONE_SHOT,
                            callback=self.handleInterrupt)

    def stopSong(self):
        self.songIndex = 0

    def random(self, x, y):
        return randint(x, y)

    def wait(self):
        timer_dif = int(1000 / self.frameRate) - ticks_diff(
            ticks_ms(), self.displayTimer)
        if timer_dif > 0:
            sleep_ms(timer_dif)
        self.displayTtimer = ticks_ms()
Esempio n. 8
0
vext = Pin(21, Pin.OUT)
vext.value(0)
sleep(0.2)
rst = Pin(16, Pin.OUT)
rst.value(1)
sleep(1)
scl = Pin(15, Pin.OUT, Pin.PULL_UP)
sda = Pin(4, Pin.OUT, Pin.PULL_UP)
i2c = I2C(scl=scl, sda=sda, freq=450000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3c)

Pin(21, Pin.OUT, value=1)

adc = ADC(Pin(36, Pin.IN))
adc.atten(ADC.ATTN_6DB)

nmuestras = 10
i = 0

while 1:
    value = adc.read()
    """
	for x in range(1,nmuestras):
		value = value + adc.read()
	value = value/10
	"""
    oled.fill(value)
    oled.show()
    """
	oled.text(str(value),32,32)
    # function to get average of a list
    return sum(lst) / len(lst)


def ReadEC(voltage, temp):

    #rawEC = 1000*voltage/820.0/200.0

    ecValue = voltage / (1.0 + 0.0185 * (temp - 25.0))

    return ecValue


# Pin definition and ADC initialization
ec = ADC(Pin(34))
ec.atten(ADC.ATTN_11DB)  # Reading range: 3.3V

# DS18B20 temperatur
ds18_temp = 25

# Creat empty list for value storage
buf = []
sample = range(5)

for i in sample:
    buf.append(ec.read())
    sleep(1)
    print(buf)

avgValue = Average(buf)
Esempio n. 10
0
#esp8266 ya göre çalıştık

"""

"""
Bit kısmı okunan değeri map fonksiyonuna göre çevirtmek
için yapılır
"""
"""
ADC.width(ADC.WIDTH_9BIT)# 0 ile 511 arasında 2^9
ADC.width(ADC.WIDTH_10IT)# 0 ile 1023 arasında okuyabildiğmiz veri
ADC.width(ADC.WIDTH_11BIT)#0 ile 2047 arasında""" 
ADC.width(ADC.WIDTH_12BIT)#0 ile 4095 

" Esp32 ye göre yapıyoruz"

pot = ADC(Pin(34))
"""
pot.atten(ADC.ATTN_0DB) #1.2V analog değer okuyor
pot.atten(ADC.ATTN_2_5DB)#1.5v değeri karşılıyor 
pot.atten(ADC.ATTN_6DB) #2.0V"""
pot.atten(ADC.ATTN_11DB)# 3.3v göre 




while True :
  pot_deger=pot.read()
  print(str(pot_deger)+" okunan potasiyometre değeri")
  sleep(0.1)
Esempio n. 11
0
i2c = I2C(id=0, scl=Pin(SCL), sda=Pin(SDA), freq=100000)
imu = MPU9250(i2c)


def imu_collect():
    return {
        "accel": Vector3.from_imu_vector(imu.accel.xyz),
        "gyro": Vector3.from_imu_vector(imu.gyro.xyz),
        "mag": Vector3.from_imu_vector(imu.mag.xyz),
        "temp": imu.temperature
    }


mic_adc = ADC(Pin(ADC6))
mic_adc.atten(ADC.ATTN_11DB)


def calibrate():
    print("calibrating...")
    total_noise = 0
    total_temp = 0
    total_accel = Vector3()
    total_gyro = Vector3()
    total_mag = Vector3()
    for _ in range(CALIBRATION_SIZE):
        total_noise += mic_adc.read()
        imu_values = imu_collect()
        total_accel += imu_values["accel"]
        total_gyro += imu_values["gyro"]
        total_mag += imu_values["mag"]
Esempio n. 12
0
class gameESP():
    max_vol = 6
    duty = {0: 0, 1: 0.05, 2: 0.1, 3: 0.5, 4: 1, 5: 2, 6: 70}
    tones = {
        'c4': 262,
        'd4': 294,
        'e4': 330,
        'f4': 349,
        'f#4': 370,
        'g4': 392,
        'g#4': 415,
        'a4': 440,
        "a#4": 466,
        'b4': 494,
        'c5': 523,
        'c#5': 554,
        'd5': 587,
        'd#5': 622,
        'e5': 659,
        'f5': 698,
        'f#5': 740,
        'g5': 784,
        'g#5': 831,
        'a5': 880,
        'b5': 988,
        'c6': 1047,
        'c#6': 1109,
        'd6': 1175,
        ' ': 0
    }

    def __init__(self):
        # True =  SPI display, False = I2C display
        self.ESP32 = True
        self.paddle2 = False
        self.useSPI = True
        self.timer = 0
        self.vol = int(self.max_vol / 2) + 1
        seed(ticks_us())
        self.btnU = 1 << 1
        self.btnL = 1 << 2
        self.btnR = 1 << 3
        self.btnD = 1 << 4
        self.btnA = 1 << 5
        self.btnB = 1 << 6
        self.btnUval = 0
        self.btnDval = 0
        self.btnLval = 0
        self.btnRval = 0
        self.btnAval = 0
        self.btnBval = 0
        self.frameRate = 30
        self.screenW = 128
        self.screenH = 64
        self.Btns = 0
        self.lastBtns = 0

        self.PinBuzzer = Pin(26, Pin.OUT)

        # configure oled display SPI SSD1306
        self.spi = SPI(2,
                       baudrate=14500000,
                       sck=Pin(18),
                       mosi=Pin(23),
                       miso=Pin(19))
        #        display = Display(spi, rst=Pin(4), dc=Pin(21), cs=Pin(5), )
        #DC, RES, CS
        self.display = SSD1306_SPI(128, 64, self.spi, Pin(21), Pin(4), Pin(5))

        self.PinBtnA = Pin(32, Pin.IN, Pin.PULL_UP)
        self.PinBtnB = Pin(33, Pin.IN, Pin.PULL_UP)
        self.adcX = ADC(34)
        self.adcY = ADC(35)
        self.adc = ADC(39)
        self.adcX.atten(ADC.ATTN_11DB)
        self.adcY.atten(ADC.ATTN_11DB)
        self.adc.atten(ADC.ATTN_11DB)

    def deinit(self):
        self.adc.deinit()
        self.adcX.deinit()
        self.adcY.deinit()
        if self.useSPI:
            self.spi.deinit()

    def getPaddle(self):
        # ESP32 - 142 to 3155
        return max(min(int(self.adc.read() / 2.935) - 48, 1023), 0)

    def pressed(self, btn):
        return (self.Btns & btn)

    def justPressed(self, btn):
        return (self.Btns & btn) and not (self.lastBtns & btn)

    def justReleased(self, btn):
        return (self.lastBtns & btn) and not (self.Btns & btn)

    def getBtn(self):

        self.btnAval = not self.PinBtnA.value()
        self.btnBval = not self.PinBtnB.value()

        val = self.adcX.read()
        self.btnLval = 1 if val > 2500 else 0
        self.btnRval = 1 if 1500 < val < 2000 else 0

        val = self.adcY.read()
        self.btnUval = 1 if val > 2500 else 0
        self.btnDval = 1 if 1500 < val < 2000 else 0

        self.lastBtns = self.Btns
        self.Btns = 0
        self.Btns = self.Btns | self.btnUval << 1 | self.btnLval << 2 | self.btnRval << 3 | self.btnDval << 4 | self.btnAval << 5 | self.btnBval << 6
        return self.Btns
        print(self.Btns)

    def setVol(self):
        if self.pressed(self.btnB):
            if self.justPressed(self.btnU):
                self.vol = min(self.vol + 1, self.max_vol)
                self.playTone('c4', 100)
                return True
            elif self.justPressed(self.btnD):
                self.vol = max(self.vol - 1, 0)
                self.playTone('d4', 100)
                return True

        return False

    def playTone(self, tone, tone_duration, rest_duration=0):
        beeper = PWM(self.PinBuzzer,
                     freq=self.tones[tone],
                     duty=self.duty[self.vol])
        sleep_ms(tone_duration)
        beeper.deinit()
        sleep_ms(rest_duration)

    def playSound(self, freq, tone_duration, rest_duration=0):
        beeper = PWM(self.PinBuzzer, freq, duty=self.duty[self.vol])
        sleep_ms(tone_duration)
        beeper.deinit()
        sleep_ms(rest_duration)

    def random(self, x, y):
        return getrandbits(20) % (y - x + 1) + x

    def display_and_wait(self):
        self.display.show()
        timer_dif = int(1000 / self.frameRate) - ticks_diff(
            ticks_ms(), self.timer)
        if timer_dif > 0:
            sleep_ms(timer_dif)
        self.timer = ticks_ms()
Esempio n. 13
0
        else:
            authmode=0
        self.ap.config(essid=essid,password=password,authmode=authmode, channel=channel)

    def disable_APWiFi(self):
        self.ap.active(False)
        print('disable AP WiFi...')


# 3 rgb leds
rgb = NeoPixel(Pin(17, Pin.OUT), 3, 3, 1, brightness=0.3)
rgb.write()

# light sensor
light = ADC(Pin(39))
light.atten(light.ATTN_11DB)

# sound sensor
sound = ADC(Pin(36))
sound.atten(sound.ATTN_11DB)

# buttons
button_a = Pin(0, Pin.IN, Pin.PULL_UP)
button_b = Pin(2, Pin.IN, Pin.PULL_UP)

# touchpad
touchPad_P = TouchPad(Pin(27))
touchPad_Y = TouchPad(Pin(14))
touchPad_T = TouchPad(Pin(12))
touchPad_H = TouchPad(Pin(13))
touchPad_O = TouchPad(Pin(15))
Esempio n. 14
0
# 6-axies motion sensor:mpu6050
motion = Motion()
accelerometer = motion.accelerometer
gyroscope = motion.gyroscope

# 3-axies megnetic sensor:MMC5983MA
magnetic = Magnetic()

# 3 rgb leds
rgb = NeoPixel(Pin(17, Pin.OUT), 3, 3, 1)
rgb.write()

# light sensor
light = ADC(Pin(39))
light.atten(light.ATTN_11DB)


# sound sensor
class sound():
    @staticmethod
    def init():
        audio.recorder_init()
        audio.set_volume(0)

    @staticmethod
    def deinit():
        audio.recorder_deinit()

    @staticmethod
    def read():
Esempio n. 15
0
from codes.autoconnect import *
import socket
import time
from machine import UART, ADC, DAC, Pin

pin = Pin(2, Pin.IN)
light = ADC(Pin(35))
light.atten(ADC.ATTN_11DB)
light.width(ADC.WIDTH_12BIT)
dac = DAC(Pin(25), bits=12)

INIT = 0

uart = UART(2, 9600)
while 1:
    while 1:
        connect_res, ipaddr = connect()
        uart.write(str(connect_res))
        if connect_res:
            break
        time.sleep(10)

    if not INIT:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                          socket.IPPROTO_UDP)
        addr0 = (ipaddr, 8080)
        s.bind(addr0)
        s.settimeout(30.0)

        s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                           socket.IPPROTO_UDP)
Esempio n. 16
0
# Brandon Gant
# Created: 2020-08-11
# Updated: 2020-09-09

from machine import Pin, ADC
from time import sleep

bright = ADC(Pin(38))  #  1K voltage divider resistor
dark = ADC(Pin(37))  # 51K voltage divider resistor

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

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

while True:
    print("%s    %s" % (bright.read(), dark.read()))
    sleep(1)
Esempio n. 17
0
from machine import Pin
from machine import ADC
from dht import DHT11
from time import sleep
import network

# These two imports are local files from this folder
from allthingstalk import AllThingsTalkDevice
from config import config

moisture = ADC(Pin(32))
moisture.atten(ADC.ATTN_11DB)

temperature_humidity = DHT11(Pin(22))

# Create an object for the connection to AllThingsTalk
cloud = AllThingsTalkDevice(config["device_id"], config["device_token"])

# Create an object for the wifi connection
wifi = network.WLAN(network.STA_IF)


# This is a function, it is called from the while-loop further down
def connect_wifi():
    wifi.active(True)
    if not wifi.isconnected():
        print('connecting to network...')
        wifi.connect(config["wifi_ssid"], config["wifi_password"])
        while not wifi.isconnected():
            pass
    print('network config:', wifi.ifconfig())
Esempio n. 18
0
from machine import UART, Pin, ADC
from time import sleep, sleep_ms

serial = UART(2, 9600, tx=17, rx=16)
serial.init(baudrate=9600, bits=8, parity=None, stop=1)
sleep(1.5)

ADC.width(ADC.WIDTH_10BIT)
mea = ADC(Pin(34))
mea.atten(ADC.ATTN_11DB)
led_indicate = Pin(2, Pin.OUT)
led_indicate.on()
tx_led = Pin(27, Pin.OUT)
valve_led = Pin(33, Pin.OUT)
pump_valve = Pin(22, Pin.OUT)
pump_valve.on()


def tx_blink():  # 750ms 0.75
    led_indicate.off()
    tx_led.on()
    sleep_ms(150)
    tx_led.off()
    sleep_ms(150)
    tx_led.on()
    sleep_ms(150)
    tx_led.off()
    sleep_ms(150)
    tx_led.on()
    sleep_ms(150)
    tx_led.off()
Esempio n. 19
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()
Esempio n. 20
0
led_bleue = Pin(2, Pin.OUT)
led_verte = Pin(18, Pin.OUT)
led_jaune = Pin(19, Pin.OUT)
led_rouge = Pin(23, Pin.OUT)

tp1 = TouchPad(Pin(15))
tp2 = TouchPad(Pin(4))

bpA = Pin(25, Pin.IN)
bpB = Pin(34, Pin.IN)
bpC = Pin(39, Pin.IN)
bpD = Pin(36, Pin.IN)

p1 = ADC(Pin(35))        # cree l'objet ADC   # CHANGEMENT !
p1.atten(ADC.ATTN_11DB)  # set 11dB input attenuation (range 0.0v - 3.6v)
p1.width(ADC.WIDTH_9BIT) # set 9 bit return values (returned range 0-511)

p2 = ADC(Pin(33))        # cree l'objet ADC
p2.atten(ADC.ATTN_11DB)  # set 11dB input attenuation (range 0.0v - 3.6v)
p2.width(ADC.WIDTH_9BIT) # set 9 bit return values (returned range 0-511)

ldr = ADC(Pin(32))        # cree l'objet ADC
ldr.atten(ADC.ATTN_11DB)  # set 11dB input attenuation (range 0.0v - 3.6v)
ldr.width(ADC.WIDTH_9BIT) # set 9 bit return values (returned range 0-511)

n = 8                          # nombre de pixels
p = 26                         # pin de commande du neopixel
np = NeoPixel(Pin(p), n)       # creation de l'instance np

buzzer = PWM(Pin(5))
Esempio n. 21
0
    print(">>> temp_init")
    from util.octopus import temp_init
    ts = temp_init()  # ts := temp sensor
    if len(ts.ts) == 0:
        ts = None
    sensorsDisplay()

if ios.get("mois"):
    print(">>> moisture_init")
    from machine import ADC
    from hydroponics.iot_garden import get_moisture
    pwM = Pin(pinout.PWM1_PIN, Pin.OUT)  # moisture
    pin_adcM = Pin(pinout.I35_PIN, Pin.IN)
    adcM = ADC(pin_adcM)
    if ios.get("cmois"):
        adcM.atten(ADC.ATTN_2_5DB)

if ios.get("relay"):
    print(">>> relay_init")
    from util.iot import Relay
    relayPump = Relay()
    relayPump.value(1)
    sleep(1)
    relayPump.value(0)

if ios.get("fet"):
    print(">>> pwm_init")
    from hydroponics.iot_garden import pwm_init, pwm_fade_in
    pwmLed = pwm_init()
    pwm_fade_in(pwmLed, 1000)
    pwmLed.duty(0)
Esempio n. 22
0
class LedShow:
    def __init__(self):
        self.led_number = 120
        self.led_pin = 12
        self.np = NeoPixel(Pin(12,Pin.OUT),self.led_number)
        self.KEY1=Pin(27,Pin.IN,Pin.PULL_UP)
        #麦克风
        self.micc = ADC(Pin(34))
        self.micc.atten(self.micc.ATTN_11DB)
        # 144led 变态RGB 实际为GRB
        self.color = [
            (0,0,0),#黑
            (255,0,0),#绿
            (255,255,0),#黄
            (255,255,0),#橙色
            (0,255,0),#红
            (255,0,255),#青色
            (0,0,255),#蓝色
            (0,255,255),#粉红
            (255,255,255),#白
            (247,238,214),#米黄
            (0,0,128),#蓝色
            ] #七彩

    def clear(self):
        for i in range(self.led_number):
            self.np[i] = (0, 0, 0)
        self.np.write()

    def Start(self):
        for x in range(6):
            for y in range(10):
                self.np[x*10+y] = self.color[6]
                self.np[119-x*10-y] = self.color[6]
            time.sleep(0.1)
            self.np.write()
        for x in range(6):
            for y in range(10):
                self.np[(x+6)*10+y] = self.color[0]
                self.np[59-x*10-y] = self.color[0]
            time.sleep(0.1)
            self.np.write()
        
    
    def PrintDot(self,eTxt,cr=6):
        ctext  =aztxt.Zifu[eTxt]
        for x in range(0,8):
            for y in range(0,8):
                if ctext[x][y] is 1:
                    self.np[9-x+y*10]=self.color[cr]
        self.np.write()

    def SetColor(self,cc=6):
        for x in range(self.led_number):            
            self.np[x] = self.color[cc]
            self.np.write()

    def VuColor(self,val,cc=6):
        htt = val
        for x in range(12):
            
            for y in range(10):
                if y < htt[x]:                    
                    self.np[x*10+y] = self.color[cc]
                elif y==htt[x]:
                    self.np[x*10+y] = self.color[10]                    
                else:
                    self.np[x*10+y] = self.color[0]           
        self.np.write()  

    def sample(self):
        values = []
        start = time.ticks_ms()
        for i in range(16):
            val = self.micc.read()
            values.append(val)
        return (time.ticks_ms() - start, max(values) - min(values))

    def getloudness(self):
        maxloudness = 0
        for i in range(8):
            timetaken, loudness = self.sample()  
            if loudness > maxloudness:
                maxloudness = loudness
        val = maxloudness*10/3000
        return math.floor(val)

    def micphone(self):
        while True:
            tones = []
            for i in range(12):
                t = self.getloudness()
                tones.append(t) 
            print(tones)       
            self.VuColor(tones)
            if self.KEY1.value() == 0:     #按键被按下
                time.sleep_ms(2)    #消除抖动
                if self.KEY1.value() == 0:   #确认按键被按下
                    print("Key1 close")
                    break
Esempio n. 23
0
import machine
import utime
from machine import Pin
from machine import ADC

mosfet1 = Pin(13, Pin.OUT)
mosfet2 = Pin(12, Pin.OUT)
mosfet3 = Pin(27, Pin.OUT)

bttn = ADC(Pin(33))
bttn.atten(ADC.ATTN_11DB)


def triggerWaitH(pin, number):
    while pin.read() < number:
        pass


def triggerWaitL(pin, number):
    while pin.read() > number:
        pass


cont = True

while cont:
    d1 = int(input())
    d2 = int(input())
    d3 = int(input())

    triggerWaitH(bttn, 3500)
Esempio n. 24
0
from machine import Pin, ADC
import time

adc = ADC(Pin(34))  # 設定進行 ADC 的腳位
adc.atten(ADC.ATTN_11DB)  # 設定最大電壓為3.6V

while True:
    print(adc.read())  # 讀取 ADC 值
    time.sleep(0.05)  # 等候 0.05 秒
# 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)
Esempio n. 26
0
from machine import Pin, ADC
from time import sleep

pot = ADC(0)
pot.atten(ADC.ATTN_11DB)  #Full range: 3.3v

while True:
    pot_value = pot.read()
    print(pot_value)
    sleep(0.1)
Esempio n. 27
0
led_lef = Pin(18, Pin.OUT)

light_dict = {1: led_lef, 2: led_down, 3: led_up, 4: led_down}

led_up.value(0)
led_down.value(0)
led_lef.value(0)
led_rig.value(0)

"Joystick code"
PINX = 34  # needs to be a pin that supports ADC
PINY = 32  # needs to be a pin that supports ADC
PINSW = 27

cx = ADC(Pin(PINX))
cx.atten(ADC.ATTN_11DB)
cy = ADC(Pin(PINY))
cy.atten(ADC.ATTN_11DB)
sw = Pin(PINSW, Pin.IN, Pin.PULL_UP)


def button_pressed(p):
    print('Click')


def joystick(adc):
    return max(6, min(120, int(adc.read() / 32)))


def check_joystick(dx, dy):
    "0=center, 1=left, 2=right, 3=up, 4=down, 5=up-left, 6=down-right, 7=up-right, 8=down-left"
Esempio n. 28
0
    import urequests
    import machine
    import json
    import gc
    import micropython

    SSID = "Xperia X"
    PASSWORD = "******"
    port = 500
    wlan = None
    s = None

    #sensor pins are set here
    pot = ADC(Pin(34))
    pot.width(ADC.WIDTH_10BIT)
    pot.atten(ADC.ATTN_6DB)

    def connectWifi(ssid, passwd):  # function to connect to the Web
        global wlan  # declare a WLAN object
        wlan = network.WLAN(network.STA_IF)  # create a wlan object
        wlan.active(True)  # Activate the network interface
        wlan.disconnect()  # Disconnect the last connected WiFi
        wlan.connect(ssid, passwd)  # connect wifi
        while (wlan.ifconfig()[0] == '0.0.0.0'):  # wait for connection
            sleep_ms(1)
        sleep_ms(1000)  # hold on for 1 second
        print("Connecting to WLAN")

    def main():

        url = "https://shielded-tor-11299.herokuapp.com/postdata"
Esempio n. 29
0
from machine import ADC, Pin  # machineモジュールのADCクラスとPinクラスをインポート
import time  # timeモジュールをインポート
adc = ADC(Pin(35))  # 35番ピンを制御するADCオブジェクトを生成
adc.atten(ADC.ATTN_11DB)  # 減衰率を11dBに設定
while True:
    val = []  # ADC値のリストを作る
    for i in range(20):  # 複数回データを測定する
        val.append(adc.read())  # データを測定し、リストに追加
    mean_val = sum(val) / len(val)  # 平均値を求める
    temp = (mean_val / 4095 * 3.3 + 0.1132 - 0.6) / 0.01  # 温度を計算
    print(temp)
    time.sleep(1)  # 1秒待つ
Esempio n. 30
0
            authmode=4
        else:
            authmode=0
        self.ap.config(essid=essid,password=password,authmode=authmode, channel=channel)

    def disable_APWiFi(self):
        self.ap.active(False)
        print('disable AP WiFi...')

# 3 rgb leds
rgb = NeoPixel(Pin(17, Pin.OUT), 3, 3, 1, brightness=0.3)
rgb.write()

# light sensor
light = ADC(Pin(39))
light.atten(light.ATTN_11DB)

# sound sensor
sound = ADC(Pin(36))
sound.atten(sound.ATTN_11DB)
# Potentiometer sensor
Potentiometer = ADC(Pin(34))
Potentiometer.atten(sound.ATTN_11DB)


# buttons
class Button:
    def __init__(self, pin_num, reverse=False):
        self.__reverse = reverse
        (self.__press_level, self.__release_level) = (0, 1) if not self.__reverse else (1, 0)
        self.__pin = Pin(pin_num, Pin.IN, pull=Pin.PULL_UP)
'''
Smart LED 基于光敏电阻的智能照明
如果光照强度小于某个阈值,就开灯。
'''


from machine import ADC,Pin
import utime

led_pin = Pin(13)
# 设置D33号引脚作为ADC采样引脚
pin_read = Pin(33)
# 声明ADC对象
adc = ADC(pin_read)
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

# 设定阈值
boudary = 2000

while True:
    # 数据采样 模拟信号 -> 数字信号
    # 读取光照强度 illumination intensity
    intensity = adc.read()
    
    is_dark = intensity > boudary
    if is_dark:
        led_pin.value(1)
    else:
        led_pin.value(0)
        # 如果光照强度
Esempio n. 32
0
class MPythonPin():
    def __init__(self, pin, mode=PinMode.IN, pull=None):
        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG, PinMode.OUT_DRAIN]:
            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG,OUT_DRAIN'")
        if pin == 4:
            raise TypeError("P4 is used for light sensor")
        if pin == 10:
            raise TypeError("P10 is used for sound sensor")
        try:
            self.id = pins_remap_esp32[pin]
        except IndexError:
            raise IndexError("Out of Pin range")
        if mode == PinMode.IN:
            # if pin in [3]:
            #     raise TypeError('IN not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.IN, pull)
        if mode == PinMode.OUT:
            if pin in [2, 3]:
                raise TypeError('OUT not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.OUT, pull)
        if mode == PinMode.OUT_DRAIN:
            if pin in [2, 3]:
                raise TypeError('OUT_DRAIN not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.OPEN_DRAIN, pull)
        if mode == PinMode.PWM:
            if pin not in [0, 1, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 19, 20, 23, 24, 25, 26, 27, 28]:
                raise TypeError('PWM not supported on P%d' % pin)
            self.pwm = PWM(Pin(self.id), duty=0)
        if mode == PinMode.ANALOG:
            if pin not in [0, 1, 2, 3, 4, 10]:
                raise TypeError('ANALOG not supported on P%d' % pin)
            self.adc = ADC(Pin(self.id))
            self.adc.atten(ADC.ATTN_11DB)
        self.mode = mode

    def irq(self, handler=None, trigger=Pin.IRQ_RISING):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return self.Pin.irq(handler, trigger)

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

    def write_digital(self, value):
        if self.mode not in [PinMode.OUT, PinMode.OUT_DRAIN]:
            raise TypeError('the pin is not in OUT or OUT_DRAIN mode')
        self.Pin.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)
Esempio n. 33
0
class tempNTC3950(Sensor):
    ''' De NTC 3950 thermistor is een analoge sensor waarbij de weerstand daalt
        bij stijgende temperatuur. NTC staat voor Negatieve Temperatuur Coefficient '''
    def __init__(self, pinADC, waardeWeerstand, waardeNTC, info, debug=False):
        super().__init__(info, debug)
        self.__pinADC = pinADC
        self.__weerstand = waardeWeerstand
        self.__waardeNTC = waardeNTC
        self.__ntc = None

    def start(self):
        try:
            self.__ntc = ADC(Pin(self.__pinADC))
            self.__ntc.atten(ADC.ATTN_11DB)
            if self.debug:
                print("ntc3950 is gestart")
            Sensor.teller += 1
            return (0, 1)
        except Exception as E:
            if self.debug == True:
                print("fout bij het starten van ntc3950")
                print(E)
            return (-1, -1)

    def meet(self):
        somV0 = 0
        try:
            for j in range(0, 5):
                temp = self.__ntc.read()
                if self.debug:
                    print(temp)
                somV0 += temp
                utime.sleep_ms(20)
            gemV0 = 3.6 * float(somV0) / (5 * 4095)  # spanning over weerstand
            if self.debug:
                print(somV0)
                print(gemV0)
            ntcWeerstand = self.__weerstand * (3.3 / gemV0 - 1
                                               )  # Weerstand van de ntc
            if self.debug:
                print(ntcWeerstand)
            # weerstand omzetten naar temperatuur mbv formule van Steinhart 1/T = 1/T0 + 1/3950 * ln(R/R0) (met T in Kelvin)
            resSteinhart = 1.0 / (273.15 + 25.0) + (1 / 3950.0) * math.log(
                ntcWeerstand / self.__waardeNTC)
            temp = (1.0 / resSteinhart) - 273.15
            return (1, temp)
        except Exception as E:
            if self.debug == True:
                print("fout bij meten van ntc3950")
                print(E)
            return (-1, -1)

    def stop(self):
        try:
            del self.__ntc
            if self.debug == True:
                print("ntc3950 is gestopt")
            if Sensor.teller > 0:
                Sensor.teller -= 1
            return (0, 1)
        except Exception as E:
            print("fout bij stoppen van ntc3950")
            print(E)
            return (-1, -1)
# 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)