예제 #1
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()
예제 #2
0
def wdt(secs=0):
    timer = Timer(-1)
    timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:wdt_feed())
    cnt = secs
    run = False  # Disable until 1st feed
    def inner(feed=WDT_CB):
        nonlocal cnt, run, timer
        if feed > 0:  # Call with variable timeout
            cnt = feed
            run = True
        elif feed == 0:  # Fixed timeout
            cnt = secs
            run = True
        elif feed < 0:  # WDT control/callback
            if feed == WDT_SUSPEND:
                run = False  # Temporary suspension
            elif feed == WDT_CANCEL:
                timer.deinit()  # Permanent cancellation
            elif feed == WDT_CB and run:  # Timer callback and is running.
                cnt -= 1
                if cnt <= 0:
                    reset()
    return inner
예제 #3
0
def enableInterrupt():
    """
    TIMER INTERRUPT CONFIGURATION
    """
    global CFG_TIMIRQCBF
    CFG_TIMIRQCBF = cfgget('timirqcbf')
    if cfgget("timirq") and CFG_TIMIRQCBF.lower() != 'n/a':
        try:
            period_ms_usr = int(cfgget("timirqseq"))
        except Exception as e:
            console_write("[IRQ] TIMIRQ period query error: {}".format(e))
            period_ms_usr = 3000
        console_write("[IRQ] TIMIRQ ENABLED: SEQ: {} CBF: {}".format(
            period_ms_usr, CFG_TIMIRQCBF))
        from machine import Timer
        # Init timer irq with callback function wrapper
        timer = Timer(0)
        timer.init(period=period_ms_usr,
                   mode=Timer.PERIODIC,
                   callback=secureInterruptHandler)
    else:
        console_write("[IRQ] TIMIRQ: isenable: {} callback: {}".format(
            cfgget("timirq"), cfgget('timirqcbf')))
예제 #4
0
class Pico(object):
    def __init__(self):
        self.led_pini = Pin(25, Pin.OUT)
        self.zamanlayici = Timer()

    def sicaklik_sensoru_ayarla(self):
        self.sicaklik_sensoru = ADC(4)

    def zamanlayiciyi_ayarla(self, frekans, mod, cb):
        self.zamanlayici.init(freq=frekans, mode=mod, callback=cb)

    def zamanlayiciyi_durdur(self):
        self.zamanlayici.deinit()

    def led_yaksöndür(self, zamanlayici):
        self.led_pini.toggle()

    def celcius_oku(self):
        #Referans:
        #https://github.com/raspberrypi/pico-micropython-examples/blob/master/adc/temperature.py
        ham_deger = self.sicaklik_sensoru.read_u16() * 3.3 / (65535)

        return 27 - (ham_deger - 0.706) / 0.001721
예제 #5
0
    def __init__(self, i2c):
        # Init MPU
        self.i2c = i2c
        self.addr = i2c.scan()[0]
        self.i2c.start()
        self.i2c.writeto(0x68, bytearray([107,0]))
        self.i2c.stop()
        self.x_offset = 0
        self.y_offset = 0
        self.z_offset = 0
        print('Initialized MPU6050.')

                # Gyro values will be updated every 100ms after creation of MPU object
        self.pitch = 0
        self.roll = 0
        self.yaw = 0
        self.velocity = (0,0,0)
        self.pitch_offset = 0
        self.roll_offset = 0
        self.yaw_offset = 0
        self.__init_gyro()
        gyro_timer = Timer(3)
        gyro_timer.init(mode=Timer.PERIODIC, callback=self.__update_gyro, period=100)
예제 #6
0
파일: clock.py 프로젝트: uraich/IoT-Course
    def __init__(self):
        #
        # connect to the WiFi network and setup the time
        #

        connect()

        #
        # setup the initial time
        #

        currentTime = cetTime()
        # cetTime returns (year,month,day,hours,minute,sec...)
        self.hours = currentTime[3]
        self.minutes = currentTime[4]
        time = self.hours = currentTime[3] * 100 + self.minutes
        # switch display on
        self.tm1637 = TM1637()
        self.tm1637.display_on()
        self.tm1637.write_dec(time, self.colon)
        # start a timer to interrupt every second
        timer = Timer(1)
        timer.init(period=1000, mode=Timer.PERIODIC, callback=self.set_clock)
예제 #7
0
class prog():
    def __init__(self):
        screen.clear()
        self.x = 61
        self.quit_flag = False
        self.timer = Timer(-1)
        screen.drawline(60, 100, 180, 100, 1, 0x000000)
        screen.drawline(60, 130, 180, 130, 1, 0x000000)
        screen.drawline(60, 100, 60, 130, 1, 0x000000)
        screen.drawline(180, 100, 180, 130, 1, 0x000000)

    def rect(self, z):
        screen.drawline(self.x, 100, self.x, 130, 1, 0x000000)
        self.x += 1
        if self.x == 180:
            self.timer.deinit()
            text.draw("加载完成", 88, 160, 0xff0000)
            self.quit_flag = True

    def progress(self):
        self.timer.init(mode=Timer.PERIODIC, period=1000, callback=self.rect)
        while not self.quit_flag:
            time.sleep_ms(50)
예제 #8
0
class Scheduler():
    def __init__(self):
        self.tasks = set()
        self.timer = None
        self.interval = None

    # create a new task for a callback and register it. 
    # per default the task is only run once
    def schedule_callback(self, callback, countdown=1000, interval = -1):
        self.register(CallbackTask(callback, countdown, interval))

    def register(self, task):
        self.tasks.add(task)

    def tick(self, timer):
        interval = self.interval
        for task in self.tasks:
            task.countdown -= interval
        micropython.schedule(self.run_due_tasks, None)

    def start(self, interval_ms):
        interval_ms = int(interval_ms)
        self.interval = interval_ms
        try:
            self.timer = Timer(-1)
            self.timer.init(period=interval_ms, mode=Timer.PERIODIC, callback=self.tick)
        except Exception as e:
            ct.format_exception(e, "could not initialize timer")
    
    def run_due_tasks(self, dummy=None):
        for task in self.tasks:
            if task.countdown <= 0:
                task.countdown += task.interval
                task.update(self)
                # we remove one time task at the end so that update() gets a chance to update the interval
                if task.interval < 0: 
                    self.tasks.discard(task)
