Beispiel #1
0
  def __init__(self, pinNr, activeLow, externalResistor=False):
    if externalResistor:
      self._pin = Pin(pinNr, Pin.IN) 
    else:
      self._pin = Pin(pinNr, Pin.IN, Pin.PULL_UP if activeLow else Pin.PULL_DOWN) 

    # number of millisec that have to pass by before a click is detected.
    self._clickTicks = 200

    # number of millisec that have to pass by before a long button press is detected.
    self._pressTicks = 1000

    self._debounceTicks = 50 # number of ticks for debounce times.
 
    # starting with state 0: waiting for button to be pressed
    self._state = 0
    self._isLongPressed = False # Keep track of long press state

    if (activeLow):
      # button connects ground to the pin when pressed.
      self._buttonReleased = 1  # notPressed
      self._buttonPressed = 0
    else:
      # button connects VCC to the pin when pressed.
      self._buttonReleased = 0
      self._buttonPressed = 1


    self._clickFunc = None
    self._doubleClickFunc = None
    self._longPressStartFunc = None
    self._longPressStopFunc = None
    self._duringLongPressFunc = None

    self._startTime = None
Beispiel #2
0
    def __init__(self, debug=False, baud=100000):
        # From datasheet
        # Bit rate – up to 12 MHz1
        # ▪ Polarity – CPOL = 1; clock transition high-to-low on the leading edge and low-to-high on the
        #   trailing edge
        # ▪ Phase – CPHA = 1; setup on the leading edge and sample on the trailing edge
        # ▪ Bit order – MSB first
        # ▪ Chip select polarity – active low
        self.spi = SPI(0)
        try:
            self.spi.init(mode=SPI.MASTER, baudrate=baud, bits=8,
                          polarity=1, phase=1, firstbit=SPI.MSB,
                          pins=('GP31', 'GP16', 'GP30')) # CLK, MOSI, MISO
        except AttributeError:
            self.spi.init(baudrate=baud, bits=8,
                          polarity=1, phase=1, firstbit=SPI.MSB,
                          pins=('GP31', 'GP16', 'GP30')) # CLK, MOSI, MISO

        # These are all active low!
        self.tc_en_bar = Pin('GP4', mode=Pin.OUT)

        self.disable()

        self.tc_busy_bar = Pin('GP5', mode=Pin.IN)
        self.tc_busy_bar.irq(trigger=Pin.IRQ_RISING) # Wake up when it changes
        self.tc_cs_bar = Pin('GP17', mode=Pin.ALT, alt=7)

        self.debug = debug
Beispiel #3
0
def isLight(dataPin):
    """ Check if it's light or dark, using a CEG013600 ambient light sensor connected to the GPIO pin named by dataPin """
    light_in = Pin(dataPin, mode=Pin.IN)
    if light_in.value() == 1:
        """ 1 means dark """
        return False
    else:
        return True
def activate(state):
    global inPin
    if(state):
        inPin = Pin(12, Pin.IN, Pin.PULL_UP)
        inPin.irq(trigger=Pin.IRQ_RISING, handler=timeUS)
    # Disables the internal pull-up, therefore preventing any further RISING_EDGE case.
    else:
        inPin = Pin(12, Pin.IN)
Beispiel #5
0
    def __init__(self, pin_1, pin_2, pwm_pin):
        self.pin_1 = Pin(pin_1, mode=Pin.OUT, pull=None)
        self.pin_1.value(0)

        self.pin_2 = Pin(pin_2, mode=Pin.OUT, pull=None)
        self.pin_1.value(0)

        self.pwm = TB6612FNG_channel._pwm.channel(self.id(), pin=pwm_pin, duty_cycle=1)
        self.pwm.duty_cycle(0)
Beispiel #6
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
	def __init__(self, latch, clock, data):
		self._latch = latch
		self._clock = clock
		self._data = data
		self._latchPin = Pin(latch, mode=Pin.OUT)
		self._latchPin.value(0)
		self._clockPin = Pin(clock, mode=Pin.OUT)
		self._clockPin.value(1)
		self._dataPin = Pin(data, mode=Pin.OUT)
		self._dataPin.value(0)
Beispiel #8
0
class TB6612FNG(object):

    def __init__(self, a_1, a_2, a_pwm, b_1, b_2, b_pwm, standby_pin):
        self._standby = Pin(standby_pin, mode=Pin.OUT, pull=None)
        self._standby.value(1)
        self.channelA = _TB6612FNG_channel(a_1, a_2, a_pwm)
        self.channelB = _TB6612FNG_channel(b_1, b_2, b_pwm)

    def standby(self, *args):
        return self._standby.value(*args)
Beispiel #9
0
    def __init__(self):
        #        OUTPUT/INPUT
        self.pins = ['GP16', 'GP13']
        self.outputPin = Pin(self.pins[0], mode=Pin.OUT, value=1)
        self.inputPin = Pin(self.pins[1], mode=Pin.IN, pull=Pin.PULL_UP)

        self.triggerCount = 0
        self._triggerType_ = Pin.IRQ_RISING
        self.inputIRQ = self.inputPin.irq(trigger=self._triggerType_, handler=self.pinHandler)
        self.irqState = True
