Ejemplo n.º 1
0
    def __init__(self, gp_pin, frequency, full_range100, pulse_min, pulse_max):
        """
        :param gp_pin: GPIO pin
        :param frequency: in Hz
        :param full_range100: in deg * 100
        :param pulse_min: in µs
        :param pulse_max: in µs
        :return:
        """
        if not gp_pin in VALID_GP_PINS:
            print('invalid GP pin:', gp_pin)

        # Get WiPy PWM configuration constants
        pin_alt = PIN_PWM_ALT[gp_pin]
        timer_nr = PIN_PWM_TIMER[gp_pin]
        timer_channel = PIN_PWM_CHANNEL[gp_pin]

        # Configure PWM timer to pin flow
        Pin('GP' + str(gp_pin), mode=Pin.ALT, alt=pin_alt)
        timer = Timer(timer_nr, mode=Timer.PWM)
        self.channel = timer.channel(timer_channel, freq=frequency)

        # Store object properties
        self.PWM_frame = 1000000 // frequency  # in µs
        self.full_range100 = full_range100
        self.pulse_min = pulse_min
        self.pulse_diff = pulse_max - pulse_min
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
 def setupTimer(self):
     '''
     Need to look at the following:
     But how to average? (Do we need two buffers)
     http://docs.micropython.org/en/latest/pyboard/library/pyb.ADC.html
     '''
     #How to stop timer?
     self.tim = Timer(0, mode = Timer.PERIODIC, width = 32)#what is this width? Timer resolution?
     self.timChannel = self.tim.channel(Timer.A, freq = self.freq)
     #What is the function of the trigger, do we need to implement external vs internal?
     self.timChannel.irq(handler=self._addData_, trigger = Timer.TIMEOUT)
Ejemplo n.º 4
0
def go():
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid='upython')
    ap.config(authmode=0)
    led = Object()
#    led.np = neopixel.NeoPixel(machine.Pin(14), 1)
#    led.np[0] = (0, 0, 0)
#    led.np.write()
    led.mode = ''
    led.pwm = machine.PWM(machine.Pin(14), freq = 100, duty = 1023)
    led.count = 0

    servo = Object()
    servo.motor = machine.PWM(machine.Pin(12), freq = 50)
    servo.mode = ''
    servo.lastPos = 40
    servo.motor.duty(servo.lastPos)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 80))
    servoTimer = Timer(0)
    servoTimer.init(period = 1000, mode = Timer.PERIODIC, callback = lambda xx: doServo(servo))
    ledTimer = Timer(1)
    ledTimer.init(period = 50, mode = Timer.PERIODIC, callback = lambda xx: doLedMode(led))
    s.listen(0)	# just queue up some requests
    while True:
        time.sleep(.5)
        conn, addr = s.accept()
        request = conn.recv(1024)
        
        conn.sendall('HTTP/1.1 200 OK\nConnection: close\nServer: Tentacle\nContent-Type: text/html\n\n')

        request = str(request)
        print(request)
        if 'servo=' in request:
            servo.mode = 'manual'
            servo.motor.duty(int(valueOf(request, 'servo')))
        elif 'rgb=' in request:
            handleRGB(valueOf(request, 'rgb'), led)
        elif 'pwm=' in request:
            handlePWM(int(valueOf(request, 'pwm')), led)
        elif 'action=' in request:
            todo = valueOf(request, 'action')
            if 'fight' == todo: 
                servo.mode= 'fight'
                led.mode = 'fight'
            elif 'reset' == todo: machine.reset()
            elif 'stop' == todo: servo.mode = 'stop'
            elif 'ledoff' == todo: 
                led.mode = ''
                handleRGB('0,0,0', led)
                handlePWM(1023, led)
            elif 'heartbeat' == todo: led.mode = 'heartbeat'
        else:
            with open('pg.htm', 'r') as html:
                conn.sendall(html.read())
                conn.sendall('\n')

        conn.close()
Ejemplo n.º 5
0
class Fader(object):
    def __init__(self, np, NEOPIXEL_COUNT):
        super(Fader, self).__init__()
        self.step = 0
        self.np = np
        self.NEOPIXEL_COUNT = NEOPIXEL_COUNT
        self.tim = Timer(-1)

    def start(self):
        self.tim.init(period=40, mode=Timer.PERIODIC, callback=self.tick)

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

    def rainbow_cycle(self):
        for i in range(0, self.NEOPIXEL_COUNT):
            self.np[i] = brightness(wheel(int(i * 256 / self.NEOPIXEL_COUNT + self.step) & 255))
        self.np.write()

    def tick(self, t):
        self.rainbow_cycle()
        self.step += 1
        if self.step > 256 * 5:
            self.step = 0
Ejemplo n.º 6
0
#
# SPDX-License-Identifier: MIT License
#
# Change Logs:
# Date           Author       Notes
# 2019-06-29     ChenYong     first version
#

from machine import Timer
import utime as time


def callback_periodic(obj):  # defined  preiodic mode timeout callback
    print("Timer callback periodic test")


def callback_oneshot(obj):  # defined  ont shot mode timeout callback
    print("Timer callback oneshot test")


timer = Timer(1)  # Create Timer object. Timer device number 15 are used.
timer.init(timer.PERIODIC, 1000,
           callback_periodic)  # Initialize the Timer device object
# Set Timer mode to preiodic mode, set timeout to 1 seconds and set callback fucntion
time.sleep_ms(5500)  # Execute 5 times timeout callback in the delay time
timer.init(timer.ONE_SHOT, 1000,
           callback_oneshot)  # Reset initialize the Timer device object
# Set Timer mode to one shot mode, set timeout to 1 seconds and set callback fucntion
time.sleep_ms(1500)  # Execute 1 times timeout callback in the delay time
timer.deinit()  # Stop and close Timer device object
Ejemplo n.º 7
0
    import ujson as json
    try:
        with open("/config.json", "w") as f:
            f.write(json.dumps(CONFIG))
    except OSError:
        print("Couldn't save /config.json")


try:
    c_mqtt = MQTTClient(CONFIG['client_id'], CONFIG['broker'], CONFIG['port'], timeout=1, sbt=CONFIG['topic'],
                        debug=False)

except (OSError, ValueError):
    print("Couldn't connect to MQTT")

timer_http = Timer(-1)
_debug = True
_routeHandlers = []

#System
_routeHandlers.append(SystemHandler(debug=_debug).route_handler)


#Led
LED_2_pin = 2
LED_2 = RELAY(name="Led2", pin_num=LED_2_pin, on_value=0, off_value=1, state_on=1, state_off=0, default=1)
_routeHandlers.append(LedHandler(debug=_debug, relay=LED_2).route_handler)


def main():
    if _debug:
Ejemplo n.º 8
0
from machine import Timer, PWM
import time
from board import board_info
from fpioa_manager import *

board_info = board_info()

tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
ch = PWM(tim, freq=500000, duty=50, pin=board_info.LED_G)
duty = 0
dir = True
while True:
    if dir:
        duty += 10
    else:
        duty -= 10
    if duty > 100:
        duty = 100
        dir = False
    elif duty < 0:
        duty = 0
        dir = True
    time.sleep(0.05)
    ch.duty(duty)
Ejemplo n.º 9
0
pycom.rgbled(0x7f7f00) # yellow
print("Reading file {}".format(filename))
#In case of 0-byte file, create an empty Payload
try:
	with open(filename, "rb") as data:
		f = data.read()
		payload = bytearray(f)

except OSError as e:
		print('Error number {}, {}'.format(e.args[0],e))
		payload = ''

pycom.rgbled(0x007f00) # green

# Init Chrono
chrono = Timer.Chrono()
laps = []
fragmentation_time = 0
start_sending_time = 0
end_sending_time = 0

# stats variables (for testing)
current_fragment = {}
fragments_info_array = []
tx_status_ok = False