예제 #9
0
class Blinker(object):
	def __init__(self, output_pin, period, pulses = None):
		# setup output pin
		self.output_pin = output_pin
		self.period = period
		self.pulses = pulses
		self.pin = Pin(self.output_pin,Pin.OUT)
		self.pin.off()
		self.counter = 0

	# Blocks the REPL until it has finished
	def blink_blocking(self):
		if self.pulses == None:
			while True:
				self.pin.value(not self.pin.value())
				time.sleep_ms(int(self.period/2))
		else:
			for i in range(0,(self.pulses)*2):
				self.pin.value(not self.pin.value())
				time.sleep_ms(int(self.period/2))

	def callback_timer(self,arg):
		self.pin.value(not self.pin.value())
		if (self.pulses != None):
			self.counter+=1
			if(self.counter == (self.pulses*2)):
				self.timing.deinit()
				self.counter = 0 

	def disable_isr(self):
		self.pin.off()
		self.timing.deinit()

	# Uses an interruption timer and callback function to trigger the toggle
	def blink_timer_isr(self):
		self.timing = Timer(-1)
		self.timing.init(period=int(self.period/2), mode=Timer.PERIODIC, callback=self.callback_timer)
예제 #10
0
파일: fader.py 프로젝트: stlk/micropython
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
예제 #11
0
def setup():
    # Sets up the timer based interrupt that will manage the lights
    # A period of 17ms means that every 60 updates will take 1020ms,
    # close enough to 60Hz refresh rate for me.
    global timer
    global info_index
    global info_msg
    global active
    global info
    global leds

    # Start the garbage collection
    gc.enable()

    with open('led_info_data', 'r') as info_f:
        info = ujson.load(info_f)

    leds = neopixel.NeoPixel(Pin(14), 2)
    info_index = len(info[0]) - 1
    info_msg = 0
    tim = Timer(0)
    tim.init(period=17, mode=Timer.PERIODIC, callback=__irq_led_info_update)
    timer = tim
    active = True
예제 #12
0
        class Debounced():
            tid = 10

            def __init__(self):
                self.run = True
                self.tid = Debounced.tid
                Debounced.tid += 1

            def __call__(self, *args, **kwargs):
                self.args = args
                self.kwargs = kwargs

                if self.run:
                    self.call_it()

                self.run = False
                self.t = Timer(5)
                self.t.init(mode=Timer.ONE_SHOT, period=wait, callback=self.clear_run)

            def call_it(self):
                fun(*self.args, **self.kwargs)

            def clear_run(self, dummy):
                self.run = True
예제 #13
0
class Watcher:
    def __init__(self, logService, interval = 15, timerId = 1):
        self._logService = logService
        self._isStuck = False
        self._interval = interval * 1000 # in seconds
        self._timerId = timerId
        self._logService.log('Watcher : interval ' + str(interval) + ' seconds')
        
    def check(self):
        self._logService.log('Watcher : isProcess stuck ' + str(self._isStuck))
        if self._isStuck:
            self._logService.log('Watcher: process detected stuck. Will restart now')
            machine.reset()

    def run(self):
        self._timer = Timer(self._timerId)
        self._timer.init(mode=Timer.PERIODIC, period=self._interval, callback=lambda x: self.check())   # one shot firing after 1000ms

    def watch(self, func):
        if func:
            self._isStuck = True
            result = func() # the function should finish with the elapse time otherwise the device will restart
            self._isStuck = False
            return result
예제 #14
0
class led_timer:
    def __init__(self, PinNum=25, periodH=500, periodL=500):
        self.pin = PinNum
        self.periodH = periodH
        self.periodL = periodL
        self.led = Pin(self.pin, Pin.OUT)
        self.led.value(0)
        self.timer = Timer()
        self.timer.init(period=self.periodL,
                        mode=Timer.ONE_SHOT,
                        callback=self.toggle)

    def toggle(self, timer):
        self.led.value(not self.led.value())
        if (self.led.value()):
            self.timer.init(period=self.periodH,
                            mode=Timer.ONE_SHOT,
                            callback=self.toggle)
        else:
            self.timer.init(period=self.periodL,
                            mode=Timer.ONE_SHOT,
                            callback=self.toggle)

    def setPeriodH(self, period):
        self.periodH = period

    def setPeriodL(self, period):
        self.periodL = period

    def setPeriod(self, period):
        self.periodL = self.periodH = period

    def setPeriodHL(self, periodH, periodL):
        self.periodL = periodL
        self.periodH = periodH

    def stop(self):
        self.timer.deinit()
        self.led.value(0)

    def restart(self):
        self.toggle(self.timer)
예제 #15
0
#############################################################

from machine import Pin, Timer
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)  # wait forever


try:
    led = Pin(LED_GPIO, Pin.OUT)
    # create a software-based timer
    timer = Timer(-1)
    # start the timer in periodic mode (100msec period)
    timer.init(mode=Timer.PERIODIC,
               period=100,
               callback=lambda t: led.value(not led.value()))
    main_loop()
except KeyboardInterrupt:
    pass
finally:
    led.value(LED_OFF)
    timer.deinit()

#############################################################
예제 #16
0
    print("Temp: ", temperature, ", Pressure: ", pressure, ", Humidity: ", humidity)

    # Get numerical value for temperature and generate an IFTTT notification if
    # it is over the threshold
    # Temperature is returned as "26.46C" by the BME280 library.
    # Use the Python substring operator with cast to float to get the numerical version.
    temperature_float = float(temperature[0:5])
    if (temperature_float > 25):
        modules.post_to_ifttt(temperature,humidity,pressure,wlan,settings,url)

    modules.clear_dynamic_screen(display)
    modules.draw_dynamic_screen(temperature,humidity,pressure,display)
    display.show()
    led.off()