def test():
    stx = Pin(Pin.board.Y5, Pin.OUT_PP)         # Define pins
    sckout = Pin(Pin.board.Y6, Pin.OUT_PP)
    sckout.value(0) # Don't assert clock until data is set
    srx = Pin(Pin.board.Y7, Pin.IN)
    sckin = Pin(Pin.board.Y8, Pin.IN)

    objsched = Sched(heartbeat = 1)
    with SynCom(objsched, False, sckin, sckout, srx, stx) as channel:
        objsched.add_thread(initiator_thread(channel))
        objsched.run()
Beispiel #11
0
class Relay:

    def __init__(self, pin, initialValue=0):
        self.controlPin = Pin(pin, Pin.OUT)
        self.Open()
        pass
    
    def Open(self):
        self.controlPin.value(0)
        
    def Close(self):
        self.controlPin.value(1)
Beispiel #12
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()
def main(use_stream=False):
	s = socket.socket()

	# Binding to all interfaces - server will be accessible to other hosts!
	ai = socket.getaddrinfo("0.0.0.0", 8080)
	print("Bind address info:", ai)
	addr = ai[0][-1]

	#prepping LED pin
	p = Pin(2,Pin.OUT)
#	p.high()
#	time.sleep(1)
#	p.low()


	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind(addr)
	s.listen(5)
	print("Listening, connect your browser to http://<this_host>:8080/")

	counter = 0
	while True:
		res = s.accept()
		client_s = res[0]
		client_addr = res[1]
		print("Client address:", client_addr)
		print("Client socket:", client_s)
		print("Request:")
		if use_stream:
			# MicroPython socket objects support stream (aka file) interface
			# directly.
			#print(client_s.read(4096))
			val = client_s.read(4096)
			print(val)
			client_s.write(CONTENT % counter)
		else:
			#print(client_s.recv(4096))
			val = client_s.recv(4096)
			print(val)
			client_s.send(CONTENT % counter)
		if "GET /toggle" in val:
			print("Toggling!")
			p.high()
			time.sleep(1)
			p.low()
			machine.reset()
		client_s.close()
		counter += 1
		print()
Beispiel #14
0
class LaserBeam:
    def __init__(self, laser_pinname, photodiode_pinname):
        self.laser = Pin(laser_pinname, Pin.OUT_OD)
        self.photodiode = ADC(photodiode_pinname)
        self.threshold = 100

    def ping(self):
        dark = self.photodiode.read()
        self.laser.value(0)          # pull down to on
        light = self.photodiode.read()
        self.laser.value(1)          # float to off
        return light-dark

    def interrupted(self):
        return self.ping() < self.threshold \
            and sum(self.ping() for i in range(10)) < 10 * self.threshold
	def __init__(self, triggerGPIO, echoGPIO):
		self.triggerPin = Pin(triggerGPIO, mode = Pin.OUT)
		self.echoPin = Pin(echoGPIO, mode = Pin.IN)
		# The var to know if we have 28 or 028 in the decimal part
		self.mm_decimal = ""
		# Distance initated to -1 while nothing
		self.mm = -1
		self.cm = -1
Beispiel #16
0
    def __init__(self,name,config,callback):
       # mode = config.get('MODE', 'OUTPUT')
        port = config.get('PORT', 1)
        self._name = name
        self._callback = callback
        print('GPIO-output',port,config,name,callback)

        self._gpio = Pin(port, Pin.OUT)
Beispiel #17
0
class Sonar:
 def __init__(self,trig,echo):
  self.trig=Pin(trig,Pin.OUT)
  self.echo=Pin(echo,Pin.IN)
 def checkdist(self):
  self.trig.value(0)
  self.echo.value(0)
  self.trig.value(1)
  time.sleep_us(10)
  self.trig.value(0)
  while(self.echo.value()==0):
   pass
  t1=time.ticks_us()
  while(self.echo.value()==1):
   pass
  t2=time.ticks_us()
  return round(time.ticks_diff(t2,t1)/10000*340/2,2)
Beispiel #18
0
  def __init__(self, spd=1000000):
    # first assign CLK, MISO, MOSI, CS to the correct pins
    self.pin_clk = Pin(self.CLK, mode=Pin.OUT)    # CLK
    self.pin_miso = Pin(self.MISO)    # MISO
    self.pin_mosi = Pin(self.MOSI, mode=Pin.OUT)    # MOSI
    self.pin_cs = Pin(self.CS, mode=Pin.OUT)    # NSS/CS
    self.pin_reset = Pin(self.RESET, mode=Pin.OUT)

    self.pin_reset.value(0)
    self.pin_cs.value(1)

    self.spi = SPI(0)
    self.spi.init(mode=SPI.MASTER, baudrate=spd, pins=(self.CLK, self.MOSI, self.MISO))
    
    self.pin_reset.value(1)

    self.MFRC522_Init()