# Initialize variables.
total_size = len(payload)
current_size = 0
percent = 0
ack = None
Ejemplo n.º 10
0
	def blink(self):
		pin = machine.Pin(PIN_D5, machine.Pin.OUT, machine.Pin.PULL_UP)
		tim = Timer(-1)
		pin.low()
		tim.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:pin.high())
Ejemplo n.º 11
0
'''

from machine import Timer
import os
import time

mch = os.uname().machine
if 'LaunchPad' in mch:
    pwm_pin = ('GP24')
elif 'WiPy' in mch:
    pwm_pin = ('GP24')
else:
    raise Exception('Board not supported!')

for i in range(4):
    tim = Timer(i, mode=Timer.PERIODIC)
    print(tim)
    ch = tim.channel(Timer.A, freq=5)
    print(ch)
    ch = tim.channel(Timer.B, freq=5)
    print(ch)
    tim = Timer(i, mode=Timer.ONE_SHOT)
    print(tim)
    ch = tim.channel(Timer.A, freq=50)
    print(ch)
    ch = tim.channel(Timer.B, freq=50)
    print(ch)
    tim = Timer(i, mode=Timer.PWM)
    print(tim)
    ch = tim.channel(Timer.A, freq=50000, duty_cycle=2000, polarity=Timer.POSITIVE)
    print(ch)
Ejemplo n.º 12
0
from time import sleep_us, sleep_ms
from machine import Timer
from pyb import Pin

D0 = Pin(0, Pin.IN)

LED_BUILDIN = 16
led = Pin(LED_BUILDIN, Pin.OUT)

def get_value():
    print("flash_key : %d" % D0.value())
    if(D0.value()):
        led.high()
    else:
        led.low()

tim = Timer(0)
tim.init(period=100, mode=Timer.PERIODIC, callback=lambda t:get_value())
#
Ejemplo n.º 13
0
    dailyResult.close()
    return json


def refresh():
    nowRsp = nowWeather(API_KEY)  #通过API密钥获取天气实况
    dailyRsp = dailyWeather(API_KEY)  #通过API密钥获取多日天气预报

    today = dailyRsp['results'][0]['daily'][0]['date'][-5:]  #当前日期,显示“月-日”
    todayHigh = dailyRsp['results'][0]['daily'][0]['high']  #最高温度
    todaylow = dailyRsp['results'][0]['daily'][0]['low']  #最低温度

    nowText = nowRsp['results'][0]['now']['text']  #天气现象文字
    nowTemper = nowRsp['results'][0]['now']['temperature']  #温度
    todayIco = nowRsp['results'][0]['now']['code']  #天气现象图标
    city = nowRsp['results'][0]['location']['name']  #地理位置

    oled.fill(0)
    oled.Bitmap(10, 23, ico[todayIco], 38, 38, 1)  #显示当前天气现象图标
    oled.DispChar("%s,天气实况" % city, 0, 0)
    oled.DispChar(today, 90, 0)
    oled.DispChar("%s℃/%s" % (nowTemper, nowText), 70, 25)  #显示当前温度
    oled.DispChar("%s~%s℃" % (todaylow, todayHigh), 70, 45)  #显示今日最低、最高气温
    oled.show()


refresh()  #数据更新

tim1 = Timer(1)
tim1.init(period=1800000, mode=Timer.PERIODIC,
          callback=lambda _: refresh())  #定时,每半个钟刷新一次
Ejemplo n.º 14
0
def cancel_de(pin):
    tim.init(period=300, mode=Timer.ONE_SHOT, callback=call)


#Switch 2 interrupt
def call2(pin):
    global interrupt2
    interrupt2 = 1


def cancel_de2(pin):
    tim2.init(period=300, mode=Timer.ONE_SHOT, callback=call2)


tim = Timer(1)
tim2 = Timer(2)
switch1.irq(trigger=Pin.IRQ_FALLING, handler=cancel_de)
switch2.irq(trigger=Pin.IRQ_FALLING, handler=cancel_de2)
i2c = I2C(scl=Pin(22), sda=Pin(23), freq=400000)
acc_id = list(i2c.scan())[1]
temp_id = list(i2c.scan())[0]


def initialize():
    addr_list = list(i2c.scan())
    acc_addr = i2c.readfrom_mem(addr_list[1], 0, 1)
    temp_addr = i2c.readfrom_mem(addr_list[0], 0x0b, 1)

    if acc_addr != b'\xe5':
        raise error('Wrong accelerometer device')
Ejemplo n.º 15
0
print('\n')


def http_get(url):
    import usocket
    _, _, host, path = url.split('/', 3)
    addr = usocket.getaddrinfo(host, 80)[0][-1]
    s = usocket.socket()
    s.connect(addr)
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host),
                 'utf8'))
    response = urequests.get('http://jsonplaceholder.typicode.com/albums/1')
    parsed = response.json()
    s.close()


def hardDispTime(timer):
    t = esp32.raw_temperature()
    h = esp32.hall_sensor()
    print("temperature (°F): " + str(t))
    print("hall sensor: " + str(h))

    base_url = 'https://api.thingspeak.com/update'
    API_key = '?api_key=R1N8YAFNXLY6MMWM'
    fieldanddata = "&field1=" + str(t) + "&field2=" + str(h)
    url = base_url + API_key + fieldanddata
    http_get(url)


hardTimer = Timer(0)
hardTimer.init(period=10000, mode=Timer.PERIODIC, callback=hardDispTime)
Ejemplo n.º 16
0
    datetime = rtc.datetime()  # 获取当前时间

    oled.fill(0)  # 清屏显示黑色背景
    oled.text('01Studio', 0, 0)  # 首行显示01Studio
    oled.text('RTC Clock', 0, 15)  # 次行显示实验名称

    # 显示日期,字符串可以直接用“+”来连接
    oled.text(
        str(datetime[0]) + '-' + str(datetime[1]) + '-' + str(datetime[2]) +
        ' ' + week[datetime[3]], 0, 40)

    # 显示时间需要判断时、分、秒的值否小于10,如果小于10,则在显示前面补“0”以达
    # 到较佳的显示效果
    for i in range(4, 7):
        if datetime[i] < 10:
            time_list[i - 4] = "0"
        else:
            time_list[i - 4] = ""

    # 显示时间
    oled.text(
        time_list[0] + str(datetime[4]) + ':' + time_list[1] +
        str(datetime[5]) + ':' + time_list[2] + str(datetime[6]), 0, 55)
    oled.show()


#开启RTOS定时器
tim = Timer(-1)
tim.init(period=300, mode=Timer.PERIODIC, callback=RTC_Run)  #周期300ms
Ejemplo n.º 17
0
#app_eui = ubinascii.unhexlify('70B3D57ED0028A4F')
#app_key = ubinascii.unhexlify('88397B010F71D34BEDF77DA003C3A54C')

# create an OTAA authentication parameters for no ring lopy
#dev address = 260125A9
#dev_eui = ubinascii.unhexlify('70B3D54990435DFE') # these settings can be found from TTN
#app_eui = ubinascii.unhexlify('70B3D57ED0028A4F')
#app_key = ubinascii.unhexlify('CE46C01958A612D102F0D106AB415862')

# join a network using OTAA (Over the Air Activation)
if not lora.has_joined():
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
    pycom.rgbled(green)
    time.sleep(2.5)

handshk_time = Timer.Chrono()
handshk_time.start()
# wait until the module has joined the network
while not lora.has_joined():
    pycom.rgbled(off)
    time.sleep(0.1)
    pycom.rgbled(red)
    time.sleep(2.4)
    print('Not yet joined...')

lora.nvram_save()
handshk_time.stop()
print("Total handshake time: {0}".format(handshk_time.read()))
print('Joined!')
pycom.rgbled(blue)
print(binascii.hexlify(lora.mac()).upper().decode('utf-8'))
Ejemplo n.º 18
0
 def __init__(self, np, NEOPIXEL_COUNT):
     super(Fader, self).__init__()
     self.step = 0
     self.np = np
     self.NEOPIXEL_COUNT = NEOPIXEL_COUNT
     self.tim = Timer(-1)
Ejemplo n.º 19
0
#引入相关模块
from machine import Pin, I2C, Timer
from ssd1306 import SSD1306_I2C
import dht, time

#初始化相关模块
i2c = I2C(sda=Pin(13), scl=Pin(14))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)

#创建DTH11对象
d = dht.DHT11(Pin(5))  #传感器连接到引脚14
time.sleep(1)  #首次启动停顿1秒让传感器稳定


def dht_get(tim):

    d.measure()  #温湿度采集

    #OLED显示温湿度
    oled.fill(0)  #清屏背景黑色
    oled.text('01Studio', 0, 0)
    oled.text('DHT11 test:', 0, 15)
    oled.text(str(d.temperature()) + ' C', 0, 40)  #温度显示
    oled.text(str(d.humidity()) + ' %', 48, 40)  #湿度显示
    oled.show()


#开启RTOS定时器,编号为-1
tim = Timer(-1)
tim.init(period=2000, mode=Timer.PERIODIC, callback=dht_get)  #周期为2000ms
Ejemplo n.º 20
0
# ######################### #
# 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()))
Ejemplo n.º 21
0
class CStat:
    def __init__(self):
        self.url = 'https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats?country=Ukraine'
        self.x_rapidapi_key = ''  # modify this line
        self.ssid = ''  # modify this line
        self.password = ''  # modify this line

        self.confirmed = 0
        self.recovered = 0
        self.deaths = 0
        self.updated = ''

        self.display = self.tim = None

        i2c = I2C(-1, Pin(5), Pin(4))
        self.display = ssd1306.SSD1306_I2C(128, 32, i2c)
        self.display.fill(0)
        self.display.text('Connecting...', 1, 1, 1)
        self.display.show()

        self.tim = Timer(-1)
        self.do_connect()

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

    def parse_country_data(self, json):
        self.confirmed = json['data']['covid19Stats'][0]['confirmed']
        self.recovered = json['data']['covid19Stats'][0]['recovered']
        self.deaths = json['data']['covid19Stats'][0]['deaths']
        self.updated = json['data']['covid19Stats'][0]['lastUpdate']

    def grab_api_data(self):
        headers = {
            'content-type': 'application/json',
            'x-rapidapi-host': 'covid-19-coronavirus-statistics.p.rapidapi.com',
            'x-rapidapi-key': self.x_rapidapi_key
        }
        resp = urequests.get(self.url, headers=headers)

        if resp.status_code is 200:
            self.parse_country_data(resp.json())
        else:
            print('Sorry, cannot connect')
            print(resp.status_code)
            print(resp.text)

    def display_results(self):
        self.display.fill(0)
        self.display.text(self.updated, 1, 1, 1)

        self.display.text('A' + str(self.confirmed), 1, 10, 1)
        self.display.text('R' + str(self.recovered), 50, 10, 1)
        self.display.text('D' + str(self.deaths), 90, 10, 1)

        self.display.show()

    def grab_data(self):
        try:
            print('update function called')
            self.grab_api_data()
            self.display_results()
            gc.collect()
        except Exception as e:
            print(e)

    def start(self):
        self.grab_data()
        self.tim.init(period=60000, mode=Timer.PERIODIC, callback=lambda f: self.grab_data())
Ejemplo n.º 22
0
import utime
from machine import Timer


t1 = Timer(0, 10)
t2 = Timer(1, 3)
t1.callback(lambda t: print(t, "tick1"))
t2.callback(lambda t: print(t, "tick2"))

utime.sleep(3)
print("done")
Ejemplo n.º 23
0
'''
实验名称:定时器
版本:v1.0
日期:2019.7
作者:01Studio
说明:通过定时器让LED周期性每秒闪烁1次
'''
from machine import Pin, Timer

led = Pin(2, Pin.OUT)
Counter = 0
Fun_Num = 0


def fun(tim):

    global Counter
    Counter = Counter + 1
    print(Counter)
    led.value(Counter % 2)


#开启RTOS定时器,编号为-1
tim = Timer(-1)
tim.init(period=1000, mode=Timer.PERIODIC, callback=fun)  #周期为1000ms
Ejemplo n.º 24
0
# connect to WiFi
wifi = WLAN(mode=WLAN.STA)
wifi.connect(WIFI_SSID, auth=WIFI_AUTH, timeout=5000)
while not wifi.isconnected():
    pass

print('IP address:', wifi.ifconfig()[0])

# assign GP9, GP10, GP11, GP24 to alternate function (PWM)
p9 = Pin('GP9', mode=Pin.ALT, alt=3)
p10 = Pin('GP10', mode=Pin.ALT, alt=3)
p11 = Pin('GP11', mode=Pin.ALT, alt=3)
p24 = Pin('GP24', mode=Pin.ALT, alt=5)

# timer in PWM mode and width must be 16 buts
timer10 = Timer(4, mode=Timer.PWM, width=16)
timer9 = Timer(3, mode=Timer.PWM, width=16)
timer1 = Timer(1, mode=Timer.PWM, width=16)

# enable channels @1KHz with a 50% duty cycle
pwm9 = timer9.channel(Timer.B, freq=700, duty_cycle=100)
pwm10 = timer10.channel(Timer.A, freq=700, duty_cycle=100)
pwm11 = timer10.channel(Timer.B, freq=700, duty_cycle=100)
pwm24 = timer1.channel(Timer.A, freq=700, duty_cycle=100)


def v3_write_handler(value):
    pwm9.duty_cycle(int(value))
	
def v4_write_handler(value):
    pwm10.duty_cycle(int(value))
Ejemplo n.º 25
0
class Encoder(object):
    '''
    编码器对象
    '''
    def __init__(self,
                 gpio_a,
                 gpio_b,
                 timer_id,
                 name='RightEncoder',
                 motor_install_dir=True,
                 is_debug=False):

        # 设置编码器的名称
        self.name = name
        # 根据电机安装方向,设置AB相Pin
        if motor_install_dir:
            self.pin_a = Pin(gpio_a)
            self.pin_b = Pin(gpio_b)
        else:
            self.pin_a = Pin(gpio_b)
            self.pin_b = Pin(gpio_a)

        # 最近一次A相的电平
        self.last_a = 0
        # 最近一次B相的电平
        self.last_b = 0
        # 新的A相电平
        self.new_a = 0
        # 新的B相电平
        self.new_b = 0
        # 定时器计数
        self.count = 0
        # 定时器
        self.timer = Timer(timer_id)
        # 定时器 每1ms执行一次
        self.timer.init(period=1, mode=Timer.PERIODIC, callback=self.callback)

        # 是否开启Debug模式
        self.is_debug = is_debug

    def callback(self, timer):
        '''
        回调函数
        '''
        # 更新A相电平
        self.new_a = self.pin_a.value()
        # 更新B相电平
        self.new_b = self.pin_b.value()

        if not self.last_a and self.new_a:
            # 检测到编码器A相上升沿 RISING
            if self.new_b:
                self.count += 1
            else:
                self.count -= 1
        elif self.last_a and not self.new_a:
            # 检测到编码器A相下降沿 FALLING
            if self.new_b:
                self.count -= 1
            else:
                self.count += 1
        elif not self.last_b and self.new_b:
            # 检测到编码器B相上升沿 RASING
            if self.new_a:
                self.count -= 1
            else:
                self.count += 1
        elif self.last_b and not self.new_b:
            # 检测到编码器B相下降沿 FALLING
            if self.new_a:
                self.count += 1
            else:
                self.count -= 1

        # 更新电平历史
        self.last_a = self.new_a
        self.last_b = self.new_b

        if self.is_debug:
            # 打印计数器信息
            print('{} Counter: {}'.format(self.name, self.count))
Ejemplo n.º 26
0
tof.set_Vcsel_pulse_period(tof.vcsel_period_type[0], 18)
tof.set_Vcsel_pulse_period(tof.vcsel_period_type[1], 14)

tof.start()

# Blinker
led = Pin(2, Pin.OUT)

# Main button.
btn = Pin(BTN, Pin.IN, Pin.PULL_DOWN)

###############
# Calibration
###############

de_bnc_tmr = Timer(DE_BNC_TMR)
de_bnc_flag = False
def dnc_timer_expr(timer):
    global de_bnc_flag
    de_bnc_flag = False

def on_btn(pin):
    global tof
    global de_bnc_flag
    global cali_file
    global btn_state
    global btn
    global led

    if not de_bnc_flag:
        # Turn on debounce timer.
Ejemplo n.º 27
0
'''
# file pub_sub_with_timer.py
# brief         Set 'SERVER','CLIENT_ID'(this can be null),'IOT_pubTopic','IOT_UserName','IOT_PassWord'
#               download into mpython and run the file
#               You will send the message by seconds and receive the message from server
# Copyright     Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
# licence       The MIT License (MIT)
# author        [LuoYufeng]([email protected])
# version       V1.0
# date          2019-10-8
'''
from siot import iot
from machine import Timer
import time
SERVER = "192.168.2.107"  #MQTT服务器IP
CLIENT_ID = ""  #在SIoT上,CLIENT_ID可以留空
IOT_pubTopic = 'xzr/001'  #“topic”为“项目名称/设备名称”
IOT_UserName = '******'  #用户名
IOT_PassWord = '******'  #密码
siot = iot(CLIENT_ID, SERVER, user=IOT_UserName, password=IOT_PassWord)

def WIFIconnect():
    import network
    ssid = "dfrobotYanfa"
    password = "******"
    station = network.WLAN(network.STA_IF)
    if station.isconnected() == True:
        print("Wifi already connected")
        return
    station.active(True)
Ejemplo n.º 28
0
from machine import WDT
from machine import Timer
import utime
import checkNet


'''
下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值,
在执行用户代码前,会先打印这两个变量的值。
'''
PROJECT_NAME = "QuecPython_WDT_example"
PROJECT_VERSION = "1.0.0"

checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION)

timer1 = Timer(Timer.Timer1)

def feed(t):
    wdt.feed()


if __name__ == '__main__':
    '''
    手动运行本例程时,可以去掉该延时,如果将例程文件名改为main.py,希望开机自动运行时,需要加上该延时,
    否则无法从CDC口看到下面的 poweron_print_once() 中打印的信息
    '''
    utime.sleep(5)
    checknet.poweron_print_once()
    '''
    如果用户程序包含网络相关代码,必须执行 wait_network_connected() 等待网络就绪(拨号成功);
    如果是网络无关代码,可以屏蔽 wait_network_connected()