display.init_display()
display.sleep(False)
display.rotate(True)
modules.draw_static_screen(display)
display.show()
modules.do_connect(wlan,settings)
sleep(1)
modules.get_internet_time(wlan)
modules.do_disconnect(wlan)

#timer_isr(1)    # Used for testing
#modules.do_disconnect(wlan)       # Used for testing
blink_timer = Timer(1)
blink_timer.init(period=1000, mode=Timer.PERIODIC, callback=timer_isr)
예제 #17
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()))
예제 #18
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(27)) #传感器连接到引脚15
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
예제 #19
0
    client.connect()
    client.set_callback(receive_handler)
    client.subscribe(Topic_sub)
    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (mqtt_server, Topic_sub))
    return client


##Random Number Generate and publish
def send_sessionid(pin):
    global pub, num
    if pub > 0:
        print("Session ID published")
        num = random.randint(0, 2024)
        client.publish(topic=sessionIDTopic_pub, msg=str(num))
        pub = 0
        print(num)
    else:
        pass


client = mqtt_pub(client_id, mqtt_server, 'swpdieal', 'MdwlLdTQWzbI', '14584',
                  sessionIDTopic_pub, sensorTopic_sub)
tim3 = Timer(3)
tim3.init(period=1000, mode=1, callback=send_sessionid)

while True:
    if interrupt2 > 0:
        client.check_msg()
        sleep(1)