Beispiel #19
0
class Button:
    def __init__(self, pin):
        from machine import Pin
        self.pin = Pin(pin, Pin.IN)

    def get_presses(self, delay = 1):
        last_time, last_state, presses = time.time(), 0, 0
        while time.time() < last_time + delay:
            time.sleep_ms(50)
            if last_state == 0 and self.pin.value() == 1:
                last_state = 1
            if last_state == 1 and self.pin.value() == 0:
                last_state, presses = 0, presses + 1
        return presses

    def is_pressed(self):
        return self.pin.value() == 0

    def was_pressed(self):
        last_state = self.pin.value()
        time.sleep_ms(15)
        if last_state == 1 and self.pin.value() == 0:
            return True
        return False

    def irq(self, handler, trigger):
        self.pin.irq(handler = handler, trigger = trigger)
class DistanceSensor:
	def __init__(self, triggerGPIO, echoGPIO):
		self.triggerPin = Pin(triggerGPIO, mode = Pin.OUT)
		self.echoPin = Pin(echoGPIO, mode = Pin.IN)
		# The var to know if we have 28 or 028 in the decimal part
		self.mm_decimal = ""
		# Distance initated to -1 while nothing
		self.mm = -1
		self.cm = -1

	def isDistanceCalculated(self):
		return self.mm != -1 & self.cm != -1

	def setTriggerPinValue(self, value):
		self.triggerPin.value(value)

	def getDistanceString(self):
		return str(self.cm) + "," + self.mm_decimal + str(self.mm) + "cm"
	def changingEdge(self, pin):
		global callback

		# Get the flag which enabled to IRQ
		flags = callback.flags()
		# If rising, start count the time
		if flags & Pin.IRQ_RISING:
			self.raising_time = time.ticks_us()
		# If falling edge, then stop counting the time and calculate the distance
		elif flags & Pin.IRQ_FALLING:
			self.falling_time = time.ticks_us()
			# Get the ellapsed time between RISING and FALLING
			delay = time.ticks_diff(self.raising_time, self.falling_time)
			# We use 17 instead of 0,017
			distance = delay * 17
			# We rescale the distance in cm by separating cm and mm
			self.cm = distance // 1000
			self.mm = distance % 1000
		
			#in case we have a distance like 49028
			# cm = 49
			# mm = 028 but the 0 would be discared so we check it
			if distance % 100 == distance % 1000:
				self.mm_decimal = "0"
Beispiel #21
0
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pages = self.height // 8
        self.buffer = bytearray(self.pages * self.width)
        self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB)

        self.spi = SPI(0)
        # chip select
        self.cs = Pin("P16", mode=Pin.OUT, pull=Pin.PULL_UP)
        # command
        self.dc = Pin("P17", mode=Pin.OUT, pull=Pin.PULL_UP)
        
        # initialize all pins high
        self.cs.high()
        self.dc.high()

        self.spi.init(baudrate=8000000, phase=0, polarity=0)

        self.init_display()
Beispiel #22
0
class PulseCounter:
    def __init__(self, pin, value=0):     # value is in cents
        self.pin = Pin(pin, mode=Pin.IN)
        self.value = value
        self.count = 0
        self.total = 0
        self.int = self.pin.irq(handler=self._count, trigger=Pin.IRQ_FALLING, priority=7)

    def _count(self, pin):
        self.count += 1
        self.total += self.value
Beispiel #23
0
class Ultrasonic(object):
    def __init__(self, trigger_pin, echo_pin, timeout_us=30000):
        # WARNING: Don't use PA4-X5 or PA5-X6 as echo pin without a 1k resistor

        # Default timeout is a bit more than the HC-SR04 max distance (400 cm):
        # 400 cm * 29 us/cm (speed of sound ~340 m/s) * 2 (round-trip)

        self.timeout = timeout_us

        # Init trigger pin (out)
        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
        self.trigger.off()

        # Init echo pin (in)
        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)

    def distance_in_inches(self):
        return (self.distance_in_cm() * 0.3937)

    def distance_in_cm(self):
        # Send a 10us pulse
        self.trigger.on()
        sleep_us(10)
        self.trigger.off()

        # Wait for the pulse and calc its duration
        time_pulse = time_pulse_us(self.echo, 1, self.timeout)

        if time_pulse < 0:
            raise MeasurementTimeout(self.timeout)

        # Divide the duration of the pulse by 2 (round-trip) and then divide it
        # by 29 us/cm (speed of sound = ~340 m/s)
        return (time_pulse / 2) / 29
Beispiel #24
0
	def __init__(self, sck, mosi, miso, rst, cs):

		self.sck = Pin(sck, Pin.OUT)
		self.mosi = Pin(mosi, Pin.OUT)
		self.miso = Pin(miso)
		self.rst = Pin(rst, Pin.OUT)
		self.cs = Pin(cs, Pin.OUT)

		self.rst.value(0)
		self.cs.value(1)

		if uname()[0] == 'WiPy':
			self.spi = SPI(0)
			self.spi.init(SPI.MASTER, baudrate=1000000, pins=(self.sck, self.mosi, self.miso))
		elif uname()[0] == 'esp8266':
			self.spi = SPI(baudrate=100000, polarity=0, phase=0, sck=self.sck, mosi=self.mosi, miso=self.miso)
			self.spi.init()
		else:
			raise RuntimeError("Unsupported platform")

		self.rst.value(1)
		self.init()