Ejemplo n.º 29
0
class Runner:
    def __init__(self, stimulus_freqs=None) -> None:
        if stimulus_freqs is None:
            self.stim_freqs = config.STIM_FREQS  # assign defaults

        self.base_sample_freq = config.ADC_SAMPLE_FREQ
        self.downsampled_freq = config.DOWNSAMPLED_FREQ

        self.preprocessing_enabled = config.PREPROCESSING

        if self.preprocessing_enabled:
            self.downsampled_freq = config.DOWNSAMPLED_FREQ

        self.sample_counter = 0
        self.buffer_size = 256  # TODO: update this to be populated dynamically

        self.output_buffer = [0.0 for i in range(self.buffer_size)]
        self.decoded_output = {}

        self.is_setup = False
        self.is_sampling = False
        self.is_logging = False

    def setup(self,
              spi_params=None,
              adc_params=None,
              log_period=5,
              logger_type=None):
        from machine import freq

        freq(config.BASE_CLK_FREQ)  # set the CPU frequency

        self._init_decoder()
        gc.collect()

        self._init_peripherals(spi_params, adc_params)
        gc.collect()

        self._setup_logger(log_period, logger_type)
        gc.collect()

        self.is_setup = True

    def run(self):
        if not self.is_setup:
            raise ValueError(
                "Runner not setup. Call `.setup()` before running.")

        self.start_sample_timer()

        if self.logger is not None:
            self.start_logger()

    def stop(self):
        if self.is_sampling:
            self.stop_sample_timer()

        if self.is_logging:
            self.stop_logger()

    def preprocess_data(self, signal):
        """Preprocess incoming signal before decoding algorithms.
        This involves applying a bandpass filter to isolate the target SSVEP range
        and then downsampling the signal to the Nyquist boundary.

        Returns:
            [np.ndarray]: filtered and downsampled signal
        """
        from lib.signal import sos_filter

        ds_factor = self.downsampling_factor
        signal = np.array(signal) - np.mean(signal)  # remove DC component

        # downsample filtered signal by only selecting every `ds_factor` sample
        return sos_filter(signal, fs=self.base_sample_freq)[::ds_factor]

    def decode(self, *args):
        """
        Run decoding on current state of output buffer.

        Note that `*args` is specified but not used directly: this allows
        this function to be called using `micropython.schedule` which
        requires the scheduled func to accept an argument.
        """
        data = np.array(self.output_buffer)
        data = data.reshape((1, len(data)))  # reshape to row vector
        gc.collect()

        result = self.decoder.compute_corr(data)

        # note: need to be careful not to change the memory address of this variable using direct
        # assignment since the logger depends on this reference. Also would just be inefficient.
        self.decoded_output.update(
            {freq: round(corr[0], 5)
             for freq, corr in result.items()})
        gc.collect()
        return self.decoded_output

    def sample_callback(self, *args, **kwargs):
        from lib.utils import update_buffer

        self.periph_manager.adc_read_to_buff(size=1)
        self.sample_counter += 1

        # this will only be true every 1s once buffer fills
        if self.sample_counter >= self.buffer_size:
            self.periph_manager.write_led("red", 1)
            data = self._read_internal_buffer(
                preprocess=self.preprocessing_enabled)
            update_buffer(self.output_buffer,
                          list(data),
                          self.buffer_size,
                          inplace=True)
            self.sample_counter = 0
            self.periph_manager.write_led("red", 0)

            # TODO: workout how to run decoding in another handler as
            # this could take a non-negligible amount of time which
            # would disrupt consistency of sampling freq. For now,
            # we can schedule this function to run 'soon' while allowing other
            # ISRs to interrupt it if need be.
            try:
                schedule(self.decode, None)
            except RuntimeError:
                # if schedule queue is full, run now
                self.decode()

    def read_output_buffer(self):
        return self.output_buffer

    def start_logger(self):
        if self.logger is not None:
            self.logger.start()
            self.is_logging = True

    def stop_logger(self):
        if self.logger is not None:
            self.logger.stop()
            self.is_logging = False

    def start_sample_timer(self):
        from machine import Timer

        self.sample_timer = Timer(0)
        self.sample_timer.init(freq=self.base_sample_freq,
                               callback=self.sample_callback)
        self.is_sampling = True

    def stop_sample_timer(self):
        if self.sample_timer is not None:
            self.sample_timer.deinit()
            self.is_sampling = False

    @property
    def downsampling_factor(self):
        return self.base_sample_freq // self.downsampled_freq

    def _read_internal_buffer(self, preprocess=False):
        data = self.periph_manager.read_adc_buffer()
        if preprocess and len(data) > 1:
            data = self.preprocess_data(data)
        return data

    def _init_peripherals(self, spi_params, adc_params):

        self.periph_manager = PeripheralManager(spi_params=spi_params,
                                                adc_params=adc_params)
        self.periph_manager.init()

    def _init_decoder(self):
        from lib.decoding import CCA

        # note: downsampled_freq is same as base sampling freq if
        # preprocessing is disabled
        self.decoder = CCA(self.stim_freqs, self.downsampled_freq)

    def _setup_logger(self, log_period, logger_type):
        if logger_type is not None:
            if logger_type != logger_types.SERIAL:
                print(
                    "Warning: only the `SERIAL` logger type is available offline. Defaulting to this."
                )
            self.logger = BaseLogger(log_period, self.decoded_output,
                                     self.output_buffer)
        else:
            self.logger = None