예제 #20
0
파일: osd.py 프로젝트: emard/ulx3s_mac128
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.diskfile = [open("main.py", "rb"),
                         open("main.py", "rb")]  # any dummy file that can open
        self.imgtype = bytearray(
            2)  # [0]=0:.mac/.bin 1638400 bytes, [0]=1:.dsk 819200 bytes
        self.drive = bytearray(1)  # [0]=0:1st drive, [0]=1:2nd drive
        self.conv_dataIn12K = bytearray(12 * 1024)
        # memoryview for each track//16
        datainmv = memoryview(self.conv_dataIn12K)
        self.conv_dataIn = []
        for i in range(5):
            self.conv_dataIn.append(memoryview(datainmv[0:(12 - i) * 1024]))
        self.conv_nibsOut = bytearray(1024)
        dsk2mac.init_nibsOut(self.conv_nibsOut)
        self.track2sector = bytearray(81 * 2)
        self.init_track2sector()
        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_read_trackno = bytearray([1, 0xD0, 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_write_track = [
            bytearray([0, 0xD1, 0, 0, 0]),
            bytearray([0, 0xD1, 0, 0x60, 0])
        ]
        self.spi_channel = const(2)
        self.spi_freq = const(3000000)
        self.init_pinout_sd()
        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()
        self.led = Pin(self.gpio_led, Pin.OUT)
        self.led.off()


# init file browser

    def init_fb(self):
        self.fb_topitem = 0
        self.fb_cursor = 0
        self.fb_selected = -1

    @micropython.viper
    def init_track2sector(self):
        p16t2s = ptr16(addressof(self.track2sector))
        offset = 0
        for i in range(0, 81):
            p16t2s[i] = offset
            offset += 12 - i // 16

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

    @micropython.viper
    def update_track(self):
        p8result = ptr8(addressof(self.spi_result))
        p16t2s = ptr16(addressof(self.track2sector))
        p8it = ptr8(addressof(self.imgtype))
        # ask FPGA for current track number
        self.ctrl(4)  # stop cpu
        self.cs.on()
        self.spi.write_readinto(self.spi_read_trackno, self.spi_result)
        self.cs.off()
        drive = 0
        if p8result[6] & 0x80:
            drive = 1
        track = p8result[6] & 0x7F
        if track > 79:
            track = 79
        trackdiv16 = track // 16
        #print("Fetching drive " + str(drive) + " track " + str(track))
        sectors = 12 - trackdiv16
        self.diskfile[drive].seek((2 - p8it[drive]) * p16t2s[track] * 1024)
        # upload data
        self.cs.on()
        self.spi.write(self.spi_write_track[drive])
        if p8it[drive]:  # .dsk
            self.diskfile[drive].readinto(self.conv_dataIn[trackdiv16])
            offset = 0
            for side in range(2):
                for sector in range(sectors):
                    dsk2mac.convert_sector(self.conv_dataIn12K, offset,
                                           self.conv_nibsOut, track, side,
                                           sector)
                    offset += 512
                    self.spi.write(self.conv_nibsOut)
        else:  # .mac
            for side in range(2):
                self.diskfile[drive].readinto(self.conv_dataIn[trackdiv16])
                self.spi.write(self.conv_dataIn[trackdiv16])
        self.cs.off()
        self.ctrl(0)  # resume cpu

    @micropython.viper
    def irq_handler(self, pin):
        p8result = ptr8(addressof(self.spi_result))
        p8drive = ptr8(addressof(self.drive))
        self.cs.on()
        self.spi.write_readinto(self.spi_read_irq, self.spi_result)
        self.cs.off()
        btn_irq = p8result[6]
        if btn_irq & 1:  # drive 1 request
            self.update_track()
        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:  # btn5 cursor left
                        self.updir()
                    if btn == 65:  # btn6 cursor right 1st drive
                        p8drive[0] = 0
                        self.select_entry()
                    if btn == 3:  # btn1 2nd drive
                        p8drive[0] = 1
                        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(".mac") or filename.endswith(
                    ".MAC") or filename.endswith(".dsk") or filename.endswith(
                        ".DSK"):
                self.diskfile[self.drive[0]] = open(filename, "rb")
                self.imgtype[self.drive[0]] = 0
                if filename.endswith(".dsk") or filename.endswith(".DSK"):
                    self.imgtype[self.drive[0]] = 1
                #self.update_track()
                self.ctrl(16 << self.drive[0])  # set insert_disk
                self.enable[0] = 0
                self.osd_enable(0)
            if filename.endswith(".bit"):
                self.spi_request.irq(handler=None)
                self.timer.deinit()
                self.enable[0] = 0
                self.osd_enable(0)
                self.spi.deinit()
                import ecp5
                ecp5.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 = ecp5.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(".nes") \
            or filename.endswith(".snes") \
            or filename.endswith(".smc") \
            or filename.endswith(".sfc"):
                import ld_nes
                s = ld_nes.ld_nes(self.spi, self.cs)
                s.ctrl(1)
                s.ctrl(0)
                s.load_stream(open(filename, "rb"))
                del s
                gc.collect()
                self.enable[0] = 0
                self.osd_enable(0)
            if filename.startswith("/sd/ti99_4a/") and filename.endswith(
                    ".bin"):
                import ld_ti99_4a
                s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs)
                s.load_rom_auto(open(filename, "rb"), filename)
                del s
                gc.collect()
                self.enable[0] = 0
                self.osd_enable(0)
            if (filename.startswith("/sd/msx") and filename.endswith(".rom")) \
            or filename.endswith(".mx1"):
                import ld_msx
                s = ld_msx.ld_msx(self.spi, self.cs)
                s.load_msx_rom(open(filename, "rb"))
                del s
                gc.collect()
                self.enable[0] = 0
                self.osd_enable(0)
            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(".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()
            if filename.endswith(".cas"):
                self.enable[0] = 0
                self.osd_enable(0)
                import ld_trs80
                s = ld_trs80.ld_trs80(self.spi, self.cs)
                s.loadcas(filename)
                del s
                gc.collect()
            if filename.endswith(".cmd"):
                self.enable[0] = 0
                self.osd_enable(0)
                import ld_trs80
                s = ld_trs80.ld_trs80(self.spi, self.cs)
                s.loadcmd(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
        for fname in ls:
            stat = os.stat(self.fullpath(fname))
            if stat[0] & 0o170000 != 0o040000:
                self.direntries.append([fname, 0, stat[6]])  # file

    # NOTE: this can be used for debugging
    #def osd(self, a):
    #  if len(a) > 0:
    #    enable = 1
    #  else:
    #    enable = 0
    #  self.cs.on()
    #  self.spi.write(bytearray([0,0xFE,0,0,0,enable])) # enable OSD
    #  self.cs.off()
    #  if enable:
    #    self.cs.on()
    #    self.spi.write(bytearray([0,0xFD,0,0,0])) # write content
    #    self.spi.write(bytearray(a)) # write content
    #    self.cs.off()

    def ctrl(self, i):
        self.cs.on()
        self.spi.write(bytearray([0, 0xFF, 0xFF, 0xFF, 0xFF, i]))
        self.cs.off()

    def peek(self, addr, length):
        self.ctrl(4)
        self.ctrl(6)
        self.cs.on()
        self.spi.write(
            bytearray([
                1, (addr >> 24) & 0xFF, (addr >> 16) & 0xFF,
                (addr >> 8) & 0xFF, addr & 0xFF, 0
            ]))
        b = bytearray(length)
        self.spi.readinto(b)
        self.cs.off()
        self.ctrl(4)
        self.ctrl(0)
        return b

    def poke(self, addr, data):
        self.ctrl(4)
        self.ctrl(6)
        self.cs.on()
        self.spi.write(
            bytearray([
                0, (addr >> 24) & 0xFF, (addr >> 16) & 0xFF,
                (addr >> 8) & 0xFF, addr & 0xFF
            ]))
        self.spi.write(data)
        self.cs.off()
        self.ctrl(4)
        self.ctrl(0)
예제 #21
0
        onboard_pwm.duty(512)

        temp = mpu.temperature()
        temp_dif = init_temp - temp

        onboard_pwm.freq(10 + int(temp_dif) * 5)

        print("Temperature: " + str(round(temp, 3)) + " degrees C\n")


def state1(pin):
    global state
    state = 1


def state2(pin):
    global state
    state = 2


def debounce1(pin):
    timer1.init(mode=Timer.ONE_SHOT, period=200, callback=state1)


def debounce2(pin):
    timer2.init(mode=Timer.ONE_SHOT, period=200, callback=state2)


timer3.init(mode=Timer.PERIODIC, period=500, callback=run)
switch1.irq(trigger=Pin.IRQ_RISING, handler=debounce1)
switch2.irq(trigger=Pin.IRQ_RISING, handler=debounce2)
#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()
#tim.init(mode=Timer.PERIODIC, width=32)#terminal froze.
예제 #23
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())
예제 #24
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())
#
예제 #25
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())
#
예제 #26
0
def run(timer):
	if not upgrade:
		print('Running sensors...')
		import wake
		wake.main()	
	else:
		print('Upgrading...')
		import webrepl, iot
		iot.init_sta(False)
		iot.init_ap(True)
		webrepl.start()

if machine.reset_cause() == machine.DEEPSLEEP_RESET:
	print('Woke from a deep sleep...')
	import wake
	wake.main()

else:  # an opportunity to enter WebREPL after hard reset
	print('Hard reset')  
	# ESP8266 Code
	"""pin0 = Pin(0, Pin.IN, Pin.PULL_UP)   	# set GPIO0 as input with pullup
	pin0.irq(trigger=Pin.IRQ_RISING, handler=callback)"""
	#ESP32 Code
	""" """
	timer.init(period=5000, mode=Timer.ONE_SHOT, callback=run)
	
	# ESP32 Code