Beispiel #25
0
class PulseCounter:
    def __init__(self, pin, pull, trigger, debounce_ms):
        self._pin = Pin(pin, mode=Pin.IN, pull=pull)
        self._debounce_ms = debounce_ms
        self._last_count_ms = time.ticks_ms()
        self._irq = self._pin.irq(trigger=trigger, handler=self._handler)
        self.counter = 0

    def _handler(self, pin):
        time_ms = time.ticks_ms()
        if (time_ms - self._last_count_ms > self._debounce_ms):
            self.counter += 1
            self._last_count_ms = time_ms
Beispiel #26
0
class Trigger_Monitor(object):
    '''
    Is there a way to change the callback?
    '''
    def __init__(self):
        #        OUTPUT/INPUT
        self.pins = ['GP16', 'GP13']
        self.outputPin = Pin(self.pins[0], mode=Pin.OUT, value=1)
        self.inputPin = Pin(self.pins[1], mode=Pin.IN, pull=Pin.PULL_UP)

        self.triggerCount = 0
        self._triggerType_ = Pin.IRQ_RISING
        self.inputIRQ = self.inputPin.irq(trigger=self._triggerType_, handler=self.pinHandler)
        self.irqState = True

    def toggleInput(self, time_ms = 5):
        self.outputPin.toggle()
        time.sleep_ms(time_ms)

    def pinHandler(self, pin_o):
        # global self.pin_irq_count_trigger
        # global self.pin_irq_count_total
        # self._triggerType_
        # if self._triggerType_ & self.inputIRQ.flags():
        #     self.pin_irq_count_trigger += 1
        self.triggerCount += 1 

    def getTriggerCount(self):
        print("Trigger Count: ", self.triggerCount)

    def resetTriggerCount(self):
        self.triggerCount = 0

    def disableIRQ(self):
        self.irqState = machine.disable_irq() # Start of critical section

    def reEnableIRQ(self):
        machine.enable_irq(True)
        self.irqState=True
Beispiel #27
0
class Button:
    def __init__(self, id):
        self.pressed = False
        self.btn = Pin(id, mode=Pin.IN, pull=Pin.PULL_UP)

    def on(self):
        self.btn.callback(Pin.IRQ_FALLING | Pin.IRQ_RISING,
                          self._handler)
    def off(self):
        self.btn.callback(Pin.IRQ_FALLING | Pin.IRQ_RISING,
                          None)

    def _handler(self, pin):
        value = pin.value()
        if not value and not self.pressed:
            print('Button pushed')
            self.pressed = True
        elif value and self.pressed:
            print('Button released')
            self.pressed = False
        else:
            pass
    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):
        """
        trigger_pin: Output pin to send pulses
        echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor
        echo_timeout_us: Timeout in microseconds to listen to echo pin. 
        By default is based in sensor limit range (4m)
        """
        self.echo_timeout_us = echo_timeout_us
        # Init trigger pin (out)
        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
        self.trigger.value(0)

        # Init echo pin (in)
        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)
Beispiel #29
0
    def __init__(self, trigger_pin, echo_pin, timeout_us=30000):
        # WARNING: Don't use PA4-X5 or PA5-X6 as echo pin without a 1k resistor

        # Default timeout is a bit more than the HC-SR04 max distance (400 cm):
        # 400 cm * 29 us/cm (speed of sound ~340 m/s) * 2 (round-trip)

        self.timeout = timeout_us

        # Init trigger pin (out)
        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
        self.trigger.off()

        # Init echo pin (in)
        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)
Beispiel #30
0
    def __init__(self, dout, pd_sck, gain=128):

        self.pSCK = Pin(pd_sck , mode=Pin.OUT)
        self.pOUT = Pin(dout, mode=Pin.IN, pull=Pin.PULL_DOWN)
        self.pSCK.value(False)

        self.GAIN = 0
        self.OFFSET = 0
        self.SCALE = 1
        
        self.time_constant = 0.1
        self.filtered = 0

        self.set_gain(gain)
Beispiel #31
0
def setupOled():
    global oled
    i2c = I2C(BUS, sda=Pin(SDA), scl=Pin(SCL), freq=400000)
    oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
    oled.fill(0)
Beispiel #32
0
from iot_workshop.src.ili934xhax import ILI9341, color565n
from machine import SPI, Pin
import mcp
import bme280_int

spi = SPI(
    2,
    baudrate=40000000,
    miso=Pin(19),
    mosi=Pin(23),
    sck=Pin(18))
display = ILI9341(spi,
    cs=Pin(0),
    dc=Pin(15),
    rst=Pin(5))

I2C_SCL = 27
I2C_SDA = 32

BUTTON_LEFT = 5
BUTTON_RIGHT = 6
BUTTON_UP = 7
BUTTON_DOWN = 4

PIN_LEFT = 9 #gucci
PIN_RIGHT = 10 #gucci
PIN_UP = 8 #gucci
PIN_DOWN = 11 #gucci

pinz = [PIN_LEFT, PIN_RIGHT, PIN_UP, PIN_DOWN, BUTTON_LEFT, BUTTON_RIGHT, BUTTON_UP, BUTTON_DOWN]
import dht
from machine import Pin
from time import sleep

led_blue = Pin(2, Pin.OUT)
led_red = Pin(16, Pin.OUT)
sensor = dht.DHT11(Pin(4))