Ejemplo n.º 30
0
class osd:
  def __init__(self):
    self.screen_x = const(64)
    self.screen_y = const(20)
    self.cwd = "/"
    self.init_fb()
    self.exp_names = " KMGTE"
    self.mark = bytearray([32,16,42]) # space, right triangle, asterisk
    self.read_dir()
    self.spi_read_irq = bytearray([1,0xF1,0,0,0,0,0])
    self.spi_read_btn = bytearray([1,0xFB,0,0,0,0,0])
    self.spi_result = bytearray(7)
    self.spi_enable_osd = bytearray([0,0xFE,0,0,0,1])
    self.spi_write_osd = bytearray([0,0xFD,0,0,0])
    self.spi_channel = const(2)
    self.spi_freq = const(3000000)
    self.init_pinout_sd()
    #self.spi=SPI(self.spi_channel, baudrate=self.spi_freq, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=Pin(self.gpio_sck), mosi=Pin(self.gpio_mosi), miso=Pin(self.gpio_miso))
    self.init_spi()
    alloc_emergency_exception_buf(100)
    self.enable = bytearray(1)
    self.timer = Timer(3)
    self.irq_handler(0)
    self.irq_handler_ref = self.irq_handler # allocation happens here
    self.spi_request = Pin(0, Pin.IN, Pin.PULL_UP)
    self.spi_request.irq(trigger=Pin.IRQ_FALLING, handler=self.irq_handler_ref)

  def init_spi(self):
    self.spi=SPI(self.spi_channel, baudrate=self.spi_freq, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=Pin(self.gpio_sck), mosi=Pin(self.gpio_mosi), miso=Pin(self.gpio_miso))
    self.cs=Pin(self.gpio_cs,Pin.OUT)
    self.cs.off()