예제 #27
0
파일: temp.py 프로젝트: 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()
예제 #28
0
class SwitchReader:
    def __init__(self, config_file='/config/switch.txt'):
        config_loader = ConfigurationLoader(config_file)
        configs = config_loader.load_configuration('mqtt_broker', 'mqtt_topic',
                                                   'mqtt_id', 'switch_pin',
                                                   'switch_update_period')
        self.config_file = config_file
        self.switch_update_period = int(configs['switch_update_period'])
        self.mqtt_client = MQTTClient(configs['mqtt_id'],
                                      configs['mqtt_broker'])
        self.mqtt_client.DEBUG = True
        self.mqtt_topic = configs['mqtt_topic']
        self.switch_pin_num = int(configs['switch_pin'])
        self.switch_pin = Pin(self.switch_pin_num, Pin.IN)
        self.id = configs['mqtt_id']
        self.mqtt_broker = configs['mqtt_broker']
        self.logger = MyLogger(False)
        self.logger.log('DEBUG', self.id,
                        'Connecting to {}...'.format(self.mqtt_broker))
        try:
            self.mqtt_client.connect()
            self.logger.log('INFO', self.id,
                            'Reconnected to {}'.format(self.mqtt_broker))
        except:
            self.logger.log(
                'ERROR', self.id,
                'Connection failure to {}'.format(self.mqtt_broker))
        self.last_switch_position = self.switch_pin.value()
        self.mqtt_messages_sent = 0
        self.debounce_time = 0.5
        self.timer = None
        self.init_timer()

    def init_timer(self):
        self.deinit_timer()
        self.timer = Timer(-1)
        self.timer.init(period=self.switch_update_period,
                        mode=Timer.ONE_SHOT,
                        callback=lambda t: self.loop())

    def loop(self):
        self.read_switch()
        self.init_timer()

    def deinit_timer(self):
        if isinstance(self.timer, Timer):
            self.timer.deinit()
        self.timer = None

    def read_switch(self):
        switch_position = self.switch_pin.value()
        if switch_position != self.last_switch_position:
            self.last_switch_position = switch_position
            self.notify_hub()
            self.deinit_timer()
            sleep(self.debounce_time)

    def notify_hub(self):
        if not self._connected_to_broker():
            try:
                self.mqtt_client.connect()
                self.logger.log('INFO', self.id,
                                'Reconnected to {}'.format(self.mqtt_broker))
            except:
                self.logger.log(
                    'ERROR', self.id,
                    'Connection failure to {}'.format(self.mqtt_broker))

        try:
            '''
			if self.mqtt_messages_sent > 3:
				self.reset_mqtt_connection()
			'''
            self.mqtt_client.publish(topic=self.mqtt_topic,
                                     msg='pressed',
                                     qos=1)
            self.logger.log('INFO', self.id, 'hub successfully notified')
            self.mqtt_messages_sent += 1
            self.reset_mqtt_connection()
        except Exception as e:
            self.logger.log('ERROR', self.id,
                            "Can't notify the hub; {}".format(e))

    def reset_mqtt_connection(self):
        self.mqtt_client.disconnect()
        sleep(0.1)
        self.mqtt_client.connect()
        self.mqtt_messages_sent = 0

    def _connected_to_broker(self):
        try:
            self.mqtt_client.ping()
            return True
        except:
            return False

    def edit_configuration(self, key, value):
        try:
            with open(self.config_file, 'rb') as file:
                configs = json.load(file)
        except Exception as e:
            self.logger.log('ERROR', self.__class__.__name__,
                            "Can't open configuration file; {}".format(e))
            return False

        configs[key] = value

        try:
            with open(self.config_file, 'wb') as file:
                json.dump(configs, file)
        except Exception as e:
            self.logger.log('ERROR', self.__class__.__name__,
                            "Can't save configuration; {}".format(e))
            return False

        return True
예제 #29
0
    if led1.value() == False:
        led1.on()
    else:
        led1.off()


def blue_blink_isr(event):
    if led2.value() == False:
        led2.on()
    else:
        led2.off()


def green_blink_isr(event):
    if led3.value() == False:
        led3.on()
    else:
        led3.off()


blink_timer_red = Timer(0)
blink_timer_red.init(period=250, mode=Timer.PERIODIC, callback=red_blink_isr)

blink_timer_blue = Timer(1)
blink_timer_blue.init(period=350, mode=Timer.PERIODIC, callback=blue_blink_isr)

blink_timer_green = Timer(2)
blink_timer_green.init(period=450,
                       mode=Timer.PERIODIC,
                       callback=green_blink_isr)
예제 #30
0
class Lab2:
    def __init__(self, devices):
        #LED
        self.freq = 1
        self.duty = 512
        self.led = PWM(Pin(13), freq=self.freq, duty=self.duty)

        # Piezo
        self.piezo = PWM(Pin(15), freq=self.freq, duty=self.duty)

        # ALS
        self.als = ADC(0)

        # Switch
        self.switch = Pin(14, Pin.IN)
        self.switch.irq(handler=self.switch_cb,
                        trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING,
                        hard=True)

        # Interrupt flags
        self.do_debounce = False
        self.read_als = False

        # Timer
        self.timer = Timer(-1)
        self.timer.init(period=1000,
                        mode=Timer.PERIODIC,
                        callback=self.timer_cb)

        # test LED
        self.test_led = Pin(2, Pin.OUT)
        self.test_led.off()

        return

    def timer_cb(self, timer):
        if self.read_als:
            self.duty = self.als.read()
            self.led.duty(self.duty)
        self.test_led.off()

        #if self.do_debounce:
        #    self.do_debounce = False
        #    self.debounce()
        return

    # Interrupt callback
    def switch_cb(self, pin):
        state = disable_irq()
        value = pin.value()
        if value == 1:
            self.read_als = True
        else:
            self.read_als = False
        self.do_debounce = True
        self.test_led.on()
        enable_irq(state)
        return

    # Debounce
    def debounce(self):
        cur_val = self.switch.value()
        dur_active = 0
        while dur_active < 10:
            if pin.value() == cur_val:
                dur_active = dur_active + 1
            else:
                cur_val = self.switch.value()
                dur_active = 0
            time.sleep_ms(1)  # 1 millisecond
        if cur_val == 1:
            self.read_als = True
        else:
            self.read_als = False
        return
예제 #31
0
from machine import Timer
from machine import Pin 
import time

led = Pin(2, Pin.OUT, value=0)
led_value = 0
def ledkg(t):
    global led_value
    if led_value==0:
        led_value=1
    else:
        led_value=0
    led.value(led_value)
    print('LED%d'%led_value)