def toggle_leds():
    led_blue.value(0)
    led_red.value(0)
    sleep(1)
    led_blue.value(1)
    led_red.value(1)
    sleep(1)


def toggle_leds_on():
    led_blue.value(0)
    led_red.value(0)


def toggle_leds_off():
    led_blue.value(1)
    led_red.value(1)


def read_sensor():
    sensor.measure()
    return sensor.temperature(), sensor.humidity()
 def __init__(self, pin_led):
     self.pin_led = PWM(Pin(pin_led))
     self.set_intensidad(0)
Beispiel #35
0
api_key = 'REPLACE_WITH_YOUR_WEBHOOKS_IFTTT_API_KEY'

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())

# ESP32 - Pin assignment
i2c = I2C(1, scl=Pin(22), sda=Pin(21), freq=10000)
# ESP8266 - Pin assignment
#i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=10000)

try:
  bme = BME280.BME280(i2c=i2c)
  temp = bme.temperature
  hum = bme.humidity
  pres = bme.pressure

  # uncomment for temperature in Fahrenheit
  #temp = (bme.read_temperature()/100) * (9/5) + 32
  #temp = str(round(temp, 2)) + 'F'

  sensor_readings = {'value1':temp, 'value2':hum, 'value3':pres}
  print(sensor_readings)
Beispiel #36
0
  import socket

from machine import Pin, I2C
import network
import ssd1306

import esp
esp.osdebug(None)

import gc
gc.collect()

ssid = 'makerspace'
password = '******'

i2c = I2C(scl=Pin(12), sda=Pin(14))
station = network.WLAN(network.STA_IF)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
oled.text('Connecting to:', 0, 0)
oled.text(ssid, 0, 8)
oled.show()

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

oled.text("Connected!", 0, 16)
ip = str(station.ifconfig())
x = ip.find("'", 2)
Beispiel #37
0
    'miso': 19,
    'mosi': 27,
    'ss': 18,
    'sck': 5,
    'dio_0': 26,
    'reset': 14,
    'led': 2,
}
compt = 0

device_spi = SPI(baudrate=10000000,
                 polarity=0,
                 phase=0,
                 bits=8,
                 firstbit=SPI.MSB,
                 sck=Pin(device_config['sck'], Pin.OUT, Pin.PULL_DOWN),
                 mosi=Pin(device_config['mosi'], Pin.OUT, Pin.PULL_UP),
                 miso=Pin(device_config['miso'], Pin.IN, Pin.PULL_UP))

lora = SX127x(device_spi, pins=device_config)
display = Display()


def synchro_us(temps_cycle):
    global compt, top, somme
    if compt == 0:
        top = ticks_us()
        somme = 0
    tip = ticks_us()
    delta = tip - top
    compt = compt + 1
Beispiel #38
0
from machine import Pin, ADC
import time

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

while True:
    print(pot.read())
    time.sleep_ms(200)
import time
import machine
import ugfx
from machine import Pin
from machine import ADC

# init ugfx
ugfx.init()
ugfx.clear(ugfx.BLACK)

# Set LED pin for output
sharpLEDPin = Pin(32, Pin.OUT)
sharpVoPin = ADC(Pin(36))

# ADC Setup
sharpVoPin.atten(ADC.ATTN_11DB)

# Output volate at no dust in V
Voc = 0.6  # 0.1 to 1.1

# Sensitivity in units of V per 100ug/m3.
K = 0.5  # 0.425 to 0.575

# Average
Vos = 0.8
idx = 0


def readValue():
    global Voc, Vos, idx
from machine import I2C
from machine import Pin 
from ssd1306 import SSD1306_I2C
import machine
from writer import Writer
import time
import dseg_18
import rsu_text_font_14 as dseg_12 
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
scl = Pin(22)
sda = Pin(21) 
i2c = I2C(scl=scl, sda=sda, freq=450000)
oled = SSD1306_I2C(128, 64, i2c)
dseg18 = Writer(oled, dseg_18)
dseg12 = Writer(oled, dseg_12)
rtc = machine.RTC()
rtc.ntp_sync(server="pool.ntp.org")
time.sleep(2)
while not rtc.synced():
  machine.idle()
while True:
  _tm = time.localtime()
  print(_tm)
  oled.fill(0)
  dseg12.set_textpos(5,40)
  dseg12.printstring('{0:02d}/{1:02d}/{2} {3}'.format(_tm[2], _tm[1], _tm[0], days[_tm[6]]))
  dseg18.set_textpos(30,20)
  dseg18.printstring('{0:02d}:{1:02d}:{2:02d}'.format(_tm[3] + 6, _tm[4], _tm[5])) 
  oled.show()
  time.sleep(1)
Beispiel #41
0
# Neopixel definitions and functions

from machine import Pin
from neopixel import NeoPixel


class Pixels:

    def __init__(self, io)

    pin = Pin(io, Pin.OUT) # Set GPIO16 to output to drive NeoPixels
    np = NeoPixel(pin, 9) # Create NeoPixel driver on GPIO16 for 9 pixels
    n = np.n

    ## Examples
    #np[0] = (255, 255, 255) # Set the first pixel to white
    #np.write()
    #r, g, b = np[0]

    @staticmethod
    # Custom Animations

    def pixset(pixel, r, g, b):
        np[pixel] = (r, g, b)
        np.write()

    def clear():
        # clear
        for i in range(n):
            np[i] = (0, 0, 0)
        np.write()