# init file browser
  def init_fb(self):
    self.fb_topitem = 0
    self.fb_cursor = 0
    self.fb_selected = -1

  @micropython.viper
  def init_pinout_sd(self):
    self.gpio_cs   = const(5)
    self.gpio_sck  = const(16)
    self.gpio_mosi = const(4)
    self.gpio_miso = const(12)

  @micropython.viper
  def irq_handler(self, pin):
    p8result = ptr8(addressof(self.spi_result))
    self.cs.on()
    self.spi.write_readinto(self.spi_read_irq, self.spi_result)
    self.cs.off()
    btn_irq = p8result[6]
    if btn_irq&0x80: # btn event IRQ flag
      self.cs.on()
      self.spi.write_readinto(self.spi_read_btn, self.spi_result)
      self.cs.off()
      btn = p8result[6]
      p8enable = ptr8(addressof(self.enable))
      if p8enable[0]&2: # wait to release all BTNs
        if btn==1:
          p8enable[0]&=1 # clear bit that waits for all BTNs released
      else: # all BTNs released
        if (btn&0x78)==0x78: # all cursor BTNs pressed at the same time
          self.show_dir() # refresh directory
          p8enable[0]=(p8enable[0]^1)|2;
          self.osd_enable(p8enable[0]&1)
        if p8enable[0]==1:
          if btn==9: # btn3 cursor up
            self.start_autorepeat(-1)
          if btn==17: # btn4 cursor down
            self.start_autorepeat(1)
          if btn==1:
            self.timer.deinit() # stop autorepeat
          if btn==33: # btn6 cursor left
            self.updir()
          if btn==65: # btn6 cursor right
            self.select_entry()

  def start_autorepeat(self, i:int):
    self.autorepeat_direction=i
    self.move_dir_cursor(i)
    self.timer_slow=1
    self.timer.init(mode=Timer.PERIODIC, period=500, callback=self.autorepeat)

  def autorepeat(self, timer):
    if self.timer_slow:
      self.timer_slow=0
      self.timer.init(mode=Timer.PERIODIC, period=30, callback=self.autorepeat)
    self.move_dir_cursor(self.autorepeat_direction)
    self.irq_handler(0) # catch stale IRQ

  def select_entry(self):
    if self.direntries[self.fb_cursor][1]: # is it directory
      oldselected = self.fb_selected - self.fb_topitem
      self.fb_selected = self.fb_cursor
      try:
        self.cwd = self.fullpath(self.direntries[self.fb_cursor][0])
      except:
        self.fb_selected = -1
      self.show_dir_line(oldselected)
      self.show_dir_line(self.fb_cursor - self.fb_topitem)
      self.init_fb()
      self.read_dir()
      self.show_dir()
    else:
      self.change_file()

  def updir(self):
    if len(self.cwd) < 2:
      self.cwd = "/"
    else:
      s = self.cwd.split("/")[:-1]
      self.cwd = ""
      for name in s:
        if len(name) > 0:
          self.cwd += "/"+name
    self.init_fb()
    self.read_dir()
    self.show_dir()

  def fullpath(self,fname):
    if self.cwd.endswith("/"):
      return self.cwd+fname
    else:
      return self.cwd+"/"+fname

  def change_file(self):
    oldselected = self.fb_selected - self.fb_topitem
    self.fb_selected = self.fb_cursor
    try:
      filename = self.fullpath(self.direntries[self.fb_cursor][0])
    except:
      filename = False
      self.fb_selected = -1
    self.show_dir_line(oldselected)
    self.show_dir_line(self.fb_cursor - self.fb_topitem)
    if filename:
      if filename.endswith(".bit"):
        self.spi_request.irq(handler=None)
        self.timer.deinit()
        self.enable[0]=0
        self.osd_enable(0)
        self.spi.deinit()
        tap=ecp5.ecp5()
        tap.prog_stream(open(filename,"rb"),blocksize=1024)
        if filename.endswith("_sd.bit"):
          os.umount("/sd")
          for i in bytearray([2,4,12,13,14,15]):
            p=Pin(i,Pin.IN)
            a=p.value()
            del p,a
        result=tap.prog_close()
        del tap
        gc.collect()
        #os.mount(SDCard(slot=3),"/sd") # BUG, won't work
        self.init_spi() # because of ecp5.prog() spi.deinit()
        self.spi_request.irq(trigger=Pin.IRQ_FALLING, handler=self.irq_handler_ref)
        self.irq_handler(0) # handle stuck IRQ
      if filename.endswith(".z80"):
        self.enable[0]=0
        self.osd_enable(0)
        import ld_zxspectrum
        s=ld_zxspectrum.ld_zxspectrum(self.spi,self.cs)
        s.loadz80(filename)
        del s
        gc.collect()
      if filename.endswith(".nes"):
        import ld_zxspectrum
        s=ld_zxspectrum.ld_zxspectrum(self.spi,self.cs)
        s.ctrl(1)
        s.ctrl(0)
        s.load_stream(open(filename,"rb"),addr=0,maxlen=0x101000)
        del s
        gc.collect()
        self.enable[0]=0
        self.osd_enable(0)
      if filename.endswith(".ora") or filename.endswith(".orao"):
        self.enable[0]=0
        self.osd_enable(0)
        import ld_orao
        s=ld_orao.ld_orao(self.spi,self.cs)
        s.loadorao(filename)
        del s
        gc.collect()
      if filename.endswith(".vsf"):
        self.enable[0]=0
        self.osd_enable(0)
        import ld_vic20
        s=ld_vic20.ld_vic20(self.spi,self.cs)
        s.loadvsf(filename)
        del s
        gc.collect()
      if filename.endswith(".prg"):
        self.enable[0]=0
        self.osd_enable(0)
        import ld_vic20
        s=ld_vic20.ld_vic20(self.spi,self.cs)
        s.loadprg(filename)
        del s
        gc.collect()

  @micropython.viper
  def osd_enable(self, en:int):
    pena = ptr8(addressof(self.spi_enable_osd))
    pena[5] = en&1
    self.cs.on()
    self.spi.write(self.spi_enable_osd)
    self.cs.off()

  @micropython.viper
  def osd_print(self, x:int, y:int, i:int, text):
    p8msg=ptr8(addressof(self.spi_write_osd))
    a=0xF000+(x&63)+((y&31)<<6)
    p8msg[2]=i
    p8msg[3]=a>>8
    p8msg[4]=a
    self.cs.on()
    self.spi.write(self.spi_write_osd)
    self.spi.write(text)
    self.cs.off()

  @micropython.viper
  def osd_cls(self):
    p8msg=ptr8(addressof(self.spi_write_osd))
    p8msg[3]=0xF0
    p8msg[4]=0
    self.cs.on()
    self.spi.write(self.spi_write_osd)
    self.spi.read(1280,32)
    self.cs.off()

  # y is actual line on the screen
  def show_dir_line(self, y):
    if y < 0 or y >= self.screen_y:
      return
    mark = 0
    invert = 0
    if y == self.fb_cursor - self.fb_topitem:
      mark = 1
      invert = 1
    if y == self.fb_selected - self.fb_topitem:
      mark = 2
    i = y+self.fb_topitem
    if i >= len(self.direntries):
      self.osd_print(0,y,0,"%64s" % "")
      return
    if self.direntries[i][1]: # directory
      self.osd_print(0,y,invert,"%c%-57s     D" % (self.mark[mark],self.direntries[i][0]))
    else: # file
      mantissa = self.direntries[i][2]
      exponent = 0
      while mantissa >= 1024:
        mantissa >>= 10
        exponent += 1
      self.osd_print(0,y,invert,"%c%-57s %4d%c" % (self.mark[mark],self.direntries[i][0], mantissa, self.exp_names[exponent]))

  def show_dir(self):
    for i in range(self.screen_y):
      self.show_dir_line(i)

  def move_dir_cursor(self, step):
    oldcursor = self.fb_cursor
    if step == 1:
      if self.fb_cursor < len(self.direntries)-1:
        self.fb_cursor += 1
    if step == -1:
      if self.fb_cursor > 0:
        self.fb_cursor -= 1
    if oldcursor != self.fb_cursor:
      screen_line = self.fb_cursor - self.fb_topitem
      if screen_line >= 0 and screen_line < self.screen_y: # move cursor inside screen, no scroll
        self.show_dir_line(oldcursor - self.fb_topitem) # no highlight
        self.show_dir_line(screen_line) # highlight
      else: # scroll
        if screen_line < 0: # cursor going up
          screen_line = 0
          if self.fb_topitem > 0:
            self.fb_topitem -= 1
            self.show_dir()
        else: # cursor going down
          screen_line = self.screen_y-1
          if self.fb_topitem+self.screen_y < len(self.direntries):
            self.fb_topitem += 1
            self.show_dir()

  def read_dir(self):
    self.direntries = []
    ls = sorted(os.listdir(self.cwd))
    for fname in ls:
      stat = os.stat(self.fullpath(fname))
      if stat[0] & 0o170000 == 0o040000:
        self.direntries.append([fname,1,0]) # directory
      else:
        self.direntries.append([fname,0,stat[6]]) # file
      gc.collect()
