Example #1
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)
Example #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
Example #3
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)
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()
Example #5
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)
Example #6
0
def main():
    # set internal clock
    rtc = settime(timezone_offset=TIMEZONE_OFFSET)
    year, month, day, hour, minute, second, *_ = rtc.now()

    trigger = Pin('GP5', mode=Pin.OUT)
    trigger.value(0)

    # initial trigger timer
    timer = Timer(3, mode=Timer.PERIODIC, width=32)
    timer_channel = timer.channel(Timer.A | Timer.B, period=30000000)
    timer_channel.irq(handler=lambda t: trigger.toggle(), trigger=Timer.TIMEOUT)

    try:
        while True:
            leds = clock2matrix(hour=hour, minute=minute).columns

            # led matrix multiplexing
            current_trigger = trigger.value()
            while trigger.value() == current_trigger:
                for col in leds:
                    latch.value(0)
                    # write current time
                    spi.write(col)
                    # update LEDs
                    latch.value(1)

                    sleep_ms(1)

                    latch.value(0)
                    spi.write(OFF)
                    latch.value(1)

                    sleep_us(50)

            latch.value(0)
            spi.write(OFF)
            latch.value(1)

            year, month, day, hour, minute, second, *_ = rtc.now()

            # update rtc at 04:00
            if hour == 4 and minute == 0:
                rtc = settime(timezone_offset=TIMEZONE_OFFSET)
    except Exception as e:
        matrix_off()
        while True:
            print(e)
            sleep_ms(2000)
Example #7
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
Example #8
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
Example #9
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)
Example #10
0
class Buzz(object):
 def __init__(self,pin=6):
  self.id=pins_remap_esp32[pin]
  self.io=Pin(self.id)
  self.io.value(1)
  self.isOn=False
 def on(self,freq=500):
  if self.isOn is False:
   self.pwm=PWM(self.io,freq,512)
   self.isOn=True
 def off(self):
  if self.isOn:
   self.pwm.deinit()
   self.io.init(self.id,Pin.OUT)
   self.io.value(1)
   self.isOn=False
 def freq(self,freq):
  self.pwm.freq(freq)
Example #11
0
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"
Example #12
0
class output(object):
    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)

    def run(self):
        while True:

            yield

    def SET(self,value):
        if 'ON' in value:
           self._gpio.value(1)
        else:
           self._gpio.value(0)
           #self._gpio.off()
     #   print('GET METHode VALUE',value)
        return True
Example #13
0
# PIR
PIR_PIN = 13 # Signal du senseur PIR.
PIR_RETRIGGER_TIME = 15 * 60 # 15 min
# temps (sec) dernière activation PIR
last_pir_time = 0 
last_pir_msg  = "NONE"
# temps (sec) dernier envoi MSG
last_pir_msg_time = 0 
# Programme principal doit-il envoyer
# une notification "MOUV" rapidement?
fire_pir_alert = False 

# --- Demarrage conditionnel ---
runapp = Pin( 12,  Pin.IN, Pin.PULL_UP )
led = Pin( 0, Pin.OUT )
led.value( 1 ) # eteindre

def led_error( step ):
	global led
	t = time.time()
	while ( time.time()-t ) < ERROR_REBOOT_TIME:
		for i in range( 20 ):
			led.value(not(led.value()))
			time.sleep(0.100)
		led.value( 1 ) # eteindre
		time.sleep( 1 )
		# clignote nbr fois
		for i in range( step ):
			led.value( 0 ) 
			time.sleep( 0.5 )
			led.value( 1 )
Example #14
0
#############################################################
# LED blink Demo 5
# Date: 2020-04-18
#############################################################

from machine import Pin, PWM
import utime as time

LED_OFF = 1  # 1=OFF, 0=ON
LED_GPIO = 5  # use GPIO5 for LED output


def main_loop():
    while True:
        time.sleep(-1)


try:
    led = Pin(LED_GPIO, Pin.OUT)
    # create a PWM object for the specified pin
    pwm = PWM(led)
    pwm.freq(5)  # note: 1Hz is the lowest frequency
    main_loop()
except KeyboardInterrupt:
    pass
finally:
    led.value(LED_OFF)  # turn off LED
    pwm.deinit()  # turn off PWM

#############################################################
class HCSR04:
    """
    Driver to use the untrasonic sensor HC-SR04.
    The sensor range is between 2cm and 4m.

    The timeouts received listening to echo pin are converted to OSError('Out of range')

    """
    # echo_timeout_us is based in chip range limit (400cm)
    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)

    def _send_pulse_and_wait(self):
        """
        Send the pulse to trigger and listen on echo pin.
        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
        """
        self.trigger.value(0) # Stabilize the sensor
        time.sleep_us(5)
        self.trigger.value(1)
        # Send a 10us pulse.
        time.sleep_us(10)
        self.trigger.value(0)
        try:
            pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
            return pulse_time
        except OSError as ex:
            if ex.args[0] == 110: # 110 = ETIMEDOUT
                raise OSError('Out of range')
            raise ex

    def distance_mm(self):
        """
        Get the distance in milimeters without floating point operations.
        """
        pulse_time = self._send_pulse_and_wait()

        # To calculate the distance we get the pulse_time and divide it by 2 
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.34320 mm/us that is 1mm each 2.91us
        # pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582 
        mm = pulse_time * 100 // 582
        return mm

    def distance_cm(self):
        """
        Get the distance in centimeters with floating point operations.
        It returns a float
        """
        pulse_time = self._send_pulse_and_wait()

        # To calculate the distance we get the pulse_time and divide it by 2 
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.034320 cm/us that is 1cm each 29.1us
        cms = (pulse_time / 2) / 29.1
        return cms
Example #16
0
from machine import Pin
import time, network, urequests

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("Wifi 基地台", "Wifi 密碼")
while not sta_if.isconnected():
    pass
print('wifi connect')

# window D0
window = Pin(16, Pin.IN)

while True:
    print(window.value())
    if window.value() == 1:
        print('家裡遭小偷,請盡速查看')
        urequests.get("IFTTT 的 HTTP 請求網址")
        time.sleep(10)
    time.sleep(1)