Beispiel #42
0
from machine import Pin
import time

open_led = True
io0 = Pin(0, Pin.OUT)
io2 = Pin(2, Pin.OUT)

io2.off()
time.sleep(1)
io2.on()
time.sleep(1)
io2.off()
time.sleep(1)
io2.on()
time.sleep(1)
while True:
    if (open_led):
        io0.on()
        io2.on()
        open_led = False
    else:
        io0.off()
        io2.off()
        open_led = True
    time.sleep(30)
Beispiel #43
0
from machine import Pin
from time import sleep

led = Pin(25, Pin.OUT)
for i in range(14):
    if i % 2 == 0:
        led.on()
    else:
        led.off()
    sleep(1)    
from machine import Pin, PWM
import time
import os
import json

with open('tonesDict.json', 'r') as tonesDict:
	tones = json.loads(tonesDict.read())

# set up pin PWM timer for output to buzzer or speaker
pwm = PWM(Pin(0)) #D3 on Wemos D1 mini

def playNotes(Val):
	msg = None
	try:
		for i,v in enumerate(Val.split(",")):
			note = tones[v.strip()]
			pwm.duty(512)
			if note == 0:
				pwm.duty(0)
			else:
				pwm.freq(int((note/100)*20)) # change frequency for change tone
				#Taking only 20% of freq as D1 mini (ESP12-E) accepts a maximum of 1 KHz
			time.sleep_ms(150)
		msg = "Done playing"
	except:
		msg = "Something is not right"
	return msg

def startPlay(fileName):
	print("File name receive:", fileName)
	with open(fileName,"r") as tune:
Beispiel #45
0
start_measure = True


def irq_callback(pin, event=None):
    global start_measure
    is_falling = event & Pin.IRQ_FALLING
    if pin == u2if.GP13 and is_falling:
        print("Range: {0}mm".format(vl53.read_measure()))
        start_measure = mode_auto
    elif pin == u2if.GP9 and is_falling:
        start_measure = True


# Initialize I2C bus and sensor. Use first I2C port.
i2c = I2C(i2c_index=0, frequency=400000)  # , pullup=True
int_pin = Pin(u2if.GP13, Pin.IN)
int_pin.irq(handler=irq_callback, trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING)
button_pin = Pin(u2if.GP9, Pin.IN)
button_pin.irq(handler=irq_callback, trigger=Pin.IRQ_FALLING, debounce=True)
vl53 = adafruit_vl53l0x.VL53L0X(i2c)

# Optionally adjust the measurement timing budget to change speed and accuracy.
# See the example here for more details:
#   https://github.com/pololu/vl53l0x-arduino/blob/master/examples/Single/Single.ino
# For example a higher speed but less accurate timing budget of 20ms:
# vl53.measurement_timing_budget = 20000
# Or a slower but more accurate timing budget of 200ms:
# vl53.measurement_timing_budget = 200000
# The default timing budget is 33ms, a good compromise of speed and accuracy.

vl53.measurement_timing_budget = 100000
from machine import Pin, Signal

# ESP12 module as used by many boards
# Blue LED on pin 2, active low (inverted)
LED = Signal(Pin(2, Pin.OUT), inverted=True)
Beispiel #47
0
from machine import Pin, ADC, SPI
import st7789py

button_A = Pin(39, Pin.IN)
button_B = Pin(2, Pin.IN, Pin.PULL_UP)
button_JA = Pin(5, Pin.IN, Pin.PULL_UP)
button_JB = Pin(12, Pin.IN, Pin.PULL_UP)

led = Pin(4, Pin.OUT)
led_state = False

spi = SPI(
   1,
   baudrate=40000000,
   polarity=1,
   phase=0,
   sck=Pin(14),
   mosi=Pin(13),
   miso=Pin(12)
)

dc    = Pin(16, Pin.OUT)
reset = Pin(17, Pin.OUT)

display = st7789py.ST7789(spi, 240, 240, reset=reset, dc=dc)

print("SPI TFT display init")
display.init()

while True:
    # TODO: GPIO pins 34-39 do not have a pull-up resistor :(