tim=Timer(1)
tim.init(period=2000, mode=Timer.PERIODIC, callback=ledkg)
time.sleep(10)#延迟10秒停用定时器
tim.deinit()
time.sleep(10)#延迟10秒重新配置定时器
tim.init(period=2000, mode=Timer.PERIODIC, callback=ledkg)
'''
tim=Timer(1)使用定时器1创建一个定时器对象
tim.init(period=2000, mode=Timer.PERIODIC, callback=ledkg)
#[period 定时器周期] [mode 定时器循环模式] [callback 定时器调用函数]
            
tim.init()           >>>初始化定时器
tim.callback(fun)    >>>设置定时器触发时所调用的函数。
tim.deinit()         >>>禁用停用定时器
'''
예제 #32
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())
#
예제 #33
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()

    def get_spi_result(self):
        return self.spi_result

    def get_spi_result2(self):
        self.cs.on()
        self.spi.write_readinto(self.spi_read_btn, self.spi_result)
        self.cs.off()
        return self.spi_result

# A couple of shortcut functions to change directories, useful for TI-99/4A core development.
# After running "import osd", these can be accessed with osd.run.ti_cart() for example.

    def change_dir(self, dir):
        os.chdir(dir)
        print("Current directory changed to {}".format(dir))

    def ti_cart(self):
        self.change_dir("/sd/ti99_4a/cart")

    def ti_grom(self):
        self.change_dir("/sd/ti99_4a/grom")

    def ti_bit(self):
        self.change_dir("/sd/ti99_4a/bitstreams")

# 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(".nes") \
            or filename.endswith(".snes") \
            or filename.endswith(".smc") \
            or filename.endswith(".sfc"):
                import ld_nes
                s = ld_nes.ld_nes(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.startswith(
                    "/sd/ti99_4a/") and filename.lower().endswith(".bin"):
                import ld_ti99_4a
                s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs)
                s.load_rom_auto(open(filename, "rb"), filename)
                del s
                gc.collect()
                self.enable[0] = 0
                self.osd_enable(0)
            if (filename.startswith("/sd/msx") and filename.endswith(".rom")) \
            or filename.endswith(".mx1"):
                import ld_msx
                s = ld_msx.ld_msx(self.spi, self.cs)
                s.load_msx_rom(open(filename, "rb"))
                del s
                gc.collect()
                self.enable[0] = 0
                self.osd_enable(0)
            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(".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()
            if filename.endswith(".cas"):
                self.enable[0] = 0
                self.osd_enable(0)
                import ld_trs80
                s = ld_trs80.ld_trs80(self.spi, self.cs)
                s.loadcas(filename)
                del s
                gc.collect()
            if filename.endswith(".cmd"):
                self.enable[0] = 0
                self.osd_enable(0)
                import ld_trs80
                s = ld_trs80.ld_trs80(self.spi, self.cs)
                s.loadcmd(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()

    # NOTE: this can be used for debugging
    #def osd(self, a):
    #  if len(a) > 0:
    #    enable = 1
    #  else:
    #    enable = 0
    #  self.cs.on()
    #  self.spi.write(bytearray([0,0xFE,0,0,0,enable])) # enable OSD
    #  self.cs.off()
    #  if enable:
    #    self.cs.on()
    #    self.spi.write(bytearray([0,0xFD,0,0,0])) # write content
    #    self.spi.write(bytearray(a)) # write content
    #    self.cs.off()

    def load_console_grom(self):
        gromfile = "/sd/ti99_4a/grom/994AGROM.Bin"
        import ld_ti99_4a
        s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs)
        s.reset_on()
        print("GROM file: {}".format(gromfile))
        bytes = s.load_stream(open(gromfile, "rb"), 0x10000)
        print("Loaded {} bytes".format(bytes))
        s.reset_off()
        del s
        gc.collect()

    def load_console_rom(self):
        romfile = "/sd/ti99_4a/rom/994AROM.Bin"
        import ld_ti99_4a
        s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs)
        s.reset_on()
        print("System ROM file: {}".format(romfile))
        bytes = s.load_stream(open(romfile, "rb"), 0)
        print("Loaded {} bytes".format(bytes))
        s.reset_off()
        del s
        gc.collect()

    def load_roms(self):
        romfile = "/sd/ti99_4a/rom/994AROM.Bin"
        gromfile = "/sd/ti99_4a/grom/994AGROM.Bin"
        import ld_ti99_4a
        s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs)
        s.reset_on()
        # Load ROM
        print("System ROM file: {}".format(romfile))
        bytes = s.load_stream(open(romfile, "rb"), 0)
        print("Loaded {} bytes".format(bytes))
        # Load GROM
        print("GROM file: {}".format(gromfile))
        bytes = s.load_stream(open(gromfile, "rb"), 0x10000)
        print("Loaded {} bytes".format(bytes))
        # remove reset
        s.reset_off()
        del s
        gc.collect()

    def save_mem(self, filename, addr, length):
        import ld_ti99_4a
        old_freq = self.spi_freq
        self.spi_freq = const(100000)
        self.init_spi()
        s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs)
        print("Saving memory from {} length {} file: {}".format(
            addr, length, filename))
        s.save_stream(open(filename, "wb"), addr, length)
        del s
        self.spi_freq = old_freq
        self.init_spi()
        gc.collect()
예제 #34
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()))
예제 #35
0
    print('WiFi Connection Successful,Network Config:%s' %str(wlan.ifconfig()))

def pubdata(data):
    j_d = json.dumps(data)
    j_l = len(j_d)
    arr = bytearray(j_l + 3)
    arr[0] = 1 #publish数据类型为json
    arr[1] = int(j_l / 256) # json数据长度 高位字节
    arr[2] = j_l % 256      # json数据长度 低位字节
    arr[3:] = j_d.encode('ascii') # json数据
    return arr

def publishSenser():
  message['datastreams'][0]['datapoints'][0]['value']=sound.read()
  message['datastreams'][1]['datapoints'][0]['value']=light.read()
  c.publish('$dp',pubdata(message))                   #publish报文上传数据点
  print('publish message:',message)
  
 
ConnectWifi()