Example #17
0
class EPD(object):
    MAX_READ = 45
    SW_NORMAL_PROCESSING = 0x9000
    EP_FRAMEBUFFER_SLOT_OVERRUN = 0x6a84 # too much data fed in
    EP_SW_INVALID_LE = 0x6c00 # Wrong expected length
    EP_SW_INSTRUCTION_NOT_SUPPORTED = 0x6d00 # bad instr
    EP_SW_WRONG_PARAMETERS_P1P2 = 0x6a00
    EP_SW_WRONG_LENGTH = 0x6700

    DEFAULT_SLOT=0 # always the *oldest*, should wear-level then I think

    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

    def enable(self):
        self.tc_en_bar.value(0) # Power up
        time.sleep_ms(5)
        while self.tc_busy_bar() == 0:
            machine.idle() # will it wake up here?
        # /tc_busy goes high during startup, low during init, then high when not busy

    def disable(self):
        self.tc_en_bar.value(1) # Off

    def send_command(self, ins, p1, p2, data=None, expected=None):

        # These command variables are always sent
        cmd = struct.pack('3B', ins, p1, p2)

        # Looks like data is only sent with the length (Lc)
        if data:
            assert len(data) <= 251 # Thus speaks the datasheet
            cmd += struct.pack('B', len(data))
            cmd += data

        # Expected data is either not present at all, 0 for null-terminated, or a number for fixed
        if expected is not None:
            cmd += struct.pack('B', expected)

        if self.debug:
            print("Sending: " + hexlify(cmd).decode())

        self.spi.write(cmd)

        # Wait for a little while
        time.sleep_us(15) # This should take at most 14.5us
        while self.tc_busy_bar() == 0:
            machine.idle()

        # Request a response
        if expected is not None:
            if expected > 0:
                result_bytes = self.spi.read(2 + expected)
            else:
                result_bytes = self.spi.read(EPD.MAX_READ)
                strlen = result_bytes.find(b'\x00')
                result_bytes = result_bytes[:strlen] + result_bytes[strlen+1:strlen+3]
        else:
            result_bytes = self.spi.read(2)

        if self.debug:
            print("Received: " + hexlify(result_bytes).decode())

        (result,) = struct.unpack_from('>H', result_bytes[-2:])

        if result != EPD.SW_NORMAL_PROCESSING:
            raise ValueError("Bad result code: 0x%x" % result)

        return result_bytes[:-2]

    @staticmethod
    def calculate_checksum(data, skip=16):
        """
        Initial checksum value is 0x6363

        :param data:
        :param skip: Skip some data as slices are expensive
        :return:
        """
        acc = 0x6363
        for byte in data:
            if skip > 0:
                skip -= 1
            else:
                acc ^= byte
                acc = ((acc >> 8) | (acc << 8)) & 0xffff
                acc ^= ((acc & 0xff00) << 4) & 0xffff
                acc ^= (acc >> 8) >> 4
                acc ^= (acc & 0xff00) >> 5
        return acc

    def get_sensor_data(self):
        # GetSensorData
        val = self.send_command(0xe5, 1, 0, expected=2)
        (temp,) = struct.unpack(">H", val)
        return temp

    def get_device_id(self):
        return self.send_command(0x30, 2, 1, expected=0x14)

    def get_system_info(self):
        return self.send_command(0x31, 1, 1, expected=0)

    def get_system_version_code(self):
        return self.send_command(0x31, 2, 1, expected=0x10)

    def display_update(self, slot=0, flash=True):
        cmd = 0x86
        if flash:
            cmd = 0x24
        self.send_command(cmd, 1, slot)

    def reset_data_pointer(self):
        self.send_command(0x20, 0xd, 0)

    def image_erase_frame_buffer(self, slot=0):
        self.send_command(0x20, 0xe, slot)

    def get_checksum(self, slot):
        cksum_val = self.send_command(0x2e, 1, slot, expected=2)
        (cksum,) = struct.unpack(">H", cksum_val)
        return cksum

    def upload_image_data(self, data, slot=0, delay_us=1000):
        self.send_command(0x20, 1, slot, data)
        time.sleep_us(delay_us)

    def upload_whole_image(self, img, slot=0):
        """
        Chop up chunks and send it
        :param img: Image to send in EPD format
        :param slot: Slot framebuffer number to use
        :param delay_us: Delay between packets? 450us and the Tbusy line never comes back
        :return:
        """
        total = len(img)
        idx = 0
        try:
            while idx < total - 250:
                chunk = img[idx:idx+250]
                self.upload_image_data(chunk, slot)
                del chunk
                idx += 250
            self.upload_image_data(img[idx:], slot)
        except KeyboardInterrupt:
            print("Stopped at user request at position: %d (%d)" % (idx, (idx // 250)))
        except ValueError as e:
            print("Stopped at position: %d (%d) - %s" % (idx, (idx // 250), e))
Example #18
0
 def __init__(self, spd=115200):
     RST = Pin(RST_PIN, mode=Pin.OUT)
     RST.value(0)
     uart = UART(1, baudrate=spd, pins=(TXD_PIN, RXD_PIN))
     RST.value(1)
Example #19
0
from machine import Pin, SPI

from .ili934xnew import ILI9341, color565
from . import m5stack as board
from . import glcdfont
from . import tt14
from . import tt24
from . import tt32

fonts = [glcdfont, tt14, tt24, tt32]

text = 'Now is the time for all good men to come to the aid of the party.'

power = Pin(m5stack.TFT_LED_PIN, Pin.OUT)
power.value(1)

spi = SPI(2,
          baudrate=40000000,
          miso=Pin(m5stack.TFT_MISO_PIN),
          mosi=Pin(m5stack.TFT_MOSI_PIN),
          sck=Pin(m5stack.TFT_CLK_PIN))

display = ILI9341(spi,
                  cs=Pin(m5stack.TFT_CS_PIN),
                  dc=Pin(m5stack.TFT_DC_PIN),
                  rst=Pin(m5stack.TFT_RST_PIN),
                  w=320,
                  h=240,
                  r=3)
Example #20
0
class Button():
    '''
    class Button
    '''

    flags_btn_deb = False
    flags_btn_flag = True
    flags_btn_state = False
    flags_isPress_f = False
    flags_oneClick_f = True
    flags_hold_flag = False
    btn_counter = 0
    flags_isRelease_f = False
    flags_step_flag = True
    flags_isOne_f = False
    btn_timer = time.ticks_ms()
    flags_tickMode = False
    counter_flag = True
    last_counter = 0
    flags_counter_flag = True
    timeout = 500
    flags_isHolded_f = False
    flags_hold_flag = True

    def __init__(self,
                 pin=5,
                 click_timeout=300,
                 debounce=60,
                 step_timeout=400):
        self.pin = pin
        self.debounce = debounce
        self.click_timeout = click_timeout
        self.step_timeout = step_timeout
        self.btn = Pin(pin, Pin.IN)

    def tick(self):
        # read pin
        self.flags_btn_state = self.btn.value()
        # нажатие
        if self.flags_btn_state and not self.flags_btn_flag:
            if not self.flags_btn_deb:
                self.flags_btn_deb = True
                self.btn_timer = time.ticks_ms()
            else:
                if time.ticks_ms() - self.btn_timer >= self.debounce:
                    self.flags_btn_flag = True
                    self.flags_isPress_f = True
                    self.flags_oneClick_f = True
        else:
            self.flags_btn_deb = False
# otpuskaem
        if not self.flags_btn_state and self.flags_btn_flag:
            self.flags_btn_flag = False
            if not self.flags_hold_flag:
                self.btn_counter = self.btn_counter + 1
            self.flags_hold_flag = False
            self.flags_isRelease_f = True
            self.btn_timer = time.ticks_ms()
            self.flags_step_flag = False
            if self.flags_oneClick_f:
                self.flags_oneClick_f = False
                self.flags_isOne_f = True
        # hold
        if self.flags_btn_flag and self.flags_btn_state and time.ticks_ms(
        ) - self.btn_timer >= self.timeout and not self.flags_hold_flag:
            self.flags_hold_flag = True
            self.btn_counter = 0
            self.last_counter = 0
            self.flags_isHolded_f = True
            self.flags_step_flag = True
            self.flags_oneClick_f = False
            self.btn_timer = time.ticks_ms()

        if time.ticks_ms(
        ) - self.btn_timer >= self.click_timeout and self.btn_counter > 0:
            self.last_counter = self.btn_counter
            self.btn_counter = 0
            self.flags_counter_flag = True

    def setTickMode(self, tickMode):
        self.flags_tickMode = tickMode

    def isSingle(self):
        if self.flags_tickMode:
            self.tick()
        if self.flags_counter_flag and self.last_counter == 1:
            self.flags_counter_flag = False
            return True
        else:
            return False

    def isDouble(self):
        if self.flags_tickMode:
            self.tick()
        if self.flags_counter_flag and self.last_counter == 2:
            self.flags_counter_flag = False
            return True
        else:
            return False

    def isTriple(self):
        if self.flags_tickMode:
            self.tick()
        if self.flags_counter_flag and self.last_counter == 3:
            self.flags_counter_flag = False
            return True
        else:
            return False

    def isPress(self):
        if self.flags_isPress_f:
            self.flags_isPress_f = False
            return True
        else:
            return False

    def state(self):
        if self.flags_tickMode:
            self.tick()
        return self.flags_btn_state

    def main(self):
        while True:
            self.tick()
            if self.isPress():
                print("Is pressed")
            if self.isDouble():
                print("is Double")
            if self.isSingle():
                print("is Single")
            if self.state():
                print("state True")
Example #21
0
import time
from machine import ADC, Pin
engine = Pin(16, Pin.OUT)
engine.value(0)

while True:
    engine.value(0)
    time.sleep(.1)
    engine.value(1)
    time.sleep(.1)
Example #22
0
class MFRC522:

    OK = 0
    NOTAGERR = 1
    ERR = 2

    REQIDL = 0x26
    REQALL = 0x52
    AUTHENT1A = 0x60
    AUTHENT1B = 0x61

    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()

    def _wreg(self, reg, val):

        self.cs.value(0)
        self.spi.write(b'%c' % int(0xff & ((reg << 1) & 0x7e)))
        self.spi.write(b'%c' % int(0xff & val))
        self.cs.value(1)

    def _rreg(self, reg):

        self.cs.value(0)
        self.spi.write(b'%c' % int(0xff & (((reg << 1) & 0x7e) | 0x80)))
        val = self.spi.read(1)
        self.cs.value(1)

        return val[0]

    def _sflags(self, reg, mask):
        self._wreg(reg, self._rreg(reg) | mask)

    def _cflags(self, reg, mask):
        self._wreg(reg, self._rreg(reg) & (~mask))

    def _tocard(self, cmd, send):

        recv = []
        bits = irq_en = wait_irq = n = 0
        stat = self.ERR

        if cmd == 0x0E:
            irq_en = 0x12
            wait_irq = 0x10
        elif cmd == 0x0C:
            irq_en = 0x77
            wait_irq = 0x30

        self._wreg(0x02, irq_en | 0x80)
        self._cflags(0x04, 0x80)
        self._sflags(0x0A, 0x80)
        self._wreg(0x01, 0x00)

        for c in send:
            self._wreg(0x09, c)
        self._wreg(0x01, cmd)

        if cmd == 0x0C:
            self._sflags(0x0D, 0x80)

        i = 2000
        while True:
            n = self._rreg(0x04)
            i -= 1
            if ~((i != 0) and ~(n & 0x01) and ~(n & wait_irq)):
                break

        self._cflags(0x0D, 0x80)

        if i:
            if (self._rreg(0x06) & 0x1B) == 0x00:
                stat = self.OK

                if n & irq_en & 0x01:
                    stat = self.NOTAGERR
                elif cmd == 0x0C:
                    n = self._rreg(0x0A)
                    lbits = self._rreg(0x0C) & 0x07
                    if lbits != 0:
                        bits = (n - 1) * 8 + lbits
                    else:
                        bits = n * 8

                    if n == 0:
                        n = 1
                    elif n > 16:
                        n = 16

                    for _ in range(n):
                        recv.append(self._rreg(0x09))
            else:
                stat = self.ERR

        return stat, recv, bits

    def _crc(self, data):

        self._cflags(0x05, 0x04)
        self._sflags(0x0A, 0x80)

        for c in data:
            self._wreg(0x09, c)

        self._wreg(0x01, 0x03)

        i = 0xFF
        while True:
            n = self._rreg(0x05)
            i -= 1
            if not ((i != 0) and not (n & 0x04)):
                break

        return [self._rreg(0x22), self._rreg(0x21)]

    def init(self):

        self.reset()
        self._wreg(0x2A, 0x8D)
        self._wreg(0x2B, 0x3E)
        self._wreg(0x2D, 30)
        self._wreg(0x2C, 0)
        self._wreg(0x15, 0x40)
        self._wreg(0x11, 0x3D)
        self.antenna_on()

    def reset(self):
        self._wreg(0x01, 0x0F)

    def antenna_on(self, on=True):

        if on and ~(self._rreg(0x14) & 0x03):
            self._sflags(0x14, 0x03)
        else:
            self._cflags(0x14, 0x03)

    def request(self, mode):

        self._wreg(0x0D, 0x07)
        (stat, recv, bits) = self._tocard(0x0C, [mode])

        if (stat != self.OK) | (bits != 0x10):
            stat = self.ERR

        return stat, bits

    def anticoll(self):

        ser_chk = 0
        ser = [0x93, 0x20]

        self._wreg(0x0D, 0x00)
        (stat, recv, bits) = self._tocard(0x0C, ser)

        if stat == self.OK:
            if len(recv) == 5:
                for i in range(4):
                    ser_chk = ser_chk ^ recv[i]
                if ser_chk != recv[4]:
                    stat = self.ERR
            else:
                stat = self.ERR

        return stat, recv

    def select_tag(self, ser):

        buf = [0x93, 0x70] + ser[:5]
        buf += self._crc(buf)
        (stat, recv, bits) = self._tocard(0x0C, buf)
        return self.OK if (stat == self.OK) and (bits == 0x18) else self.ERR

    def auth(self, mode, addr, sect, ser):
        return self._tocard(0x0E, [mode, addr] + sect + ser[:4])[0]

    def stop_crypto1(self):
        self._cflags(0x08, 0x08)

    def read(self, addr):

        data = [0x30, addr]
        data += self._crc(data)
        (stat, recv, _) = self._tocard(0x0C, data)
        return recv if stat == self.OK else None

    def write(self, addr, data):

        buf = [0xA0, addr]
        buf += self._crc(buf)
        (stat, recv, bits) = self._tocard(0x0C, buf)

        if not (stat == self.OK) or not (bits == 4) or not (
            (recv[0] & 0x0F) == 0x0A):
            stat = self.ERR
        else:
            buf = []
            for i in range(16):
                buf.append(data[i])
            buf += self._crc(buf)
            (stat, recv, bits) = self._tocard(0x0C, buf)
            if not (stat == self.OK) or not (bits == 4) or not (
                (recv[0] & 0x0F) == 0x0A):
                stat = self.ERR

        return stat
Example #23
0
class HX711(object):
    """
    Micropython driver for Avia Semiconductor's HX711
    24-Bit Analog-to-Digital Converter
    """
    CHANNEL_A_128 = const(1)
    CHANNEL_A_64 = const(3)
    CHANNEL_B_32 = const(2)

    DATA_BITS = const(24)
    MAX_VALUE = const(0x7fffff)
    MIN_VALUE = const(0x800000)
    READY_TIMEOUT_SEC = const(1)
    SLEEP_DELAY_USEC = const(80)

    def __init__(self, d_out, pd_sck, channel: int = CHANNEL_A_128):
        self.d_out_pin = Pin(d_out, Pin.IN)
        self.pd_sck_pin = Pin(pd_sck, Pin.OUT, value=0)
        self.channel = channel

    def __repr__(self):
        return "HX711 on channel %s, gain=%s" % self.channel

    def _convert_from_twos_complement(self, value: int) -> int:
        """
        Converts a given integer from the two's complement format.
        """
        if value & (1 << (self.DATA_BITS - 1)):
            value -= 1 << self.DATA_BITS
        return value

    def _set_channel(self):
        """
        Input and gain selection is controlled by the
        number of the input PD_SCK pulses
        3 pulses for Channel A with gain 64
        2 pulses for Channel B with gain 32
        1 pulse for Channel A with gain 128
        """
        for i in range(self._channel):
            self.pd_sck_pin.value(1)
            self.pd_sck_pin.value(0)

    def _wait(self):
        """
        If the HX711 is not ready within READY_TIMEOUT_SEC
        the DeviceIsNotReady exception will be thrown.
        """
        t0 = time()
        while not self.is_ready():
            if time() - t0 > self.READY_TIMEOUT_SEC:
                raise Exception("DeviceIsNotReady")

    @property
    def channel(self) -> tuple:
        """
        Get current input channel in a form
        of a tuple (Channel, Gain)
        """
        if self._channel == self.CHANNEL_A_128:
            return 'A', 128
        if self._channel == self.CHANNEL_A_64:
            return 'A', 64
        if self._channel == self.CHANNEL_B_32:
            return 'B', 32

    @channel.setter
    def channel(self, value):
        """
        Set input channel
        HX711.CHANNEL_A_128 - Channel A with gain 128
        HX711.CHANNEL_A_64 - Channel A with gain 64
        HX711.CHANNEL_B_32 - Channel B with gain 32
        """
        if value not in (self.CHANNEL_A_128, self.CHANNEL_A_64, self.CHANNEL_B_32):
            raise Exception('Gain should be one of HX711.CHANNEL_A_128, HX711.CHANNEL_A_64, HX711.CHANNEL_B_32')
        else:
            self._channel = value

        if not self.is_ready():
            self._wait()

        for i in range(self.DATA_BITS):
            self.pd_sck_pin.value(1)
            self.pd_sck_pin.value(0)

        self._set_channel()

    def is_ready(self) -> bool:
        """
        When output data is not ready for retrieval,
        digital output pin DOUT is high.
        """
        return self.d_out_pin.value() == 0

    def power_off(self):
        """
        When PD_SCK pin changes from low to high
        and stays at high for longer than 60 us ,
        HX711 enters power down mode.
        """
        self.pd_sck_pin.value(0)
        self.pd_sck_pin.value(1)
        sleep_us(self.SLEEP_DELAY_USEC)

    def power_on(self):
        """
        When PD_SCK returns to low, HX711 will reset
        and enter normal operation mode.
        """
        self.pd_sck_pin.value(0)
        self.channel = self._channel

    def read(self, raw=False):
        """
        Read current value for current channel with current gain.
        if raw is True, the HX711 output will not be converted
        from two's complement format.
        """
        if not self.is_ready():
            self._wait()

        raw_data = 0
        for i in range(self.DATA_BITS):
            self.pd_sck_pin.value(1)
            self.pd_sck_pin.value(0)
            raw_data = raw_data << 1 | self.d_out_pin.value()
        self._set_channel()

        if raw:
            return raw_data
        else:
            return self._convert_from_twos_complement(raw_data)
Example #24
0
 async def killer():
     #未引出的脚,测试
     pin = Pin(17, Pin.IN, Pin.PULL_UP)
     while pin.value():
         await asyncio.sleep_ms(50)
Example #25
0
  <p>GPIO state: <strong>""" + gpio_state + """</strong></p><p><a href="/?led=on"><button class="button">ON</button></a></p>
  <p><a href="/?led=off"><button class="button button2">OFF</button></a></p></body></html>"""
    return html


#socket ile dinleme yapmak için
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:
    conn, addr = s.accept(
    )  #response ve request yapılan bildirim aynı zamanda yapılan ip  bildirimi
    print('Got a connection from %s' % str(addr))  #yapılan request göster
    request = conn.recv(1024)  # request
    request = str(request)
    print('Content = %s' % request)  #request i göster
    led_on = request.find('/?led=on')  # yapılan request i dinle
    led_off = request.find('/?led=off')
    if led_on == 6:
        print('LED ON')
        led.value(1)
    if led_off == 6:
        print('LED OFF')
        led.value(0)
    response = web_page()  #wb sayfasını return et
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    conn.sendall(response)  #burada da bir return verimizi
    conn.close()  #burada socket bağlantısını kapatıyoruz
Example #26
0
class Hardware(BaseHardware):
    
    def __init__(self, config) :

        pin_a = Pin(BUTTON_A_PIN, mode=Pin.IN, pull=None)
        pin_b = Pin(BUTTON_B_PIN, mode=Pin.IN, pull=None)
        pin_c = Pin(BUTTON_C_PIN, mode=Pin.IN, pull=None)
        
        self.buttonA = Button(pin=pin_a)
        self.buttonB = Button(pin=pin_b)
        self.buttonC = Button(pin=pin_c)
        self.buttonA.press_func(self.button_A_callback, (pin_a,))  # Note how function and args are passed
        self.buttonB.press_func(self.button_B_callback, (pin_b,))  # Note how function and args are passed
        self.buttonC.press_func(self.button_C_callback, (pin_c,))  # Note how function and args are passed
 
        # display
        self.display = None
        self.screen_power = None
        self.header_font = None
        self.large_label_font = None
        self.small_label_font = None

        self.setup_screen()

        # screen saver
        # 0 - disable
        # x - screen saver activation in second
        self.screensaver = 0
        self.currentcount  = 0
        if "screensaver" in config:
            self.screensaver = int(config["screensaver"])
            self.currentcount = int(config["screensaver"])
        
        self.screen_timeout_lock = Lock()
        
        # wifi
        super().__init__(config)
    
    def get_ble_handle(self):
        return self.ble_handle
    
    def set_callback(self, button, cb):
        if button == BUTTON_A_PIN:
            self.buttonA = Button(pin=Pin(BUTTON_A_PIN, mode=Pin.IN, pull=None),  
                callback=cb, trigger=Pin.IRQ_FALLING)

    def button_A_callback(self, pin):
        print("Button (%s) changed to: %r" % (pin, pin.value()))
        if pin.value() == 0 :
            
            #device = self.device_req_handler["studyrmfan"]
            # handle the request
            topic = self.tranport_handler.topicprefix + 'cmnd/studyrmfan/press'
            self.tranport_handler.publish(topic, 'on')
            # rest the screen saver
            self.tranport_handler.loop.create_task(self.reset_screen_saver())         
            
    def button_B_callback(self, pin):
        print("Button (%s) changed to: %r" % (pin, pin.value()))
        if pin.value() == 0 :
            
            # handle the request
            topic = self.tranport_handler.topicprefix + 'cmnd/studyrmtemp/getstatus'
            self.tranport_handler.publish(topic, 'on')
            # rest the screen saver
            self.tranport_handler.loop.create_task(self.reset_screen_saver())            

    def button_C_callback(self, pin):
        print("Button (%s) changed to: %r" % (pin, pin.value()))
        if pin.value() == 0 :
            
            #device = self.device_req_handler["waterheater"]
            # handle the request
            topic = self.tranport_handler.topicprefix + 'cmnd/waterheater/press'
            self.tranport_handler.publish(topic, 'on')
            # rest the screen saver
            self.tranport_handler.loop.create_task(self.reset_screen_saver())      
    def clear_dashboard(self):
        '''
        Clear the dashboard area
        '''
        self.display.fill_rectangle(70, 80, 200, 100, color565(0,0,0))

    def setup_screen(self):
        self.screen_power = Pin(m5stack.TFT_LED_PIN, Pin.OUT)
        self.screen_power.value(1)
        spi = SPI(
            2,
            baudrate=40000000,
            miso=Pin(m5stack.TFT_MISO_PIN),
            mosi=Pin(m5stack.TFT_MOSI_PIN),
            sck=Pin(m5stack.TFT_CLK_PIN))    
        #display = Display(spi, dc=Pin(4), cs=Pin(16), rst=Pin(17))
        self.display = Display(
            spi,
            cs=Pin(m5stack.TFT_CS_PIN),
            dc=Pin(m5stack.TFT_DC_PIN),
            rst=Pin(m5stack.TFT_RST_PIN), width=320, height=240, rotation=0)
        self.display.clear()    

        self.header_font = XglcdFont('/screen/m5stack/fonts/Unispace12x24.c', 12, 24)
        self.large_label_font = XglcdFont('/screen/m5stack/fonts/IBMPlexMono12x24.c', 12, 24)
        self.small_label_font = XglcdFont('/screen/m5stack/fonts/ArcadePix9x11.c', 9, 11)
        self.display.draw_text(0, 0, 'Loading...', self.large_label_font, color565(0, 0, 0), background=color565(255, 255, 255))

    def show_setupcomplete(self):
        self.home_page()
        self.display.draw_text(70, 80, 'Waiting For', self.large_label_font, color565(255, 255, 255), background=color565(0, 0, 0))
        self.display.draw_text(70, 100, 'Messages', self.large_label_font, color565(255, 255, 255), background=color565(0, 0, 0))

        #activate the screen saver
        self.tranport_handler.loop.create_task(self.screen_saver_countdown())

    def home_page(self):
        self.display.clear()
        self.display.draw_image('/images/blecanvas.raw',0,0,320,240)
        #self.display.draw_text(45, 203, 'Fan', self.large_label_font, color565(0, 0, 0), background=color565(255, 255, 255))
        #self.display.draw_text(135, 203, 'Temp', self.large_label_font, color565(0, 0, 0), background=color565(255, 255, 255))
        #self.display.draw_text(225, 203, 'Heater', self.large_label_font, color565(0, 0, 0), background=color565(255, 255, 255))
        self.screen_power.value(1)

        

    def display_result(self, text):
        print("Display Result")
        self.clear_dashboard()
        self.display.draw_text(70, 80, text["line1"], self.large_label_font, color565(255, 255, 255))
        self.display.draw_text(70, 100, text["line2"], self.large_label_font, color565(255, 255, 255))
        self.display.draw_text(70, 120, text["line3"], self.large_label_font, color565(255, 255, 255))
    
    def screen_off(self):
        self.screen_power.value(0)
    
    def screen_on(self):
        self.screen_power.value(1)
    
    async def reset_screen_saver(self):
        '''
        Reset the screen Saver timeout to
        
        '''
        await self.screen_timeout_lock.acquire()
        self.currentcount = self.screensaver
        self.screen_timeout_lock.release()
        self.screen_on()

    
    async def screen_saver_countdown(self):
        while True:
            await self.screen_timeout_lock.acquire()
            if self.currentcount > 0: 
                self.currentcount -= 1 
            if self.currentcount == 0 :
                self.screen_off()
            self.screen_timeout_lock.release()
            await asyncio.sleep(1)
    
       
    
        
#a=Hardware()
#a.show_setupcomplete
Example #27
0
#   - Joshua Vaughan
#   - [email protected]
#   - http://www.ucs.louisiana.edu/~jev9637
#
# Modified:
#   *
#
###############################################################################

import webrepl
import time
from machine import Pin

# Create a pin object for the esp8266 onboard LED
pin = Pin(2, Pin.OUT)
pin.value(1) # Turn the LED off to start

WIFI_SSID = "WIFISSID"
WIFI_PASSWORD = "******"

# Set to true to connect to the WIFI network identified by the parameters above
# We'll leave the access point open too, for easy debugging/programming
CONNECT_AS_STATION = True

def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('Connecting to network...')
        sta_if.active(True)
        sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
Example #28
0
class ShiftRegister:
    def __init__(self, serial, oe, register_clock, serial_clock, serial_clear):
        self.serial = Pin(serial, Pin.OUT, Pin.PULL_DOWN, value=0)
        self.oe = Pin(oe, Pin.OUT, Pin.PULL_UP, value=1)
        self.register_clock = Pin(register_clock,
                                  Pin.OUT,
                                  Pin.PULL_DOWN,
                                  value=0)
        self.serial_clock = Pin(serial_clock, Pin.OUT, Pin.PULL_DOWN, value=0)
        self.serial_clear = Pin(serial_clear, Pin.OUT, Pin.PULL_UP, value=1)

    def clear(self):
        self.serial_clear.value(0)
        self.register_clock.value(1)
        self.register_clock.value(0)
        self.serial_clear.value(1)

    def enable(self):
        self.clear()
        self.oe.value(0)

    def disable(self):
        self.oe.value(1)

    def write_bits(self, bits):
        self.clear()

        self.oe.value(1)

        for bit in bits:
            self.serial.value(bit)
            self.serial_clock.value(1)
            self.serial_clock.value(0)
            self.register_clock.value(1)
            self.register_clock.value(0)

        self.oe.value(0)

    def write_int(self, integer, le=False):
        bits = [int(bit) for bit in "{:08b}".format(integer)]
        if le:
            bits = bits[::-1]
        self.write_bits(bits)
Example #29
0
class _TB6612FNG_channel(object):
    _pwm_id = 0
    _pwm = PWM(0, frequency=5000)

    @classmethod
    def id(cls):
        if cls._pwm_id > 7:
            raise Exception("Cannot create more pwm channels")

        temp = cls._pwm_id
        cls._pwm_id += 1
        return temp

    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)

    def clockwise(self):
        self.pin_1.value(1)
        self.pin_2.value(0)

    def anticlockwise(self):
        self.pin_1.value(0)
        self.pin_2.value(1)

    def short_break(self):
        self.pin_1.value(1)
        self.pin_2.value(1)

    def freewheel(self):
        self.pin_1.value(0)
        self.pin_2.value(0)

    def duty_cycle(self, *args, **kwargs):
        return self.pwm.duty_cycle(*args, **kwargs)
Example #30
0
#hardware platform: FireBeetle-ESP32
from machine import IIS
from machine import Pin
import time
recorder = IIS(IIS.RECORDER)                        #create a iis object
button = Pin(16, Pin.IN)
def mycb(path):
  print("callback : record "+path + " is done ")
recorder.init()                                     #init recorder
recorder.set_nchannels(2)                           #set channel
recorder.set_sampwidth(16)                          #set Sample width
recorder.set_framerate(16000)                       #set framerate
recorder.record('/sd//dir1///dir2/hidfrobot.wav')   #set wav will be played
recorder.set_endcallback(mycb)                      #set callback
#Catch exceptions,stop recorder if interrupted accidentally
try:
  while True:
    if button.value() == 0:
      recorder.stop()
    elif recorder.get_busy() == False:              #if recorder not play,stop recorder
      print("record finished")
      break
except:
  recorder.stop()
Example #31
0
def mqttMsg(topic, msg):
    ''' ontvang de mqtt berichten en zet LED1 aan of uit '''
    msg = msg.decode("UTF-8")
    pLed1.value(int(msg))
    return


# constanten
#BROKER = "192.168.1.22" #IP Broker
BROKER = "172.24.0.100"  #IP Broker
ID = "esp_frank_1604"  #moet uniek zijn voor je netwerk
TOPIC1 = "sched/frank1604/LED1"

# led1 initialiseren
pLed1 = Pin(32, Pin.OUT)
pLed1.value(0)

# wifi initialiseren
mqttCl = None
myWifi = simpleWifi.Wifi()

if not (myWifi.open()):
    myWifi.get_status()
    sys.exit()
myWifi.get_status()

try:
    # mqtt client aanmaken
    mqttCl = MQTTClient(ID, BROKER)
    # callback functie instellen voor ontvangen berichten
    mqttCl.set_callback(mqttMsg)
Example #32
0
#Potentiometer board v1.0p test code

from machine import Pin
from pyb import CAN, ADC
import utime

print("initializing")
can = CAN(1, CAN.NORMAL)
can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126))

#Setup Pins
hbt_led = Pin("D5", Pin.OUT)
func_butt = Pin("E7", Pin.IN, Pin.PULL_UP)
can_wakeup = Pin("D6", Pin.OUT)
can_wakeup.value(0)

a_button = Pin("E13", Pin.IN, Pin.PULL_UP)
b_button = Pin("E12", Pin.IN, Pin.PULL_UP)
a_pot = ADC("A1")
b_pot = ADC("A0")

column_a = Pin("E4", Pin.OUT, Pin.PULL_DOWN)
column_b = Pin("E3", Pin.OUT, Pin.PULL_DOWN)
column_a.value(
    1
)  #When the column is HIGH the column is OFF, write them to OFF on initialization
column_b.value(1)

row_0 = Pin("D0", Pin.OUT)
row_1 = Pin("D1", Pin.OUT)
row_2 = Pin("E2", Pin.OUT)
Example #33
0
def test_noinit():
    for p in pin_map:
        pin = Pin(p)
        pin.value()
Example #34
0
class ShiftRegister:
	#need to know what pins we're using
	#On DIP 595 - pins 12, 11 an 14
	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)
		
	def shiftOut(self, data, latch=True):
		# print(data)
		for bit in range(8):
			print(bit)
			
			if 0 == (data & (1<<bit)):
				self._dataPin.value(0)
				print("low")
			else:
				self._dataPin.value(1)
				print("high")
			self._clockPin.value(0)
			time.sleep_us(1)
			self._clockPin.value(1)
			time.sleep_us(10)
		if(latch):
			self._latchPin.value(0)
			time.sleep_us(1)
			self._latchPin.value(1)
			time.sleep_us(1)
Example #35
0


nvic_set_prio(-1, 1)
nvic_set_prio(25, 0)

# probably want to enable-preload (ARR, CCR1, etc), then load next set of values, then CEN
# because after n-pulses, UEV fires...
# then in a UEV interrupt (??) we can load the next set of values via DMA/memory, and re-CEN (unless there are no more data from DMA/memory)

#import dump_regs
#dump_regs.dump_regs()


# make sure PA0 PA1, PA2 are output LO state
timers_init() 

YEL_LED.value(1)
EN_18V_ONBOARD.value(1)
#EN_18V_U4.value(0)
pyb.delay(900)

YEL_LED.value(0)
EN_18V_ONBOARD.value(0)
#EN_18V_U4.value(1)
pyb.delay(2000)


YEL_LED.value(1)
#EN_18V_U4.value(0)
Example #36
0
class HX711:
    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)

    def set_gain(self, gain):
        if gain is 128:
            self.GAIN = 1
        elif gain is 64:
            self.GAIN = 3
        elif gain is 32:
            self.GAIN = 2

        self.read()
        self.filtered = self.read()
        print('Gain & initial value set')
    
    def is_ready(self):
        return self.pOUT() == 0

    def read(self):
        # wait for the device being ready
        while self.pOUT() == 1:
            idle()

        # shift in data, and gain & channel info
        result = 0
        for j in range(24 + self.GAIN):
            state = disable_irq()
            self.pSCK(True)
            self.pSCK(False)
            enable_irq(state)
            result = (result << 1) | self.pOUT()

        # shift back the extra bits
        result >>= self.GAIN

        # check sign
        if result > 0x7fffff:
            result -= 0x1000000

        return result

    def read_average(self, times=3):
        sum = 0
        for i in range(times):
            sum += self.read()
        return sum / times

    def read_lowpass(self):
        self.filtered += self.time_constant * (self.read() - self.filtered)
        return self.filtered

    def get_value(self, times=3):
        return self.read_average(times) - self.OFFSET

    def get_units(self, times=3):
        return self.get_value(times) / self.SCALE

    def tare(self, times=15):
        sum = self.read_average(times)
        self.set_offset(sum)

    def set_scale(self, scale):
        self.SCALE = scale

    def set_offset(self, offset):
        self.OFFSET = offset

    def set_time_constant(self, time_constant = None):
        if time_constant is None:
            return self.time_constant
        elif 0 < time_constant < 1.0:
            self.time_constant = time_constant

    def power_down(self):
        self.pSCK.value(False)
        self.pSCK.value(True)

    def power_up(self):
        self.pSCK.value(False)
Example #37
0
            i2c.writeto(0x3c, bytes((0x80, 0x81, 0x80, contrast)))
        except OSError as e:
            print(e)


def oledinvert(invert=True):
    if buffer is not None:
        try:
            i2c.writeto(0x3c, bytes((0x80, 0xa6 | (invert & 1))))
        except OSError as e:
            print(e)


# Initialize OLED screen if it is there
rst = Pin(16, Pin.OUT)
rst.value(1)
if 0x3c in i2c.scan():

    # There is an extra byte to the data buffer to hold an I2C data/command byte
    # to use hardware-compatible I2C transactions.
    buffer = bytearray(((64 // 8) * 128) + 1)
    buffer[0] = 0x40  # Set first byte of data buffer to Co=0, D/C=1
    fbuff = framebuf.FrameBuffer1(memoryview(buffer)[1:], 128, 64)

    cmdforinit = bytes((
        0xae,  # CMD_DISP=off
        0x20,
        0x00,  # SET_MEM_ADDR  horizontal
        0x40,  # SET_DISP_START_LINE
        0xa0 | 0x01,  # column addr 127 mapped to SEG0
        0xa8,
Example #38
0
def toggle(pin: Pin) -> None:
    pin.value(not pin.value())
Example #39
0
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 Pin, SPI
from time import sleep_ms

# UEXT wiring on the Pyboard.
# https://github.com/mchobby/pyboard-driver/tree/master/UEXT
spi = SPI(2) # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init( baudrate=5000000, phase=0, polarity=0 )
# We must manage the SS signal ourself
ss = Pin( Pin.board.Y5, Pin.OUT )

# Start a new SPI transaction
ss.value( 1 )
sleep_ms( 10 )
ss.value( 0 )


print( "Write a A on the screen" )
spi.send( bytes([0x80,0x00,0x41]) )

sleep_ms( 500 )

# Now, read back the memory
# Start a new SPI transaction
ss.value( 1 )
sleep_ms( 10 )
ss.value( 0 )
spi.send( bytes([0x00,0x00]) )
Example #40
0
button_red = Pin(25, Pin.IN, Pin.PULL_DOWN)
button_green = Pin(26, Pin.IN, Pin.PULL_DOWN)

#Touchpad
tpin = TouchPad(Pin(27))
tpin_green = TouchPad(Pin(33))

# configure the threshold at which the pin is considered touched
tpin.config(500)
esp32.wake_on_touch(True)

#External button wake-up
esp32.wake_on_ext1(pins = (button_red, button_green), level = esp32.WAKEUP_ANY_HIGH)

#Red led turns on
red.value(1)

#Hardware timer - 2
tim2 = Timer(2)
tim2.init(period=10, mode=Timer.PERIODIC, callback=handletouch)

# #Hardware timer - 3
tim3 = Timer(3)
tim3.init(period=30000, mode=Timer.PERIODIC, callback=handlesleep)

# check if the device woke from a deep sleep
if machine.wake_reason() == 5:
    print('Touchpad Wake-up') 
elif machine.wake_reason() == 3:
    print('EXT1 Wake-up')
elif machine.wake_reason() == 4:
Example #41
0
class MFRC522:
  RESET = 'GP22'
  CLK = 'GP14'
  MISO = 'GP15'
  MOSI = 'GP16'
  CS = 'GP17'

  MAX_LEN = 16
  
  PCD_IDLE       = 0x00
  PCD_AUTHENT    = 0x0E
  PCD_TRANSCEIVE = 0x0C
  PCD_RESETPHASE = 0x0F
  PCD_CALCCRC    = 0x03

  PICC_REQIDL    = 0x26
  PICC_REQALL    = 0x52
  PICC_ANTICOLL  = 0x93
  PICC_SElECTTAG = 0x93
  PICC_AUTHENT1A = 0x60
  PICC_READ      = 0x30
  PICC_WRITE     = 0xA0
  
  MI_OK       = 0
  MI_NOTAGERR = 1
  MI_ERR      = 2
  MI_AUTH_ERROR_STATUS2REG = 3

  CommandReg     = 0x01
  CommIEnReg     = 0x02
  CommIrqReg     = 0x04
  DivIrqReg      = 0x05
  ErrorReg       = 0x06
  Status2Reg     = 0x08
  FIFODataReg    = 0x09
  FIFOLevelReg   = 0x0A
  WaterLevelReg  = 0x0B
  ControlReg     = 0x0C
  BitFramingReg  = 0x0D
  
  ModeReg        = 0x11
  TxControlReg   = 0x14
  TxAutoReg      = 0x15
  
  CRCResultRegM     = 0x21
  CRCResultRegL     = 0x22
  TModeReg          = 0x2A
  TPrescalerReg     = 0x2B
  TReloadRegH       = 0x2C
  TReloadRegL       = 0x2D
    
  serNum = []

  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()
  
  def MFRC522_Reset(self):
    self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)
  
  def Write_MFRC522(self, addr, val):
    self.pin_cs.value(0)
    # 0(MSB = Write) ADDR1 ADDR2 ADDR3 ADDR4 ADDR5 ADDR6 0(LSB = 0) DATA
    spiBytes = bytearray(2)
    spiBytes[0] = ((addr<<1)&0x7E) 
    spiBytes[1] = val
    self.spi.write(spiBytes)
    self.pin_cs.value(1)
  
  def Read_MFRC522(self, addr):
    self.pin_cs.value(0)
    # 1(MSB = Read) ADDR1 ADDR2 ADDR3 ADDR4 ADDR5 ADDR6 0(LSB = 0)
    self.spi.write((addr<<1)&0x7E|0x80)
    data = self.spi.read(1)
    self.pin_cs.value(1)
    return data[0]
  
  def SetBitMask(self, reg, mask):
    tmp = self.Read_MFRC522(reg)
    self.Write_MFRC522(reg, tmp | mask)
    
  def ClearBitMask(self, reg, mask):
    tmp = self.Read_MFRC522(reg);
    self.Write_MFRC522(reg, tmp & (~mask))
  
  def AntennaOn(self):
    temp = self.Read_MFRC522(self.TxControlReg)
    if(~(temp & 0x03)):
      self.SetBitMask(self.TxControlReg, 0x03)

  
  def AntennaOff(self):
    self.ClearBitMask(self.TxControlReg, 0x03)
  
  def MFRC522_ToCard(self,command,sendData):
    backData = []
    backLen = 0
    status = self.MI_ERR
    irqEn = 0x00
    waitIRq = 0x00
    lastBits = None
    n = 0
    i = 0
    
    if command == self.PCD_AUTHENT:
      irqEn = 0x12
      waitIRq = 0x10
    if command == self.PCD_TRANSCEIVE:
      irqEn = 0x77
      waitIRq = 0x30

    self.Write_MFRC522(self.CommIEnReg, irqEn|0x80)
    self.ClearBitMask(self.CommIrqReg, 0x80)
    self.SetBitMask(self.FIFOLevelReg, 0x80)
    self.Write_MFRC522(self.CommandReg, self.PCD_IDLE);  

    while(i<len(sendData)):
      self.Write_MFRC522(self.FIFODataReg, sendData[i])
      i = i+1
    self.Write_MFRC522(self.CommandReg, command)

    if command == self.PCD_TRANSCEIVE:
      self.SetBitMask(self.BitFramingReg, 0x80)
    
    i = 2000
    while True:
      n = self.Read_MFRC522(self.CommIrqReg)
      i = i - 1
      if ~((i!=0) and ~(n&0x01) and ~(n&waitIRq)):
        break
    
    self.ClearBitMask(self.BitFramingReg, 0x80)
  
    if i != 0:
      st = self.Read_MFRC522(self.ErrorReg)
      if (st & 0x1B)==0x00:
        status = self.MI_OK

        if n & irqEn & 0x01:
          status = self.MI_NOTAGERR
        elif command == self.PCD_TRANSCEIVE:
          n = self.Read_MFRC522(self.FIFOLevelReg)
          lastBits = self.Read_MFRC522(self.ControlReg) & 0x07
          if lastBits != 0:
            backLen = (n-1)*8 + lastBits
          else:
            backLen = n*8
          
          if n == 0:
            n = 1
          if n > self.MAX_LEN:
            n = self.MAX_LEN
    
          i = 0
          while i<n:
            backData.append(self.Read_MFRC522(self.FIFODataReg))
            i = i + 1;
      else:
        status = self.MI_ERR
    return (status,backData,backLen)
  
  
  def MFRC522_Request(self, reqMode):
    status = None
    backBits = None
    TagType = [reqMode]

    self.Write_MFRC522(self.BitFramingReg, 0x07)

    (status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
    if ((status != self.MI_OK) | (backBits != 0x10)):
      status = self.MI_ERR
      
    return (status,backBits)
  
  
  def MFRC522_Anticoll(self):
    backData = []
    serNumCheck = 0
    
    serNum = [self.PICC_ANTICOLL, 0x20]
  
    self.Write_MFRC522(self.BitFramingReg, 0x00)
    
    (status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,serNum)
    
    if(status == self.MI_OK):
      i = 0
      if len(backData)==5:
        while i<4:
          serNumCheck = serNumCheck ^ backData[i]
          i = i + 1
        if serNumCheck != backData[i]:
          status = self.MI_ERR
      else:
        status = self.MI_ERR
  
    return (status,backData)
  
  def CalulateCRC(self, pIndata):
    self.ClearBitMask(self.DivIrqReg, 0x04)
    self.SetBitMask(self.FIFOLevelReg, 0x80);
    i = 0
    while i<len(pIndata):
      self.Write_MFRC522(self.FIFODataReg, pIndata[i])
      i = i + 1
    self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
    i = 0xFF
    while True:
      n = self.Read_MFRC522(self.DivIrqReg)
      i = i - 1
      if not ((i != 0) and not (n&0x04)):
        break
    pOutData = []
    pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
    pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
    return pOutData
  
  def MFRC522_SelectTag(self, serNum):
    backData = []
    buf = [self.PICC_SElECTTAG, 0x70] + serNum[:5]

    buf += self.CalulateCRC(buf)
    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
    
    if (status == self.MI_OK) and (backLen == 0x18):
      return self.MI_OK
    else:
      return self.MI_ERR
  
  def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
    #First byte should be the authMode (A or B)
    #Second byte is the trailerBlock (usually 7)
    #Now we need to append the authKey which usually is 6 bytes of 0xFF
    #Next we append the first 4 bytes of the UID
    buff = [authMode, BlockAddr] + Sectorkey + serNum[:4]

    # Now we start the authentication itself
    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT,buff)

    # Check if an error occurred


    # Return the status
    return status
  
  def MFRC522_StopCrypto1(self):
    self.ClearBitMask(self.Status2Reg, 0x08)

  def MFRC522_Read(self, blockAddr):
    recvData = [self.PICC_READ, blockAddr]
    recvData += self.CalulateCRC(recvData)

    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
    return (status, backData)
  
  def MFRC522_Write(self, blockAddr, writeData):
    buff = [self.PICC_WRITE, blockAddr]
    buff += self.CalulateCRC(buff)
    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
    if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
        status = self.MI_ERR
    
    if status == self.MI_OK:
        i = 0
        buf = []
        while i < 16:
            buf.append(writeData[i])
            i = i + 1
        buf += self.CalulateCRC(buf)
        (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,buf)
        if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
            status = self.MI_ERR

    return status

  def MFRC522_Init(self):
    self.MFRC522_Reset();
    
    self.Write_MFRC522(self.TModeReg, 0x8D)
    self.Write_MFRC522(self.TPrescalerReg, 0x3E)
    self.Write_MFRC522(self.TReloadRegL, 30)
    self.Write_MFRC522(self.TReloadRegH, 0)
    self.Write_MFRC522(self.TxAutoReg, 0x40)
    self.Write_MFRC522(self.ModeReg, 0x3D)
    self.AntennaOn()
Example #42
0
from machine import Pin, PWM
import mfrc522, time

rfid = mfrc522.MFRC522(0, 2, 4, 5, 14)
led = Pin(15, Pin.OUT)

while True:
    led.value(0)  #搜尋卡片之前先關閉LED
    stat, tag_type = rfid.request(rfid.REQIDL)  #搜尋RFID卡片

    if stat == rfid.OK:  #找到卡片
        stat, raw_uid = rfid.anticoll()  #讀取RFID卡號
        if stat == rfid.OK:
            led.value(1)  #讀到卡號後點亮LED

            #將卡號由2進位格式轉換為16進位的字串
            id = "%02x%02x%02x%02x" % (raw_uid[0], raw_uid[1], raw_uid[2],
                                       raw_uid[3])
            print("偵測到卡號:", id)

            time.sleep(0.5)  #暫停一下,避免LED太快熄滅看不到
try:
  import ssd1306
except:
  # OLED support won't be available
  pass
micropython.alloc_emergency_exception_buf(100)


period = 265
width = 1
number_of_pulse_pairs = 5
common_prescaler = 11

# G30 TH Pin JP32 ==> g30pulser.sch J2-12  PB8
p32_pin = Pin('JP32', Pin.OUT) 
p32_pin.value(0)


enable_gpio_and_timers()
#enable_pa0_pa1_af()

# Setup ADC Timer and a callback to try printing the value
#adc_vals = [-1 for i in range(number_of_pulse_pairs+1 if number_of_pulse_pairs+1 > 128 else 128)]
#t4 = pyb.Timer(4, prescaler=0, period=0)
#stm.mem16[stm.TIM4 + stm.TIM_CR1] &= (~1) & 0xFFFF# disable CEN
#adc_timer = t4.channel(4, pyb.Timer.PWM)#OC_TIMING, polarity=pyb.Timer.HIGH)
#stm.mem16[stm.TIM4 + stm.TIM_CR1] &= (~1) & 0xFFFF# disable CEN

#G30TH pin JP29 ==> g30pulser.sch J2-9  PA4
adc = pyb.ADC(pyb.Pin.board.JP29) 
#adc_vals = array.array('I',[i for i in range((number_of_pulse_pairs*4)+1)])
Example #44
0
# Button:             ESP32:
# GND Add 10kOhm -->  GND + GPIO4
# VCC -->             3V3

# LED:                ESP32:
# GND add 330 Ohm --> GND
# VCC -->             GPIO5

from machine import Pin
from time import sleep

led = Pin(5, Pin.OUT)
button = Pin(4, Pin.IN)

while True:
    led.value(button.value())
    sleep(0.1)
Example #45
0
# This is an example on how to access accelerometer on
# PyBoard directly using I2C bus. As such, it's more
# intended to be an I2C example, rather than accelerometer
# example. For the latter, using pyb.Accel class is
# much easier.

from machine import Pin
from machine import I2C
import time

# Accelerometer needs to be powered on first. Even
# though signal is called "AVDD", and there's separate
# "DVDD", without AVDD, it won't event talk on I2C bus.
accel_pwr = Pin("MMA_AVDD")
accel_pwr.value(1)

i2c = I2C(1, baudrate=100000)
addrs = i2c.scan()
print("Scanning devices:", [hex(x) for x in addrs])
if 0x4c not in addrs:
    print("Accelerometer is not detected")

ACCEL_ADDR = 0x4c
ACCEL_AXIS_X_REG = 0
ACCEL_MODE_REG = 7

# Now activate measurements
i2c.mem_write(b"\x01", ACCEL_ADDR, ACCEL_MODE_REG)

print("Try to move accelerometer and watch the values")
while True:
Example #46
0
class Juego:
    TIEMPO_LIMITE = 3000  # milisegundos antes de que salte el timeout

    def __init__(self, nombre):
        self.nombre = nombre
        self.led = Pin(2, Pin.OUT)
        self.led.value(1)  # empiezo con el led apagado
        self.boton = Pin(0, Pin.IN)
        self.mimqtt = Mimqtt(self.registro_recibido
                             )  # le pasamos un callback para que nos avise
        self.sensor = None
        self.basedatos = Basedatos()
        self.mostrar_mejores_puntuaciones(
        )  # al iniciar mostramos las mejores puntuacinoes guardadas (Si hay)

    def usar_sensor(self, sensor):
        """ Si le pasamos la instancia de un sensor APDS9930, lo utilizamos en vez del boton """
        self.sensor = sensor

    def comenzar(self):
        """ Bucle infinito que hace toda la logica de esperar, led on, esperar por boton, led off, medir tiempo """
        print()
        while True:
            print("Pulsa el boton cuando se encienda el led")
            self.esperar_tiempo_random()
            if self.check_pulsado(
            ):  # comprueba si esta pulsado antes de que se encienda el led
                print(
                    "No valido. Has pulsado antes de que se encendiera el led. ",
                    end='')
                continue
            self.led.value(0)  # enciendemos led
            tiempo_inicio = utime.ticks_ms(
            )  # guardamos tiempo nada mas encender led
            valido = self.esperar_pulsacion(
            )  # espera por boton o sensor, y devuelve si fue valido o timeout
            self.led.value(1)  # apagamos led
            if not valido:
                print("Has tardado demasiado. Intentalo otra vez. ", end='')
                continue
            tiempo_fin = utime.ticks_ms(
            )  # guardamos tiempo justo al presionar el boton
            tiempo_total = utime.ticks_diff(
                tiempo_fin, tiempo_inicio)  # tiempo reaccion fin-inicio
            print("has apagado el led en {}ms".format(tiempo_total))
            self.mimqtt.enviar(self.nombre, tiempo_total)
            utime.sleep_ms(100)

    def check_pulsado(self):
        """ Comprueba si el dispositivo de entrada (boton o sensor) esta pulsado/activado """
        if self.sensor is None:
            return self.check_boton(
            )  # si sensor es None comprobamos boton de la placa
        else:
            return self.check_sensor()  # sino comprobamos sensor

    def esperar_pulsacion(self):
        """ Espera que el dispositivo de entrada (boton o sensor) se active, o salte el timeout """
        tiempo_inicio = utime.ticks_ms()
        while not self.check_pulsado(
        ):  # bucle mientra no se pulse el boton o sensor
            utime.sleep_ms(1)
            if utime.ticks_diff(utime.ticks_ms(),
                                tiempo_inicio) > Juego.TIEMPO_LIMITE:
                return False  # con False indicamos que salto el timeout
        return True  # con True indicamos que fue una pulsacion valida

    def check_sensor(self):
        """ Devuelve True si el sensor de proximidad esta activado """
        return self.sensor.get_proximidad(
        ) > 0  # si nos devuelve un valor mayor que cero es que esta activado
        # y evalua como True, por lo que devuelve True. Si es cero evalua y devuelve False

    def check_boton(self):
        """ Devuelve True si el boton de la placa esta presionado """
        return self.boton.value(
        ) == 0  # el boton funciona con logica negativa, es igual a cero cuando se pulsa

    def registro_recibido(self, nombre, tiempo):
        """ callback que salta desde mimqtt, cuando hay un nuevo registro valido """
        print("registro de '{}' tiempo {}ms".format(nombre, tiempo))
        # se lo pasamos a nuestra base de datos para que lo guarde si procede (nuevo o record)
        self.basedatos.nuevo_registro(nombre, tiempo)

    def mostrar_mejores_puntuaciones(self):
        """ Muestra por consola las 3 mejores puntuaciones guardadas en la base de datos """
        mejores_puntuaciones = self.basedatos.get_mejores_puntuaciones()
        if not mejores_puntuaciones:  # si es una lista vacia no hacemos nada
            return
        print(
            "\nMejores puntuaciones historicas\n==============================="
        )
        posiciones = ("Primero", "Segundo", "Tercero")
        for indice, tupla_nombre_tiempo in enumerate(
                mejores_puntuaciones
        ):  # es una lista de maximo 3 tuplas con (nombre, tiempo)
            print("{} - {} con {}ms".format(posiciones[indice],
                                            tupla_nombre_tiempo[0].decode(),
                                            int(tupla_nombre_tiempo[1])))

    def finalizar(self):
        """ Detiene todo lo que esta en marcha """
        self.mimqtt.disconnect(
        )  # cancela timer de comprobar mensajes y desconecta cliente
        self.basedatos.close()  # cierra todo lo relaccionado con la db

    @staticmethod
    def esperar_tiempo_random():
        tiempo_random = urandom.getrandbits(
            12)  # valor de 12 bits -> entre 0 y 4095
        utime.sleep_ms(tiempo_random + 3000)  # valor entre 3000 y 7095
Example #47
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)
Example #48
0
from machine import Pin
from utime import sleep_ms

# assign led to Pin
led = Pin(2, Pin.OUT, value=1)

#{{{ 1
for i in range(10):
    led.value(not led.value())  # swich led value
    print(i)
    sleep_ms(500)
#}}}
from nrf24l01 import NRF24L01
from machine import SPI, Pin
from time import sleep
import struct

csn = Pin(14, mode=Pin.OUT, value=1)  # Chip Select Not
ce = Pin(17, mode=Pin.OUT, value=0)  # Chip Enable
led = Pin(25, Pin.OUT)  # Onboard LED
payload_size = 20

# Handle
handle_forward = Pin(10, Pin.OUT)  # Relay 1.
handle_backward = Pin(11, Pin.OUT)  # Relay 2.

# Set both relays to off position
handle_forward.value(1)
handle_backward.value(1)

# Define the channel or 'pipes' the radios use.
# switch round the pipes depending if this is a sender or receiver pico

#role = "send"
role = "receive"

if role == "send":
    send_pipe = b"\xe1\xf0\xf0\xf0\xf0"
    receive_pipe = b"\xd2\xf0\xf0\xf0\xf0"
else:
    send_pipe = b"\xd2\xf0\xf0\xf0\xf0"
    receive_pipe = b"\xe1\xf0\xf0\xf0\xf0"
Example #50
0
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)
ads = ads1x15.ADS1115(i2c, addr, gain)

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

def measure(r2):
    vcc = ads.raw_to_v(ads.read(channel1=1))
    vout = ads.raw_to_v(ads.read())
    I = vout / r2
    r1 = r2 * (vcc / vout - 1)
    
    print('---------')
    print('R1 = {:.2f} ohm'.format(r1))
    print('Vcc = {:.2f} V'.format(vcc))
    print('Vout = {:.2f} V'.format(vout))
    print('I = {:.4f} mA'.format(I * 1000))
    
    oled.fill(0)
    oled.text('ohms', 0, 0)
    oled.text('R1 = {:.2f}'.format(r1), 10, 30)
    oled.show()
    
r2 = 9990
while True:
    if sw.value() == 0:
        time.sleep_ms(20)
        if sw.value() == 0:
            while sw.value() == 0:
                pass
            measure(r2)
Example #51
0
        fCsv.write(msg)
        fCsv.write('\n')
        fCsv.flush()
        
        print(msg)              # show in repl
        
        count = count + 1

    s.close()
    time.sleep(0.3)  #<== Try a delay here...
    
    # -----------------------------
    # add button manager
    if button() == 1:
        # pushbutton pressed
        if pressed == 1:
            continue
        # pushbutton pressed
        pycom.rgbled(0x7f0000)      # red
        # switch on the user LED
        user_led.value(1)
        # print("---------------------------- button pressed !!")
        pressed = 1
    else: 
        # pushbutton released
        pycom.rgbled(0x007f00) # green
        # switch off the user LED
        user_led.value(0)
        pressed = 0

        
Example #52
0
    trigger1(0)

    while echo1() == 0:
        pass

    chrono.start()

    while echo1() == 1:
        pass

    chrono.stop()

    distance1 = chrono.read_us() / 58.0

    if distance1 <= 7:
        p_green_light.value(1)
        count -= 1
    else:
        p_green_light.value(0)

    if distance1 > 400:
        print("Out of range")
    else:
        print("Sensor 1 {:.0f} cm".format(distance1))

    time.sleep(0.1)

    #-------------------- Sensor 2 -----------------------------------

    chrono.reset()
Example #53
0
import my_app
from machine import Pin, reset
from utime import sleep_ms
sleep_ms(1000)
pin = Pin(13, Pin.IN, Pin.PULL_UP)
while True:
    if pin.value():
        try:
            my_app.kmain()
        except:
            reset()
    else:
        sleep_ms(200)
Example #54
0
from machine import Pin
pin_button = Pin(0, Pin.IN)
pin_led = Pin(14, Pin.OUT)

while True:
    stav = pin_button.value()
    pin_led.value(stav)
    
Example #55
0
test_pin_af() # try the entire af range on all pins

# test pin init and printing
pin = Pin(pin_map[0])
pin.init(mode=Pin.IN)
print(pin)
pin.init(Pin.IN, Pin.PULL_DOWN)
print(pin)
pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER)
print(pin)
pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER)
print(pin)

# test value in OUT mode
pin = Pin(pin_map[0], mode=Pin.OUT)
pin.value(0)
pin.toggle() # test toggle
print(pin())
pin.toggle() # test toggle again
print(pin())
# test different value settings
pin(1)
print(pin.value())
pin(0)
print(pin.value())
pin.value(1)
print(pin())
pin.value(0)
print(pin())

# test all getters and setters
# ######################### #
# Blink build-in Huzzah led #
# ######################### #

from machine import Timer, Pin
p0 = Pin(0, Pin.OUT)
tim = Timer(-1)
tim.init(period=500, 
    mode=Timer.PERIODIC, callback=lambda t: p0.value(not p0.value()))
Example #57
0
class WifiClock:
    def __init__(self):

        # Initialize SPI
        self._spi = SPI(-1,
                        baudrate=10000000,
                        polarity=1,
                        phase=0,
                        sck=Pin(_SPI_CLK_PIN),
                        mosi=Pin(_SPI_MOSI_PIN),
                        miso=Pin(_SPI_MISO_PIN))
        self._cs = Pin(_SPI_CS_PIN)
        self._cs.init(self._cs.OUT, True)

        # Initialize LEDs
        self.red_led = Pin(_RED_LED_PIN, Pin.OUT)
        self.green_led = Pin(_GREEN_LED_PIN, Pin.OUT)
        self.blue_led = Pin(_BLUE_LED_PIN, Pin.OUT)

        # Initialize buttons with interrupts
        self.mode_button = Pin(_MODE_BUTTON_PIN, Pin.IN, Pin.PULL_UP)
        self.mode_button.irq(trigger=Pin.IRQ_FALLING,
                             handler=self.mode_button_callback)
        self.incr_button = Pin(_INCR_BUTTON_PIN, Pin.IN, Pin.PULL_UP)
        self.incr_button.irq(trigger=Pin.IRQ_FALLING,
                             handler=self.incr_button_callback)
        self.decr_button = Pin(_DECR_BUTTON_PIN, Pin.IN, Pin.PULL_UP)
        self.decr_button.irq(trigger=Pin.IRQ_FALLING,
                             handler=self.decr_button_callback)

        # Initialize current number and current decimal points
        self.current_num = None
        self.current_dp = 0b000000

        # Initialize timer and rtc
        self.sta_if = network.WLAN(network.STA_IF)
        self.rtc = RTC()
        self.timer = Timer(1)

        for command, data in (
            (_SHUTDOWN, 0),
            (_SCAN_LIMIT, 7),
            (_DECODE_MODE, 0xFF),
            (_INTENSITY, 0xa),
            (_SHUTDOWN, 1),
        ):
            self._register(command, data)

        self.display_clear()
        self.red_led.value(0)
        self.green_led.value(0)
        self.blue_led.value(0)

    # Connect to wifi
    def connect_to_wifi(self, ssid, password):
        if not self.sta_if.isconnected():
            print('Connecting to network...')
            self.sta_if.active(True)
            self.sta_if.connect(ssid, password)
            while not self.sta_if.isconnected():
                print('.', end='')
                time.sleep(1)
        print('Connected!')

    # Set time manually
    def set_time(self, hour, minute, second):
        self.rtc.datetime((2019, 1, 1, 0, hour, minute, second, 0))

    # Set time using ntp server (must be connected to wifi)
    def set_time_ntp(self, utc_offset):
        ntptime.settime()
        d = self.rtc.datetime()

        hour = d[4] + utc_offset

        if hour < 0:
            hour = 24 + hour
        elif hour > 23:
            hour = hour - 24

        d = (d[0], d[1], d[2], d[3], hour, d[5], d[6], d[7])
        self.rtc.datetime(d)

    # Start a 24 hour clock (call after setting the time either with set_time or set_time_ntp)
    def start_clock24(self):
        self.timer.init(period=1000,
                        mode=Timer.PERIODIC,
                        callback=self.clock_timer_callback)

    # Set the display brightness
    def display_brightness(self, value):
        if 0 <= value <= 15:
            self._register(_INTENSITY, value)
        else:
            raise ValueError("Brightness out of range")

    # Clear the display
    def display_clear(self):
        self._register(_DECODE_MODE, 0xFF)
        for i in range(6):
            self._register(_DIGIT_DICT[i], 0x0F)

        self.current_num = None

    # Write a decimal value to the display, dp is 6 bit binary value representing where to put decimal points
    def write_num(self, value, dp=0b000000):
        self._register(_DECODE_MODE, 0xFF)

        if (0 <= value <= _MAX_VALUE_DEC) and (_MIN_VALUE_DP <= dp <=
                                               _MAX_VALUE_DP):
            self.current_num = value
            self.current_dp = dp

            for i in range(6):
                current_value = value % 10

                if dp & 1:

                    self._register(_DIGIT_DICT[i], current_value | _DP)
                else:
                    self._register(_DIGIT_DICT[i], current_value)

                dp = dp >> 1
                value = value // 10

        elif (0 > value >= _MIN_VALUE_DEC) and (_MIN_VALUE_DP <= dp <=
                                                _MAX_VALUE_DP):
            self.current_num = value
            self.current_dp = dp

            value = -value
            self._register(_DIGIT5, 0xA)

            for i in range(5):
                current_value = value % 10

                if dp & 1:

                    self._register(_DIGIT_DICT[i], current_value | _DP)
                else:
                    self._register(_DIGIT_DICT[i], current_value)

                dp = dp >> 1
                value = value // 10

        else:
            raise ValueError("Value out of range")

    # Write literal hex value to the display
    def write_hex(self, value):
        self._register(_DECODE_MODE, 0x0)
        if 0x0 <= value <= _MAX_VALUE_HEX:

            self.current_num = value

            for i in range(6):
                self._register(_DIGIT_DICT[i], _HEX_TO_SEG[value % 16])
                value = value // 16
        else:
            raise ValueError("Value out of range")

    # Toggle an LED
    @staticmethod
    def toggle_led(led):
        led.value(not (led.value()))

    # Increment the current number on the display
    def increment_num(self, hex=False):
        if self.current_num is None:
            raise ValueError("No value to increment")
        else:

            if hex:
                if (self.current_num + 1) > _MAX_VALUE_HEX:
                    self.current_num = -1

                self.write_hex(self.current_num + 1)
            else:

                if (self.current_num + 1) > _MAX_VALUE_DEC:
                    self.current_num = -1

                self.write_num(self.current_num + 1, self.current_dp)

    # Decrement the current number on the display
    def decrement_num(self, hex=False):
        if self.current_num is None:
            raise ValueError("No value to decrement")
        else:

            if hex:
                if (self.current_num - 1) < _MIN_VALUE_HEX:
                    self.current_num = 1

                self.write_hex(self.current_num - 1)
            else:

                if (self.current_num - 1) < _MIN_VALUE_DEC:
                    self.current_num = 1

                self.write_num(self.current_num - 1, self.current_dp)

    # Callback for Mode button
    def mode_button_callback(self, pin):
        if self._debounce(self.mode_button):
            self.toggle_led(self.red_led)

    # Callback for Incr Button
    def incr_button_callback(self, pin):
        if self._debounce(self.incr_button):
            self.increment_num()

    # Callback for Decr button
    def decr_button_callback(self, pin):
        if self._debounce(self.decr_button):
            self.decrement_num()

    # Callback for clock after calling start_clock24
    def clock_timer_callback(self, tim):
        self._update_clock24()

    # Callback for other timer uses
    def timer_callback(self, tim):
        self.increment_num()

    # Read hours, minutes, and seconds from rtc and and write to the display
    def _update_clock24(self):
        current_time = self.rtc.datetime()

        hours = current_time[4]
        minutes = current_time[5]
        seconds = current_time[6]

        time_str = ''

        if hours < 10:
            time_str += '0'
        time_str += str(hours)

        if minutes < 10:
            time_str += '0'
        time_str += str(minutes)

        if seconds < 10:
            time_str += '0'
        time_str += str(seconds)

        self.write_num(int(time_str), 0b010100)

    # Send commands to MAX7219
    def _register(self, command, data):
        self._cs.value(0)
        self._spi.write(bytearray([command, data]))
        self._cs.value(1)

    # Debounce function for debouncing buttons
    @staticmethod
    def _debounce(button):
        flag = 0

        for i in range(_DEBOUNCE_SAMPLES):
            flag = button.value()
            if button.value():
                return not flag

        return not flag
Example #58
0
def choice():
    if mode == 1:
        pwm1.freq(int(4 + adc.read() / 120))
    if mode == 2:
        pwm0.duty(int(adc.read() / 10))


def display():
    a = rtc.datetime()
    print(week[a[3]] + ", " + str(a[1]) + '/' + str(a[2]) + '/' + str(a[0]) +
          ', ' + str(a[4]) + ':' + ("%02d" % (a[5], )) + ':' +
          ("%02d" % (a[6], )) + '.' + str(a[7]))


while (1):
    if button.value() and prev == 0:
        if mode != 1:
            mode = 1
        else:
            mode = 2
    prev = button.value()
    sleep(0.02)
'''
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:
Example #59
0
class MFRC522:

	OK = 0
	NOTAGERR = 1
	ERR = 2

	REQIDL = 0x26
	REQALL = 0x52
	AUTHENT1A = 0x60
	AUTHENT1B = 0x61

	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()

	def _wreg(self, reg, val):

		self.cs.value(0)
		self.spi.write(b'%c' % int(0xff & ((reg << 1) & 0x7e)))
		self.spi.write(b'%c' % int(0xff & val))
		self.cs.value(1)

	def _rreg(self, reg):

		self.cs.value(0)
		self.spi.write(b'%c' % int(0xff & (((reg << 1) & 0x7e) | 0x80)))
		val = self.spi.read(1)
		self.cs.value(1)

		return val[0]

	def _sflags(self, reg, mask):
		self._wreg(reg, self._rreg(reg) | mask)

	def _cflags(self, reg, mask):
		self._wreg(reg, self._rreg(reg) & (~mask))

	def _tocard(self, cmd, send):

		recv = []
		bits = irq_en = wait_irq = n = 0
		stat = self.ERR

		if cmd == 0x0E:
			irq_en = 0x12
			wait_irq = 0x10
		elif cmd == 0x0C:
			irq_en = 0x77
			wait_irq = 0x30

		self._wreg(0x02, irq_en | 0x80)
		self._cflags(0x04, 0x80)
		self._sflags(0x0A, 0x80)
		self._wreg(0x01, 0x00)

		for c in send:
			self._wreg(0x09, c)
		self._wreg(0x01, cmd)

		if cmd == 0x0C:
			self._sflags(0x0D, 0x80)

		i = 2000
		while True:
			n = self._rreg(0x04)
			i -= 1
			if ~((i != 0) and ~(n & 0x01) and ~(n & wait_irq)):
				break

		self._cflags(0x0D, 0x80)

		if i:
			if (self._rreg(0x06) & 0x1B) == 0x00:
				stat = self.OK

				if n & irq_en & 0x01:
					stat = self.NOTAGERR
				elif cmd == 0x0C:
					n = self._rreg(0x0A)
					lbits = self._rreg(0x0C) & 0x07
					if lbits != 0:
						bits = (n - 1) * 8 + lbits
					else:
						bits = n * 8

					if n == 0:
						n = 1
					elif n > 16:
						n = 16

					for _ in range(n):
						recv.append(self._rreg(0x09))
			else:
				stat = self.ERR

		return stat, recv, bits

	def _crc(self, data):

		self._cflags(0x05, 0x04)
		self._sflags(0x0A, 0x80)

		for c in data:
			self._wreg(0x09, c)

		self._wreg(0x01, 0x03)

		i = 0xFF
		while True:
			n = self._rreg(0x05)
			i -= 1
			if not ((i != 0) and not (n & 0x04)):
				break

		return [self._rreg(0x22), self._rreg(0x21)]

	def init(self):

		self.reset()
		self._wreg(0x2A, 0x8D)
		self._wreg(0x2B, 0x3E)
		self._wreg(0x2D, 30)
		self._wreg(0x2C, 0)
		self._wreg(0x15, 0x40)
		self._wreg(0x11, 0x3D)
		self.antenna_on()

	def reset(self):
		self._wreg(0x01, 0x0F)

	def antenna_on(self, on=True):

		if on and ~(self._rreg(0x14) & 0x03):
			self._sflags(0x14, 0x03)
		else:
			self._cflags(0x14, 0x03)

	def request(self, mode):

		self._wreg(0x0D, 0x07)
		(stat, recv, bits) = self._tocard(0x0C, [mode])

		if (stat != self.OK) | (bits != 0x10):
			stat = self.ERR

		return stat, bits

	def anticoll(self):

		ser_chk = 0
		ser = [0x93, 0x20]

		self._wreg(0x0D, 0x00)
		(stat, recv, bits) = self._tocard(0x0C, ser)

		if stat == self.OK:
			if len(recv) == 5:
				for i in range(4):
					ser_chk = ser_chk ^ recv[i]
				if ser_chk != recv[4]:
					stat = self.ERR
			else:
				stat = self.ERR

		return stat, recv

	def select_tag(self, ser):

		buf = [0x93, 0x70] + ser[:5]
		buf += self._crc(buf)
		(stat, recv, bits) = self._tocard(0x0C, buf)
		return self.OK if (stat == self.OK) and (bits == 0x18) else self.ERR

	def auth(self, mode, addr, sect, ser):
		return self._tocard(0x0E, [mode, addr] + sect + ser[:4])[0]

	def stop_crypto1(self):
		self._cflags(0x08, 0x08)

	def read(self, addr):

		data = [0x30, addr]
		data += self._crc(data)
		(stat, recv, _) = self._tocard(0x0C, data)
		return recv if stat == self.OK else None

	def write(self, addr, data):

		buf = [0xA0, addr]
		buf += self._crc(buf)
		(stat, recv, bits) = self._tocard(0x0C, buf)

		if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
			stat = self.ERR
		else:
			buf = []
			for i in range(16):
				buf.append(data[i])
			buf += self._crc(buf)
			(stat, recv, bits) = self._tocard(0x0C, buf)
			if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
				stat = self.ERR

		return stat
# Complete project details at https://RandomNerdTutorials.com

from machine import Pin, I2C
import ssd1306
from time import sleep

# ESP32 Pin assignment
p16 = Pin(16, Pin.OUT)
p16.value(1)

i2c = I2C(-1, scl=Pin(15), sda=Pin(4))

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

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

oled.text('Hello, World 1!', 0, 0)
oled.text('Hello, World 2!', 0, 10)
oled.text('Hello, World 3!', 0, 20)

oled.show()