class HomeAutomation:
    def __init__(self, ledpin: int, lightpin: int, ssid: str, password: str,
                 host: str, port: int, topic: str):
        """

        :param ledpin:
        :param lightpin:
        :param ssid:
        :param password:
        :param host:
        :param port:
        :param topic:
        """
        self.ledpin = Pin(ledpin, Pin.OUT)
        self.lightpin = Pin(lightpin, Pin.OUT)
        self.ssid = ssid
        self.password = password
        self.host = host
        self.port = port
        self.topic = topic

    def boardTest(self):
        """
        Testing the board by blinking LED
        :return:
        """
        print("INFO: Blinking LED")
        for i in range(0, 5, 1):
            self.ledpin.value(not self.ledpin.value())
            sleep(1)
            i = i + 1
        print("INFO: Board is fine")

    def turn_on(self):
        """
        Turns on the lights
        :return:
        """
        self.lightpin.value(1)
        print("INFO: Turning on lights")

    def turn_off(self):
        """
        Turns off the lights
        :return:
        """
        self.lightpin.value(0)
        print("INFO: Turning off lights")

    def wifiConnect(self):
        """
        Connects to the config wifi
        :return:
        """
        print("INFO: Connecting to wifi")
        station = network.WLAN(network.STA_IF)  # create station interface
        station.active(True)  # activate the interface
        if station.isconnected():
            print("INFO: Connected to wifi initially")
        else:
            while True:
                try:
                    scanned_wifi = station.scan()  # scan for access points
                    for i in scanned_wifi:
                        if i[0].decode('utf-8') == self.ssid:
                            # Connect to wifi
                            station.connect(self.ssid, self.password)
                            print("INFO: Connected to wifi")
                            break
                        else:
                            print("INFO: Wifi Not found")
                            self.wifiConnect()
                    break
                except OSError as e:
                    print("Error: ", e)

    def on_message(self, topic, msg):
        """
        This callback is used to process messages
        that are published to a subscribed topic.
        :param topic:
        :param msg:
        :return:
        """
        message = msg.decode("utf-8")
        if message == "ON":
            self.turn_on()
        elif message == "OFF":
            self.turn_off()

    def main(self):
        """
        Main function runs the board test, connects to wifi and mqtt server
        and finally waits for oncoming messages
        :return:
        """
        self.boardTest()
        self.wifiConnect()
        print("INFO: Connecting to MQTT")
        client = MQTTClient("umqtt_client", self.host, self.port)
        client.set_callback(self.on_message)
        client.connect()
        print("INFO: Connected to MQTT")
        client.subscribe(self.topic)
        while True:
            client.wait_msg()
Beispiel #49
0
from time import sleep
from machine import Pin
led = Pin(16, Pin.OUT)
for _ in range(10):

    led.value(0)
    sleep(1)
    led.value(1)
    sleep(1)
Beispiel #50
0
from machine import Pin
from machine import I2C
from ads1219 import ADS1219
import utime

# This example demonstrates how to use the ADS1219 using single-shot conversion mode
# The ADC1219 will initiate a conversion when adc.read_data() is called

i2c = I2C(scl=Pin(26), sda=Pin(27))
adc = ADS1219(i2c)

adc.set_channel(ADS1219.CHANNEL_AIN0)
adc.set_conversion_mode(ADS1219.CM_SINGLE)
adc.set_gain(ADS1219.GAIN_1X)
adc.set_data_rate(ADS1219.DR_20_SPS)  # 20 SPS is the most accurate
adc.set_vref(ADS1219.VREF_INTERNAL)

while True:
    result = adc.read_data()
    print('result = {}, mV = {:.2f}'.format(
        result,
        result * ADS1219.VREF_INTERNAL_MV / ADS1219.POSITIVE_CODE_RANGE))
    utime.sleep(0.5)
Beispiel #51
0
# -*- coding: utf-8 -*-

"""
   程式說明請參閱4-17頁
"""

from machine import Pin

toggle = 1

led = Pin(2, Pin.OUT)
sw = Pin(0, Pin.IN)

while True:
    if sw.value() == 0 :
        toggle = not toggle
        led.value(toggle)
Beispiel #52
0
Installation:
ampy -p /dev/ttyUSB0 put ./octopus_robot_board.py
ampy -p /dev/ttyUSB0 mkdir lib
ampy -p /dev/ttyUSB0 put ./lib/ssd1306.py lib/ssd1306.py
ampy -p /dev/ttyUSB0 put ./05-oled-analog.py main.py
# reset device