Ejemplo n.º 31
0
class Bot(object):
    "Class to handle all Bot board peripherals."

    def __init__(self,
                 status_update_timer=0,
                 status_update_rate=1000,
                 use_cbots=False):
        "Initialise all peripherals."

        # momentary switches on the board
        self.boot_sw = Switch(BOOT_PIN)
        self.user_sw = Switch(USER_PIN)

        # init the tft and display splash screen
        self.tft = Tft(BACKLIGHT_PIN)
        self.tft.init(self.tft.GENERIC,
                      width=TFT_WIDTH,
                      height=TFT_HEIGHT,
                      miso=MISO,
                      mosi=MOSI,
                      clk=CLK,
                      cs=CS,
                      dc=22,
                      color_bits=16)
        self.tft.image(0, 0, SPLASH_JPG)

        # init battery voltage measurement
        self.battery = Battery(BATTERY_SENSE)

        # init i2c
        self.i2c = I2C(0, sda=I2C_SDA, scl=I2C_SCL, speed=1000000)
        self.servo = Servo(self.i2c)

        # set wlan to be none at first
        self.wlan = None

        # setup periodic timer for status image updating
        self.display_status_image()
        self.status_tm = Timer(status_update_timer)
        self.status_tm.init(
            period=status_update_rate,
            mode=self.status_tm.PERIODIC,
            callback=lambda timer: self.update_display_status())

        if use_cbots:
            self.setup_cbots()

    def setup_cbots(self):
        "Setup required configuration for use of cbots library."
        if not CBOTS_LOADED:
            raise ValueError(
                "cbots_used set to true but cbots library was not found.")

        # tell them the i2c object we are using
        cbots.set_i2c(self.i2c)

        # set the servo calibration
        cbots.set_servo_zero_pos(self.servo.zero_pos)

        # change our write servo function to be the c implementations
        self.servo.get_all = cbots.servo_get_all
        self.servo.get_rad = cbots.servo_get_rad
        self.servo.get_deg = cbots.servo_get_deg
        self.servo.set_deg_raw = cbots.servo_set_deg_raw
        self.servo.set_rad_raw = cbots.servo_set_rad_raw
        self.servo.set_rad = cbots.servo_set_rad
        self.servo.set_deg = cbots.servo_set_deg

    def set_wlan(self, wlan):
        # save the ap object for later if we want to display the status
        self.wlan = wlan

    def display_status_image(self):
        self.tft.image(0, 0, STATUS_JPG)

    def update_display_status(self):
        "Show the status of the bot on the TFT display."

        # show battery, red indicates low voltage cutoff for 2S
        batt = self.battery.read()
        if batt < LVC:
            col = self.tft.RED
        else:
            col = self.tft.GREEN
        self.tft.text(25, 40, "BATT " + str(batt) + "V  ", color=col)

        # show wlan status
        if self.wlan is None:
            self.tft.text(25, 55, "IP     NO CONNECT", color=self.tft.RED)
        else:
            self.tft.text(25,
                          55,
                          "IP     " + str(self.wlan.ifconfig()[0]),
                          color=self.tft.GREEN)

    def deinit(self):
        "Deinit all peripherals."
        self.battery.deinit()
        self.servo.deinit()
        self.i2c.deinit()
        self.tft.deinit()
        self.boot_sw.deinit()
        self.user_sw.deinit()
        self.status_tm.deinit()

    def __del__(self):
        self.deinit()
Ejemplo n.º 32
0
from machine import Pin, Timer, PWM
pwm = PWM(Pin(2), 100)  #create PWM object from a pin,and set frequency
polar = 0
duty = 0


def setLed(t):  #create a variate,and change it between 0 and 1008
    global duty, polar
    if (polar == 0):
        duty += 16
        if (duty >= 1008):
            polar = 1
    else:
        duty -= 16
        if (duty <= 0):
            polar = 0
    pwm.duty(duty)  #set duty of the PWM


tim = Timer(1)  #create Timer object from Virtual timers with timer ID=1
tim.init(
    period=10, mode=Timer.PERIODIC,
    callback=setLed)  #init Timer,Call the callback function with per second

try:  #The catching
    while True:
        pass
except:  #Capture anomaly, deinit Timer and PWM
    tim.deinit()
    pwm.deinit()
Ejemplo n.º 33
0
 def timerdata(self):
     tim = Timer(-1)
     tim.init(period=30000, mode=Timer.PERIODIC, callback=self.updata)
Ejemplo n.º 34
0
timezone_correction(3)

clock_string = '1234'
alarm_string = '1234'

button1_state = 0
button2_state = 0
snooze_state = 0

button1_start = 0
button2_start = 0
snooze_start = 0

dst_state = 1
clock_mode = 1

setting_state = 1

update_clock_string(1)

screen_refresh = Timer(0)