c = MQTTClient(CLIENT_ID, SERVER,6002,username,password)
c.connect()
print("Connected to %s" % SERVER)
tim1.init(period=1000, mode=Timer.PERIODIC, callback=lambda _:publishSenser())     #每隔一秒上传数据点





예제 #36
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秒ごとに割り込み
예제 #37
0
    oled.text(station.ifconfig()[0], 25, 0)
    rtc = RTC()
    datetime = rtc.datetime()  # 获取当前时间
    oled.hline(0, 63, 127, 1)
    oled.text(
        str(datetime[0]) + '-' + str(datetime[1]) + '-' + str(datetime[2]), 30,
        45)
    oled.text(
        str(datetime[4]) + ':' + str(datetime[5]) + ':' + str(datetime[6]), 30,
        25)  #hour #minue #second
    oled.show()
    time.sleep(0.01)


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

while True:
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    request = str(request)
    print('Content = %s' % request)
    led_on = request.find('/?led=on')
    led_off = request.find('/?led=off')
    if led_off == 6:
        print('LED OFF')
        led.value(1)
        time.sleep(0.01)

    if led_on == 6:
예제 #38
0
def main(GS):
    GS.ConfigFile = 'mycfng.json'
    # GS.data           = {}
    LoadConfig(GS)
    # Init i2c
    i2c = I2C(scl=Pin(5), sda=Pin(4))
    pcfs = i2c.scan()
    devices = {}
    for p in pcfs:
        devices[p] = {}
        devices[p]["Ist"] = pcf8574.PCF8574(i2c, p)
        devices[p]["Ist"].port = 0
        devices[p]["Name"] = p
    # Station UP
    GS.station = network.WLAN(network.STA_IF)
    # Disabilito AP
    ap_if = network.WLAN(network.AP_IF)
    ap_if.active(False)
    sleep_ms(LOOP_WAIT_MS)
    sleep_ms(LOOP_WAIT_MS)
    sleep_ms(LOOP_WAIT_MS)
    WifiConnect(GS)
    MqttSetUP(GS)
    internalLed.on()
    PrintCnt = 0
    byteFields = ''
    while True:
        newByteFields = ''
        PrintCnt += 1
        for dev in devices:
            Name = devices[dev]["Name"]
            pcf = devices[dev]["Ist"]
            newByteFields += str(pcf.port)
            for x in range(I2C_PIN_NUMBER):
                value = pcf.pin(x)
                msg = "Pin: " + str(x) + " is: [ " + str(
                    value) + " ]  On DEV: " + str(Name)
                log("VERBO", msg)
                PinOut = str(Name) + "_" + str(x)
                GS.statusMsg[PinOut] = value
        if newByteFields != byteFields:
            try:
                byteFields = newByteFields
                log("DEBUG", "Pub Status on: [" + str(GS.OUT_STATUS) + "]")
                GS.statusMsg["rssi"] = str(GS.station.status('rssi'))
                GS.c.publish(GS.OUT_STATUS,
                             msg=ujson.dumps(GS.statusMsg),
                             retain=True,
                             qos=1)
                msg = "Notifications DONE"
                log("INFO", msg)
            except Exception as e:
                log("ERROR", 'Error MqttPub on OUT_STATUS {}'.format(e))
                internalLed.off()
                machine.reset()
                sleep_ms(LOOP_WAIT_MS)

        if PrintCnt == LOOP_SKIPS:  # Limit console noise
            PrintCnt = 0
            log("INFO", "----- LOOOP MqttI2cInput -----")
            timer = Timer(0)
            timer.init(period=(TIMEOUT_MS * 30),
                       mode=Timer.ONE_SHOT,
                       callback=timeout_callback)
            try:
                log("DEBUG", "NewCheck")
                GS.c.check_msg()
                log("DEBUG", "NewCheck DONE")
                log("DEBUG", "Ping Start")
                GS.c.ping()
                log("DEBUG", "Ping DONE")
                internalLed.on()
            except Exception as e:
                log("ERROR", 'Error MqttCallBack and MqttPing {}'.format(e))
                internalLed.off()
                machine.reset()
                sleep_ms(LOOP_WAIT_MS)
            finally:
                timer.deinit()
        sleep_ms(LOOP_WAIT_MS)
    GS.c.disconnect()
예제 #39
0
  -          Pin 1 (left-most) to 3.3V,
  -          Pin 2 to GPIO4,
  -          Pin 4 to GND
  -          (Pin 3 not connected).
  - 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
 DHT: http://docs.micropython.org/en/latest/esp32/quickref.html#dht-driver
 
 Course:
 MicroPython with the ESP32
 https://techexplorations.com