"""
import machine
from machine import Pin
import time
from lib import ssd1306

import octopus_robot_board as o  #octopusLab main library - "o" < octopus

pin_an = Pin(o.PIN_ANALOG, Pin.IN)
adc = machine.ADC(pin_an)

i2c = machine.I2C(-1, machine.Pin(o.I2C_SCL_PIN), machine.Pin(o.I2C_SDA_PIN))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)

# test_whole display
oled.fill(1)
oled.show()

time.sleep_ms(300)

# reset display
oled.fill(0)
oled.show()
Beispiel #53
0
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
from machine import I2C, Pin
import time
from wiichuck import WiiChuck

i2c = I2C(sda=Pin(2), scl=Pin(4))
wii = WiiChuck(i2c)  # default address=0x58

dir_time = time.time()
count_time = time.time()
while True:
    if time.time() - dir_time > 0.5:
        # Detect direction from boolean property
        direction = ''
        if wii.joy_up:
            direction = 'Up'
        elif wii.joy_down:
            direction = 'Down'
        elif wii.joy_right:
            direction = '>>>'
        elif wii.joy_left:
import utime
from machine import I2C, Pin
from mpu9250 import MPU9250
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=200000)
sensor = MPU9250(i2c)
print("MPU9250 id: " + hex(sensor.whoami))
while True:
    print('acceleration:', str(sensor.acceleration))
    print('gyro:', str(sensor.gyro))
    print('magnetic:', str(sensor.magnetic))
Beispiel #55
0
import ili9342c
color565 = ili9342c.color565
from machine import Pin, SPI
spi = SPI(miso=Pin(19), mosi=Pin(23, Pin.OUT), sck=Pin(18, Pin.OUT))
display = ili9342c.ILI934X(spi,
                           cs=Pin(14),
                           dc=Pin(27),
                           rst=Pin(33),
                           bl=Pin(32))
display.fill(color565(0x00, 0x00, 0x00))

display.fill_rectangle(150, 150, 40, 10, color565(0x00, 0xff, 0x00))
display.fill_rectangle(10, 10, 20, 60, color565(0x00, 0x00, 0xff))
display.fill_rectangle(200, 70, 50, 50, color565(0xff, 0x00, 0x00))
display.text('Hello,World!', 16, 128)
display.scroll(8)
display.scroll(8)

import sys
del sys.modules['ili9342c']
del sys
Beispiel #56
0
# Create Led Strip in D3,300 leds....yellow dot 0 to 299...
from machine import Pin
from neopixel import NeoPixel
import time


def blink_pixel(r, g, b, p):
    np[p] = (r, g, b)
    np.write()
    np[p] = (0, 0, 0)
    np.write()


pin = Pin(14,
          Pin.OUT)  # set GPIO0 or D3 in NodeMCU to output to drive NeoPixels
np = NeoPixel(pin, 64)  # create NeoPixel driver on GPIO0 for 300 pixels
while True:
    for i in range(63):
        blink_pixel(50, 50, 0, i)
    for i in range(64):
        blink_pixel(50, 50, 0, 63 - i)
Beispiel #57
0
# 
# Copyright (c) 2006-2019, RT-Thread Development Team
# 
# SPDX-License-Identifier: MIT License
# 
# Change Logs:
# Date           Author       Notes
# 2019-06-13     SummerGift   first version
#

from machine import Pin

PIN_LED_R   = 38
PIN_KEY0    = 57
KEY_PRESSED = 0

# create led object from pin PIN_LED_R, Set pin PIN_LED_R to output mode
led = Pin(("led_red", PIN_LED_R), Pin.OUT_PP)
key_0 = Pin(("key_0", PIN_KEY0), Pin.IN, Pin.PULL_UP)

while True:
    if key_0.value() == KEY_PRESSED:
        led.value(0)  # Set led turn on
    else:
        led.value(1)
Beispiel #58
0
from machine import Pin
from time import sleep

button_grn = Pin(34, Pin.IN)
button_red = Pin(39, Pin.IN)
led_grn = Pin(17, Pin.OUT)
led_red = Pin(16, Pin.OUT)
green = 0
red = 0
green_total = 0
red_total = 0

while(1):
    if button_grn.value() == 1 and green == 0:
        green_total += 1
        if green_total == 10:
            break
    if button_red.value() == 1 and red == 0:
        red_total += 1
        if red_total == 10:
            break
    if button_grn.value() == button_red.value():
        led_grn.value(0)
        led_red.value(0)
    else:            
        led_grn.value(button_grn.value())
        led_red.value(button_red.value())
    green = button_grn.value()
    red = button_red.value()
    sleep(0.05)
    
Beispiel #59
0
from machine import Pin

import socket
import json
import http
import url
import gc

# Connect variable 'led' to the user led on the expansion board
led = Pin(Pin.exp_board.G16, mode=Pin.OUT)
led(1)  # off

# Connect 'pins' to the user button on the expansion board plus one additional pin
pins = [
    Pin(i, mode=Pin.IN, pull=Pin.PULL_UP)
    for i in (Pin.exp_board.G17, Pin.exp_board.G22)
]

client = None


def pin_handler(arg):
    """ Callback for pin interrupt: send new pin value to the client.

    This implementation can only handle one client.
    """
    global client
    print("pin_handler interrupt: pin %s (%d)" % (arg.id(), arg.value()))
    if client is not None:
        try:
            client.write("event: pin_change\ndata: {\"%s\": %d}\n\n" %
Beispiel #60
0
SCR_HEIGHT = const(240)
SCR_ROT = const(2)
CENTER_Y = int(SCR_WIDTH / 2)
CENTER_X = int(SCR_HEIGHT / 2)

print(os.uname())
'''
TFT_CLK_PIN = const(10)
TFT_MOSI_PIN = const(11)
TFT_MISO_PIN = const(12)
TFT_CS_PIN = const(13)
TFT_RST_PIN = const(14)
TFT_DC_PIN = const(15)
'''
# TFT_CLK_PIN = Pin(10, Pin.OUT, Pin.PULL_UP)
TFT_CLK_PIN = Pin(10)
TFT_MOSI_PIN = Pin(11)
TFT_MISO_PIN = Pin(12)
TFT_CS_PIN = Pin(13, Pin.OUT, Pin.PULL_UP)
TFT_RST_PIN = Pin(14)
TFT_DC_PIN = Pin(15, Pin.OUT, Pin.PULL_UP)

fonts = [glcdfont, tt14, tt24, tt32]
text = 'Hello Raspberry Pi Pico/ili9341'

print(text)
print("fonts available:")
for f in fonts:
    print(f.__name__)

spi = SPI(1,