screen_refresh.init(period=10, mode=Timer.PERIODIC, callback=show_clock)

button_checker = Timer(3)

button_checker.init(period=100, mode=Timer.PERIODIC, callback=button_handler)

# button1_p.irq(handler=button_test, trigger=Pin.IRQ_RISING)
  -     Echo --> GPIO 15
  -     Trig --> GPIO 2
  -     Vcc  --> 3.3V
  - Wires
  - Breadboard

 Documentation:
 Timers: https://micropython-docs-esp32.readthedocs.io/en/esp32_doc/esp32/quickref.html#timers
 Pins and GPIO: https://micropython-docs-esp32.readthedocs.io/en/esp32_doc/esp32/quickref.html#pins-and-gpio
 HC-SR04 driver source: https://github.com/rsc1975/micropython-hcsr04
 
 Course:
 MicroPython with the ESP32
 https://techexplorations.com

'''

from machine import Pin, Timer
from hc_sr04 import HCSR04

sensor = HCSR04(trigger_pin=2, echo_pin=15, echo_timeout_us=1000000)


def hcrs04_isr(event):
    distance = sensor.distance_cm()
    print(distance)


blink_timer = Timer(1)
blink_timer.init(period=250, mode=Timer.PERIODIC, callback=hcrs04_isr)
Ejemplo n.º 36
0
        pack = ts.A.collect('switch', str(0))
    DataCache.append(pack)

uart = UART(2)
uart.init(9600, bits=8, parity=None, stop=1)
ts = ZW_Net(14, uart)

pmos.value(1)
ts.send('AT+CMEE=1')
last_time = utime.ticks_ms()
from  _thread import start_new_thread,allocate_lock
lock = allocate_lock()

start_new_thread(send_data,())

tim = Timer(0)
tim.init(period=10000, mode=Timer.PERIODIC, callback=lambda t: timetosend())

while True:

    if power_io.value() == False:
        pmos.value(1)
        for i in range(3):
            utime.sleep_ms(5000)
            Pack = ts.A.collect('error', '01')
            with lock:
                ts.sendto('219.222.189.98', '9954', Pack)
            print('error_____________________')
        pmos.value(0)
    if ts.is_setup >= 15:
        ts.state_index = 0
Ejemplo n.º 37
0
             color_bits=tft.COLOR_BITS16,
             splash=False,
             height=240)

    tft.tft_writecmd(ST7789_INVON)

    tft.clear(tft.NAVY)

    tft.image(0, 0, ICON_LOGO)
    width, height = tft.screensize()
    tft.rect(1, 1, width - 1, height - 1, tft.WHITE)

    Backlight = True
    backlight(Backlight)

    bl_timer = Timer(2)
    bl_timer.init(period=BL_OFF_TIME,
                  mode=bl_timer.ONE_SHOT,
                  callback=bl_timer_cb)

    # tft.font(tft.FONT_Tooney, rotate=0)
    # tft.text(tft.CENTER, tft.CENTER, "SoftRF", tft.WHITE, transparent=True)
    # sleep(3)
else:
    print("No TFT")

from sys import path, stdout
import network
import datetime

import bme280
Ejemplo n.º 38
0
Archivo: temp.py Proyecto: psy0rz/stuff
#         #     servosmall=max
#         # elif c=='d':
#         #     servosmall=min
#         if c=='t':
#             pid.setpoint=pid.setpoint+1
#         elif c=='g':
#             pid.setpoint=pid.setpoint-1
#
#         print(pid.setpoint)
#
#         # if servosmall<min:
#         #     servosmall=min
#         #
#         # if servosmall>max:
#         #     servosmall=max
#
#
#
#         # print("servosmall={}".format(servosmall))
#         # s.duty(servosmall)
#
#         # if c=='z':
#         #     print("SLEEP")
#         #     s.duty(0)


tim = Timer(-1)
tim.init(period=1000, mode=Timer.PERIODIC, callback=measure)

#ctrl()
Ejemplo n.º 39
0
class DAQ_Unit(object):
    def __init__(self):#, freqVal=10000, numpnts = 1000):
        if RDB.ping():
            self.daqDict = pullRedisJson(RDB, DAQPARAMKEY)
            gc.collect()
        else:
            self.daqDict = DAQPARAMS
        self.setDaqParams()
        self.curPos = 0
        self.setupADC()
        self.setupTimer()

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

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

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

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

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

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

    def _addData_(self, timer, saveData = False):
        self.dataArray[self.curPos] = self.adcPin()
        self.curPos+=1
        self.curPos%=self.numPnts#this value can ultimately help us with the number of aves.
        
    def writeData(self):
        t = time.time()
        curDir = os.getcwd()
        os.chdir("/sd")#change directory to SD card
        try:
            f = open(self.filePath, 'w')
            # json.dump(self.daqDict, f)#assumes the data has already been converted to a string-Redis doesn't like arrays
            f.write("%s\n"%self.dataID)
            f.write("%s\n"%str(self.numPnts))
            f.write("%s\n"%str(self.numAves))
            f.write("%s\n"%str(self.gpw))
            f.write("%s\n"%str(self.acqSpeed))
            f.write("%s\n"%str(self.freq))
            f.write("%s\n"%self.filePath)
            f.write("%s\n"%str(self.acqType))
            f.write("%s\n"%str(self.multiplexParam))
            for d in self.dataArray:
                f.write("%s,\n"%str(d))
            f.close()
            os.chdir(curDir)
        except:
            os.chdir(curDir)
            print("Saving to %s failed"%fileName)
        gc.collect()
        print("Write Time: %s"%(time.time()-t))
Ejemplo n.º 40
0
# GNU General Public License <https://www.gnu.org/licenses>
# STIA436 Course - Spring 2019
# Professor Colin McCormick & Father Chris Wagner
# Copyright (c) 2019 F. Pascal Girard
#
import machine, utime
from machine import Pin, Signal, Timer
"""
# ESP32 Code - see below
# from machine import TouchPad
pad = TouchPad(Pin(14))
"""

timer = Timer(0)
upgrade = False

print('Running main')

def callback(pin):
	global upgrade
	upgrade = True
	return(upgrade)

def run(timer):
	if not upgrade:
		print('Running sensors...')
		import wake
		wake.main()	
	else:
		print('Upgrading...')
		import webrepl, iot
Ejemplo n.º 41
0
from time import sleep_us, sleep_ms
from machine import Timer
from pyb import Pin

LED_BUILDIN = 16
p = Pin(LED_BUILDIN, Pin.OUT)

def count():
    for i in range(5):
        print(i)
        sleep_ms(100)

def breath():
    Brightness = 90
    Inhale = 800
    Pulse = Inhale*1000/Brightness
    for i in range(Brightness):
        p.low()
        sleep_us(i*10)
        p.high()
        sleep_us(int(Pulse) - i*10)
    for i in range(Brightness, 0, -1):
        p.low()
        sleep_us(i*10)
        p.high()
        sleep_us(int(Pulse) - i*10)

tim = Timer(0)
# tim.init(period=500, mode=Timer.PERIODIC, callback=lambda t:count())
tim.init(period=3000, mode=Timer.PERIODIC, callback=lambda t:breath())
#
Ejemplo n.º 42
0
from util.colors import *
from util.pinout import set_pinout
from util.io_config import get_from_file

pinout = set_pinout()  # set board pinout
rtc = RTC()  # real time
io_conf = get_from_file()  # read configuration for peripherals

# I2C address:
LCD_ADDR = 0x27
OLED_ADDR = 0x3c

if Env.isTimer:
    from machine import Timer
    tim1 = Timer(0)


# -------------------------------- common terminal function ---------------
def getVer():
    return "octopusLAB - lib.version: " + Env.ver + " > " + Env.verDat


def get_eui():
    return Env.uID  #mac2eui(id)


def printInfo(w=Env.TW):
    print('-' * w)
    print("| ESP UID: " + Env.uID + " | RAM free: " + str(getFree()) + " | " +
          get_hhmm())
Ejemplo n.º 43
0
from pyb import Pin
from time import sleep_ms, sleep_us, ticks_us
from machine import Timer

D5 = Pin(14, Pin.OUT)
D6 = Pin(12, Pin.IN)
Trig = D5
Echo = D6

def measure():
    Trig.low()
    sleep_us(15)
    Trig.high()
    sleep_us(15)
    Trig.low()
    while(Echo.value() == 0):
        start = ticks_us()
    while(Echo.value() == 1):
        end = ticks_us()
    duration = end - start
    dist = 0.03435 * 0.5 * duration
    print("duration: " + str(duration) + ", " + \
          "distance: " + str(dist))
    return dist

tim = Timer(0)
tim.deinit()
tim.init(period=200, mode=Timer.PERIODIC, callback=lambda t:measure())
#
Ejemplo n.º 44
0
import machine, time
from machine import Pin, Timer
from ble_pendulo import BLEPendulo
import bluetooth

def interrupcao(timer):
    global tempos
    tempos.append(time.ticks_ms())

def debounce(pin):
    global timer               
    timer.init(mode=Timer.ONE_SHOT,period=200,callback=interrupcao)
    
timer = Timer(0)
tempos = []
periodos = []

p21 = Pin(21,Pin.IN,Pin.PULL_UP)
p21.irq(trigger=Pin.IRQ_RISING,handler=debounce)

b1 = bluetooth.BLE()
ble = BLEPendulo(b1)

while True:
    
    if len(tempos)==3:
        estado = machine.disable_irq()
        t0, tf = tempos[0], tempos[2]
        tempos.clear()
        tempos.append(tf)
        machine.enable_irq(estado)
Ejemplo n.º 45
0
from machine import Pin
from machine import Timer

rt = Timer(-1)
rt.deinit()  # turn off current timers

p0 = Pin(0, Pin.OUT)
p0.off()  # red light on

p2 = Pin(2, Pin.OUT)
p2.off()  # blue light on

p4 = Pin(4, Pin.IN, Pin.PULL_UP)  # p4 with internal pull resister
p5 = Pin(5, Pin.IN, Pin.PULL_UP)  # p5 with internal pull resister
# up is 1, down is 0  for the float switches

# for the relays
p13 = Pin(13, Pin.OUT)
p13.off()

p15 = Pin(15, Pin.OUT)
p15.off()

relay_1 = p13
relay_2 = p15

top_float_switch = p4
bottom_float_switch = p5

fresh_pump = p0
dirty_pump = p2
Ejemplo n.º 46
0
#disable heartbeat
#per - https://micropython.org/resources/docs/en/latest/wipy/library/machine.html
HeartBeat().disable()

#turn LED on
# (says v1.6, led works/HB is incorrect?) https://micropython.org/resources/docs/en/latest/wipy/wipy/tutorial/repl.html#linux
led = Pin('GP25', mode=Pin.OUT)
led(1)

#simple function to blink lamp
blink = lambda f:led.toggle()

#Much of 1.4.6 doc is just bad/does not match actual v1.4.6 WiPy firmware
#https://github.com/micropython/micropython/blob/v1.4.6/docs/pyboard/tutorial/timer.rst
#initialize a timer
tim = Timer(4) #1-14 exist; 3 is for internal use; avoid 5+6 (used for servo control or ADC/DAC)
tim.init(mode=Timer.PERIODIC)

#configure a timer 'channel'
tim_a = tim.channel( tim.A, freq=5) #less than 5per sec did not work

#add something useful to the running channel
tim_a.irq(handler=blink) #blinks strangely rapidly

#disable the timer 'channel'
tim_a = None #still blinking
#tim.deinit() #stopped, terminal froze.
tim.channel( tim.A, freq=5) #stopped blinking

#reinitialize, for a slower blink
tim.deinit()
Ejemplo n.º 47
0
                                   data_type="sensors",
                                   lora=lora)
    if gps_on:
        GPS_Events = EventScheduler(logger=status_logger,
                                    data_type="gps",
                                    lora=lora)

    status_logger.info("Initialisation finished")

    # Blink green three times to identify that the device has been initialised
    for val in range(3):
        blink_led((0x005500, 0.5, True))
        time.sleep(0.5)
    # Initialise custom yellow heartbeat that triggers every 5 seconds
    heartbeat = Timer.Alarm(blink_led,
                            s=5,
                            arg=(0x005500, 0.1, True),
                            periodic=True)

    # Try to update RTC module with accurate UTC datetime if GPS is enabled and has not yet synchronized
    if gps_on and update_time_later:
        # Start a new thread to update time from gps if available
        _thread.start_new_thread(GpsSIM28.get_time, (rtc, status_logger))

except Exception as e:
    status_logger.exception("Exception in the main")
    led_lock.acquire()
    pycom.rgbled(0x550000)
    while True:
        time.sleep(5)
Ejemplo n.º 48
0
        seg7(9,blue)
    elif i >= 60*8:
        seg7(8,green)
    elif i >= 60*7:
        seg7(7,blue)
    elif i >= 60*6:
        seg7(6,green)
    elif i >= 60*5:
        seg7(5,blue)
    elif i >= 60*4:
        seg7(4,bluegreen)
    elif i >= 60*3:
        seg7(3,green)
    elif i >= 60*2:
        seg7(2,yellow)
    elif i >= 60*1:
        seg7(1,purple)
    elif i > 0:
        seg7(0,red)
    else:
        seg7(0,red)
        buz.on() # 時間ぎれでブザー鳴る
        time.sleep(0.8)
        seg7(0,blank)
        buz.off()
        time.sleep(0.1)

i = t * 60
tim = Timer(-1)
tim.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:led()) # 1秒ごとに割り込み
Ejemplo n.º 49
0
# lv.log_register_print_cb(lv_h.log)
lv.log_register_print_cb(
    lambda level, path, line, msg: print('%s(%d): %s' % (path, line, msg)))

scr = lv.obj()
btn = lv.btn(scr)
btn.align(lv.scr_act(), lv.ALIGN.CENTER, 0, 0)
label = lv.label(btn)
label.set_text("Button")
label.set_size(20, 20)
lv.scr_load(scr)


def on_timer(timer):
    lv.tick_inc(5)


timer = Timer(Timer.TIMER0,
              Timer.CHANNEL0,
              mode=Timer.MODE_PERIODIC,
              period=5,
              unit=Timer.UNIT_MS,
              callback=on_timer,
              arg=None)

while True:
    tim = time.ticks_ms()
    lv.task_handler()
    while time.ticks_ms() - tim < 5:
        pass
Ejemplo n.º 50
0
import micropython
micropython.alloc_emergency_exception_buf(100)

from machine import UART
import os
uart = UART(0, baudrate=115200)
os.dupterm(uart)
print ('UART initialised')
#uart.irq(trigger=UART.RX_ANY, wake=machine.IDLE)
	
from machine import Pin
from machine import Timer

led_out = Pin('GP16', mode=Pin.OUT)
tim = Timer(1, mode=Timer.PERIODIC)
tim_a = tim.channel(Timer.A, freq=5)
# The slowest frequency the timer can run at is 5Hz
# so we divide the frequency down to toggle the LED
# BUT the callback function doesn't appear to have been developed
# Worth trying again as it is now included in the documentation
	
tim_a.irq(handler=lambda t:led_out.toggle(), trigger=Timer.TIMEOUT)	# Toggle LED on Timer interrupt

#btn_in = Pin('GP17', mode=Pin.IN, pull=Pin.PULL_UP)


# Connect to my WiFi
import machine
from network import WLAN
wlan = WLAN() 					# get current object, without changing the mode
Ejemplo n.º 51
0
	def blinking(self):
		pin = machine.Pin(PIN_D5, machine.Pin.OUT, machine.Pin.PULL_UP)
		tim = Timer(-1)
		tim.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:pin.value(not pin.value()))