'''

from machine import Pin, Timer
import dht

dht22 = dht.DHT22(Pin(4))

def take_measurement_isr(event):
    dht22.measure()
    print("Temp: ", dht22.temperature(), "°C, Humidity: ", dht22.humidity(), "%")
    

dht_timer = Timer(1)
dht_timer.init(period=5000, mode=Timer.PERIODIC, callback=take_measurement_isr)
예제 #40
0
파일: CW01.py 프로젝트: xinabox/mu-editor
    def toggle(self):
        self.rgb += 1
        for led, val in zip(self.leds, self.pattern[self.rgb % 3]):
            led.value(val)

    def allOff(self):
        for led in self.leds:
            led.value(0)


xChip = myI2C()
xinabox = myNetwork()
LED = myLEDs()

tim = Timer(-1)
tim.init(period=100, callback=lambda t: LED.toggle())

for _ in range(10):
    xChip.scan()
    time.sleep(0.1)

xinabox.scan()

_, mpv, mpy = sys.implementation
mpv = ".".join(map(str, mpv))
print("This ran on Python v.{}, uPython v.{}, mpy v.{}".format(
    sys.version, mpv, mpy))

tim.deinit()
tim.init(period=50, mode=Timer.ONE_SHOT, callback=lambda t: LED.allOff())
예제 #41
0
class BLE_FINDME_TARGET:
    def __init__(self, name="esp32-fmpt", led=None):
        self.timer = Timer(-1)
        self.led = led
        self.irq_busy = False
        self.buzz = NOTIFYER(25, 13)
        self.i = 0
        self._is_connected = False
        self.alert_level = 0
        self._ble = bluetooth.BLE()
        self._ble.active(True)
        self._ble.irq(handler=self._irq)
        ((self._appear, self._manufact, self._model, self._firm),
         (self._alert_handle, )) = self._ble.gatts_register_services(
             (_DEV_INF_SERV_SERVICE, _IMMEDIATE_ALERT_SERVICE))
        self._connections = set()
        self._payload = advertising_payload(
            name=name,
            services=[_IMMEDIATE_ALERT_SERV_UUID],
            appearance=_ADV_APPEARANCE_GENERIC_KEYRING)
        # print(len(self._payload))
        # First 30 seconds (fast connection) Advertising Interval 20 ms to 30 ms
        print('Advertising in fast connection mode for 30 seconds...')
        self._advertise(interval_us=30000)
        self._ble.gatts_write(
            self._appear, struct.pack("h", _ADV_APPEARANCE_GENERIC_KEYRING))
        self._ble.gatts_write(self._manufact,
                              bytes('Espressif Incorporated', 'utf8'))
        self._ble.gatts_write(self._model, bytes(_MODEL_NUMBER, 'utf8'))
        self._ble.gatts_write(self._firm, bytes(_FIRMWARE_REV, 'utf8'))

        # Timeout 30 s
        self.start_adv_fast_timeout()
        # After 30 seconds (reduced power) Advertising Interval 1 s to 2.5 s

    def _irq(self, event, data):
        # Track connections so we can send notifications.
        if event == _IRQ_CENTRAL_CONNECT:
            conn_handle, _, _, = data
            self._connections.add(conn_handle)
            self.is_connected = True
            self.stop_timeout()
        elif event == _IRQ_CENTRAL_DISCONNECT:
            conn_handle, _, _, = data
            self.stop_timeout()
            self.is_connected = False
            self._connections.remove(conn_handle)
            if self.led:
                for k in range(4):
                    self.led.value(not self.led.value())
                    time.sleep(0.2)
            # Start advertising again to allow a new connection.
            print('Advertising in fast connection mode for 30 seconds...')
            self._advertise(interval_us=30000)
            self.start_adv_fast_timeout()
        elif event == _IRQ_GATTS_WRITE:
            conn_handle, value_handle, = data
            if conn_handle in self._connections and value_handle == self._alert_handle:
                self.alert_level, = struct.unpack(
                    'B', self._ble.gatts_read(self._alert_handle))
                if self.alert_level == 0:  # No Alert
                    print('No alert')
                if self.alert_level == 1:  # Mid Alert
                    print('Mild Alert')
                    self.buzz.buzz_beep(150, 3, 100, 1000)
                if self.alert_level == 2:  # High Alert
                    print('High Alert')
                    self.buzz.buzz_beep(150, 3, 100, 4000)

    def _advertise(self, interval_us=500000):
        self._ble.gap_advertise(interval_us, adv_data=self._payload)

    def check_if_connected(self, x):
        if self.irq_busy:
            return
        else:
            if self._is_connected:
                return
            else:
                print('Advertising in reduced power mode from now on...')
                self._advertise(interval_us=2500000)
                if self.led:
                    for k in range(10):
                        self.led.value(not self.led.value())
                        time.sleep(0.2)

    def start_adv_fast_timeout(self, timeout=30000):
        self.irq_busy = False
        self.timer.init(period=timeout,
                        mode=Timer.ONE_SHOT,
                        callback=self.check_if_connected)

    def stop_timeout(self):
        self.timer.deinit()
        self.irq_busy = False
예제 #42
0
class Battery:

    def __init__(self):

        """Initialize Battery."""

        self.vbat = int()

        lcd.clear(0xFF8000)

        buttonA.wasPressed(callback=self.exit)
        buttonB.wasPressed(callback=lambda: None)

        self.show_battery()

        self.refresh = Timer(0)
        self.refresh.init(period=10000, mode=Timer.PERIODIC, callback=self.show_battery)

    def show_battery(self, t=None):

        """Convert battery voltage into bars."""

        self.vbat = self.map_value(axp.getVbatData() * 1.1, 3000, 4100, 0, 6)
        print(axp.getVbatData() * 1.1)
        print(self.vbat)

        if axp.getIChargeData() / 2 > 0:
            color = lcd.YELLOW
        elif self.vbat == 1:
            color = lcd.RED
        elif self.vbat == 2:
            color = lcd.ORANGE
        else:
            color = lcd.GREEN

        # Battery Icon.
        lcd.fillRect(22, 10, 125, 60, lcd.BLACK)
        lcd.fillRect(12, 30, 10, 20, lcd.BLACK)

        # Reset bars.
        lcd.fillRect(127, 15, 15, 50, lcd.BLACK)
        lcd.fillRect(107, 15, 15, 50, lcd.BLACK)
        lcd.fillRect(87, 15, 15, 50, lcd.BLACK)
        lcd.fillRect(67, 15, 15, 50, lcd.BLACK)
        lcd.fillRect(47, 15, 15, 50, lcd.BLACK)
        lcd.fillRect(27, 15, 15, 50, lcd.BLACK)

        # Draw bars.
        if self.vbat >= 1:
            lcd.fillRect(127, 15, 15, 50, color)
        if self.vbat >= 2:
            lcd.fillRect(107, 15, 15, 50, color)
        if self.vbat >= 3:
            lcd.fillRect(87, 15, 15, 50, color)
        if self.vbat >= 4:
            lcd.fillRect(67, 15, 15, 50, color)
        if self.vbat >= 5:
            lcd.fillRect(47, 15, 15, 50, color)
        if self.vbat >= 6:
            lcd.fillRect(27, 15, 15, 50, color)

    def exit(self):

        """De-init timer and exit."""

        self.refresh.deinit()

        # Return to menu
        return Data.Menu.Menu()

    @staticmethod
    def map_value(x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min