class Ultrasonic(object):
    def __init__(self, trigger_pin, echo_pin, timeout_us=30000):
        # WARNING: Don't use PA4-X5 or PA5-X6 as echo pin without a 1k resistor

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

        self.timeout = timeout_us

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

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

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

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

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

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

        # Divide the duration of the pulse by 2 (round-trip) and then divide it
        # by 29 us/cm (speed of sound = ~340 m/s)
        return (time_pulse / 2) / 29
Beispiel #2
0
    l.duty(input)
    print(input)
    sleep(0.1)


while True:
    try:
        if button.value() == 0:
            if not timer_switch:
                deinitTimers([g, r, y])
                timer_switch = True
            green.on()
            red.on()
            yellow.on()
        else:
            if timer_switch:
                g = initTimer(green, period_green)
                r = initTimer(red, period_red)
                y = initTimer(yellow, period_yellow)
                timer_switch = False

        setBrightness(bluePWM, adc.read())

    except KeyboardInterrupt:
        deinitTimers([g, r, y])
        green.off()
        red.off()
        yellow.off()
        blue.off()
        break
Beispiel #3
0
"""This app goes with the Torch Tutorial"""

___name___ = "Tilda Torch"
___license___ = "MIT"
___dependencies___ = ["sleep"]
___categories___ = ["EMF"]

import ugfx, os, time, sleep
from tilda import Buttons
from machine import Pin

torch = Pin(Pin.GPIO_FET)

ugfx.init()
Pin(Pin.PWM_LCD_BLIGHT).on()
ugfx.clear()

ugfx.text(5, 5, "TORRRRRRCH!!!!!", ugfx.BLACK)
torch.on()

while (not Buttons.is_pressed(Buttons.BTN_A)) and (not Buttons.is_pressed(
        Buttons.BTN_B)) and (not Buttons.is_pressed(Buttons.BTN_Menu)):
    sleep.wfi()

torch.off()

ugfx.clear()
Beispiel #4
0
from machine import Pin
from hcsr04 import HCSR04
from time import sleep
from netvars import setNetVar, getNetVar, initNet

# # assuming there is a network with ssid hotspot1 and password 123456789
# connect to wifi
initNet("FRITZ!Box Fon WLAN 7360", "26019589887890601540")

# assume our LED is connected to Pin 26, we use it as output
LED = Pin(14, Pin.OUT)
sensor = HCSR04(trigger_pin=5, echo_pin=4)

old_distance = -1

while True:
    distance = sensor.distance_cm()

    if distance is not old_distance:
        setNetVar("peter_ehrich_task_2", "moved")
    else:
        setNetVar("peter_ehrich_task_2", "still")

    if getNetVar("peter_ehrich_task_2") == "moved":
        LED.on()
        sleep(5)
        LED.off()
    old_distance = distance
Beispiel #5
0
class Rodas:
    def __init__(self):
        ## Frequencia de trabalho do motor
        # O valor maximo e 1024
        self.freqA = 1024
        self.freqB = 1024
        ## Os pinos para o Shield ESP são fixos
        # Para o motor A, esquerdo, os pinos sao:
        # 5 para velocidade e 0 para direção
        self.PwmA = PWM(Pin(5), freq=1000, duty=0)
        self.DirA = Pin(0, Pin.OUT)
        # Para o motor A, esquerdo, os pinos sao:
        # 5 para velocidade e 0 para direção
        self.PwmB = PWM(Pin(4), freq=1000, duty=0)
        self.DirB = Pin(2, Pin.OUT)
        # Os pinos a seguir foram ocupados
        # para controlar a ponte H
        # D1 = GPIO 5
        # D2 = GPIO 4
        # D3 = GPIO 0
        # D4 = GPIO 2

    def frente(self):
        print("frente")
        self.PwmA.duty(800)
        self.PwmB.duty(800)
        self.DirA.off()
        self.DirB.off()

    def re(self):
        print("re")
        self.PwmA.duty(800)
        self.PwmB.duty(800)
        self.DirA.on()
        self.DirB.on()

    def esquerda(self):
        print("esquerda")
        self.PwmA.duty(800)
        self.PwmB.duty(800)
        self.DirA.on()
        self.DirB.off()

    def direita(self):
        print("direita")
        self.PwmA.duty(800)
        self.PwmB.duty(800)
        self.DirA.off()
        self.DirB.on()

    def parar(self):
        print("parar")
        self.PwmA.duty(0)
        self.PwmB.duty(0)
        self.DirA.off()
        self.DirB.off()
Beispiel #6
0
class Relay:
    def __init__(self,
                 name: str,
                 pin_num: int,
                 active_at: int,
                 persist_path=None) -> None:
        """
        Relay control for the tlvlp.iot project

        Tested on ESP32 MCUs
        :param pin_num: digital output pin to control the relay
        :param active_at: the relay is either active at a HIGH(1) or LOW(0) Pin state
        :param persist_path: if a path is provided the relay's state will be persisted to and loaded from there.
        """
        reference = "relay|"
        self.id = reference + name
        self.active_at = active_at
        self.persist_path = persist_path
        self.pin = Pin(pin_num, Pin.OUT, value=self.get_off_state())
        self.state = 0
        if persist_path is None:
            self.state_is_persisted = False
            self.relay_off()
        else:
            self.state_is_persisted = True
            self.load_state_from_file()

    def get_off_state(self) -> int:
        if self.active_at == 0:
            return 1
        else:
            return 0

    def get_module_id(self) -> str:
        return self.id

    def handle_control_message(self, value_str: str):
        value = int(float(value_str))
        if value == 1:
            self.relay_on()
        elif value == 0:
            self.relay_off()
        else:
            raise InvalidModuleInputException

    def get_state(self) -> tuple:
        """ Returns a tuple with the reference name and the current relay state that is either 1 (on) or 0 (off) """
        return self.id, self.state

    def set_state(self, state: int):
        if int(state) == 1:
            self.relay_on()
        elif int(state) == 0:
            self.relay_off()
        else:
            error = "Relay - Error! Unrecognized relay state:" + str(state)
            print(error)
            raise ValueError(error)

    def relay_on(self) -> None:
        """ Switches the relay on """
        if self.active_at == 1:
            self.pin.on()
        else:
            self.pin.off()
        self.state = 1
        if self.state_is_persisted:
            self.save_state_to_file()

    def relay_off(self) -> None:
        """ Switches the relay off """
        if self.active_at == 1:
            self.pin.off()
        else:
            self.pin.on()
        self.state = 0
        if self.state_is_persisted:
            self.save_state_to_file()

    def load_state_from_file(self) -> None:
        try:
            with open(self.persist_path) as stateFile:
                loaded_state = int(stateFile.readline())
            print("Relay - Loading state from path: {}".format(
                self.persist_path))
            self.set_state(loaded_state)
        except OSError:
            print("Relay - No persisted state exists yet at path: {}".format(
                self.persist_path))
            self.relay_off()

    def save_state_to_file(self) -> None:
        with open(self.persist_path, "w+") as state:
            state.write(str(self.state))
Beispiel #7
0
from machine import Pin, RTC
from time import sleep, sleep_ms, sleep_us
from json import load as jload
from ntptime import settime

ADDR_DELAY_US = 100
GOTO_DELAY_MS = 20
HOUR_LUT = jload(open("hour_lut.json"))
MINUTE_LUT = jload(open("minute_lut.json"))
TIME_ZONE = +2

encoder_pins = [Pin(i, Pin.IN, Pin.PULL_UP) for i in [0, 2, 4, 5, 12, 13]]

run = Pin(16, Pin.OUT)
run.off()
adc_hour = Pin(14, Pin.OUT)
adc_hour.off()
adc_minute = Pin(15, Pin.OUT)
adc_minute.off()

try:
    settime()
except:
    pass
rtc = RTC()


def select(adc, adl):
    if None != adc:
        adc.on()
    if None != adl:
Beispiel #8
0
    print("OK")
else:
    print("NG")
    print("exp: " + try_s)
    print("out: " + str(p))

p.init(p.IN, p.PULL_UP)
p.init(p.IN, pull=p.PULL_UP)
p.init(mode=p.IN, pull=p.PULL_UP)
print(p.value())

p.init(p.OUT)
p.init(p.OPEN_DRAIN)
p.low()
print(p.value())
p.high()
print(p.value())
p.value(0)
print(p.value())
p.value(1)
print(p.value())
p.value(False)
print(p.value())
p.value(True)
print(p.value())
p.off()
print(p.value())
p.on()
print(p.value())
p.off()
Beispiel #9
0
class MFRC522:

    OK = 0
    NOTAGERR = 1
    ERR = 2

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

    def __init__(self, sck, mosi, miso, rst, cs):

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

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

        board = uname()[0]

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

        self.rst.value(1)
        self.init()

    def _wreg(self, reg, val):

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

    def _rreg(self, reg):

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

        return val[0]

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

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

    def _tocard(self, cmd, send):

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

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

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

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

        if cmd == 0x0C:
            self._sflags(0x0D, 0x80)
# o que mudei. Originalmente 2000
        i = 100
        while True:
            n = self._rreg(0x04)
            i -= 1
            if ~((i != 0) and ~(n & 0x01) and ~(n & wait_irq)):
                break

        self._cflags(0x0D, 0x80)

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

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

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

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

        return stat, recv, bits

    def _crc(self, data):

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

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

        self._wreg(0x01, 0x03)

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

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

    def init(self):

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

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

    def antenna_on(self, on=True):

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

    def request(self, mode):

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

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

        return stat, bits

    def anticoll(self):

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

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

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

        return stat, recv

    def select_tag(self, ser):

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

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

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

    def read(self, addr):

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

    def write(self, addr, data):

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

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

        return stat

    def sda(self, pin):
        self.cs.off()
        self.cs = Pin(pin, Pin.OUT)
        self.cs.on()

    def select(self):
        self.cs.value(1)

    def deselect(self):
        self.cs.value(0)
Beispiel #10
0
class HCSR04:
    """
    Driver to use the untrasonic sensor HC-SR04.
    The sensor range is between 2cm and 4m.
    The timeouts received listening to echo pin are converted to OSError('Out of range')
    """
    # Timeout is based in chip range limit (400cm)
    TIMEOUT_US = 500 * 2 * 30

    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500 * 2 * 30):
        """
        trigger_pin: Output pin to send pulses
        echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor
        echo_timeout_us: Timeout in microseconds to listen to echo pin. 
        By default is based in sensor limit range (4m)
        """
        self.echo_timeout_us = echo_timeout_us
        # Init trigger pin (out)
        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
        self.trigger.off()

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

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

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

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

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

        # To calculate the distance we get the pulse_time and divide it by 2
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.034320 cm/us that is 1cm each 29.1us
        cms = (pulse_time / 2) / 29.1
        return cms
Beispiel #11
0
class osd:
    def __init__(self):
        alloc_emergency_exception_buf(100)
        self.screen_x = const(64)
        self.screen_y = const(20)
        self.cwd = "/sd/slides"  # shown on startup
        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()
        self.enable = bytearray(1)
        self.timer = Timer(3)
        self.init_slides()
        self.files2slides()
        self.start_bgreader()
        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:  # btn5 cursor left
                        self.updir()
                    if btn == 65:  # btn6 cursor right
                        self.select_entry()
                else:
                    if btn == 33:  # btn5 cursor left
                        self.change_slide(-1)
                    if btn == 65:  # btn6 cursor right
                        self.change_slide(1)
                    self.show_slide()

    @micropython.viper
    def show_slide(self):
        addr = int(self.xres) * int(
            self.yres) * (int(self.vi) % int(self.ncache))
        self.cs.on()
        self.rgtr(0x19, self.i24(addr))
        self.cs.off()

    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(".ppm"):
                self.files2slides()
                self.start_bgreader()
                self.enable[0] = 0
                self.osd_enable(0)

    @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
        self.file0 = len(self.direntries)
        for fname in ls:
            stat = os.stat(self.fullpath(fname))
            if stat[0] & 0o170000 != 0o040000:
                self.direntries.append([fname, 0, stat[6]])  # file
        self.nfiles = len(self.direntries) - self.file0
        gc.collect()

    # *** SLIDESHOW ***
    # self.direntries, self.file0
    def init_slides(self):
        self.xres = 800
        self.yres = 600
        self.bpp = 16
        membytes = 32 * 1024 * 1024
        self.slide_pixels = self.xres * self.yres
        self.ncache = membytes // (self.slide_pixels * self.bpp // 8)
        #self.ncache=7 # NOTE debug
        self.priority_forward = 2
        self.priority_backward = 1
        self.nbackward = self.ncache * self.priority_backward // (
            self.priority_forward + self.priority_backward)
        self.nforward = self.ncache - self.nbackward
        #print(self.nforward, self.nbackward, self.nbackward+self.nforward)
        self.rdi = 0  # currently reading image
        self.prev_rdi = -1
        self.vi = 0  # currently viewed image
        self.cache_li = []  # image to be loaded
        self.cache_ti = []  # top image
        self.cache_ty = []  # top good lines 0..(y-1)
        self.cache_tyend = []  # top y load max
        self.cache_bi = []  # bot image
        self.cache_by = []  # bot good lines y..yres
        for i in range(self.ncache):
            self.cache_li.append(i)
            self.cache_ti.append(-1)
            self.cache_ty.append(0)
            self.cache_tyend.append(self.yres)
            self.cache_bi.append(-1)
            self.cache_by.append(0)
        self.bg_file = None
        self.PPM_line_buf = bytearray(3 * self.xres)
        self.rb = bytearray(256)  # reverse bits
        self.init_reverse_bits()
        self.finished = 1

    def files2slides(self):
        self.finished = 1
        self.bg_file = None
        self.rdi = 0
        self.prev_rdi = -1
        self.vi = 0
        self.show_slide()
        self.nslides = 0
        self.slide_fi = []  # file index in direntries
        self.slide_xres = []
        self.slide_yres = []
        self.slide_pos = []
        for i in range(self.nfiles):
            filename = self.fullpath(self.direntries[self.file0 + i][0])
            f = open(filename, "rb")
            line = f.readline(1000)
            if line[0:2] == b"P6":  # PPM header
                line = b"#"
                while line[0] == 35:  # skip commented lines
                    line = f.readline(1000)
                xystr = line.split(b" ")
                xres = int(xystr[0])
                yres = int(xystr[1])
                line = f.readline(1000)
                if int(line) == 255:  # 255 levels supported only
                    self.slide_fi.append(self.file0 + i)
                    self.slide_xres.append(xres)
                    self.slide_yres.append(yres)
                    self.slide_pos.append(f.tell())
                    self.nslides += 1
                    #if self.nslides>=256:
                    #  break
        # discard cache
        for i in range(self.ncache):
            ci = i % self.nslides
            if i < self.nslides:
                self.cache_li[ci] = i
            else:
                self.cache_li[ci] = -1
            self.cache_ti[ci] = -1
            self.cache_ty[ci] = 0
            self.cache_tyend[ci] = self.yres
            self.cache_bi[ci] = -1
            self.cache_by[ci] = 0

    # choose next, ordered by priority
    def next_to_read(self):
        before_first = self.nbackward - self.vi
        if before_first < 0:
            before_first = 0
        after_last = self.vi + self.nforward - self.nslides
        if after_last < 0:
            after_last = 0
        #print("before_first=%d after_last=%d" % (before_first,after_last))
        next_forward_slide = -1
        i = self.vi
        n = i + self.nforward + before_first - after_last
        if n < 0:
            n = 0
        if n > self.nslides:
            n = self.nslides
        while i < n:
            ic = i % self.ncache
            if self.cache_ti[ic]!=self.cache_li[ic] \
            or self.cache_ty[ic]<self.yres:
                next_forward_slide = i
                break
            i += 1
        next_backward_slide = -1
        i = self.vi - 1
        n = i - self.nbackward - after_last + before_first
        if n < 0:
            n = 0
        if n > self.nslides:
            n = self.nslides
        while i >= n:
            ic = i % self.ncache
            if self.cache_ti[ic]!=self.cache_li[ic] \
            or self.cache_ty[ic]<self.yres:
                next_backward_slide = i
                break
            i -= 1
        next_reading_slide = -1
        if next_forward_slide >= 0 and next_backward_slide >= 0:
            if (next_forward_slide-self.vi)*self.priority_backward < \
              (self.vi-next_backward_slide)*self.priority_forward:
                next_reading_slide = next_forward_slide
            else:
                next_reading_slide = next_backward_slide
        else:
            if next_forward_slide >= 0:
                next_reading_slide = next_forward_slide
            else:
                if next_backward_slide >= 0:
                    next_reading_slide = next_backward_slide
        return next_reading_slide

    # image to be discarded at changed view
    def next_to_discard(self) -> int:
        return (self.vi + self.nforward - 1) % self.ncache

    # which image to replace after changing slide
    def replace(self, mv):
        dc_replace = -1
        if mv > 0:
            dc_replace = self.vi + self.nforward - 1
            if dc_replace >= self.nslides:
                dc_replace -= self.ncache
        if mv < 0:
            dc_replace = (self.vi - self.nbackward - 1)
            if dc_replace < 0:
                dc_replace += self.ncache
        return dc_replace

    # change currently viewed slide
    # discard images in cache
    def change_slide(self, mv):
        vi = self.vi + mv
        if vi < 0 or vi >= self.nslides or mv == 0:
            return
        self.cache_li[self.next_to_discard()] = self.replace(mv)
        self.vi = vi
        self.cache_li[self.next_to_discard()] = self.replace(mv)
        self.rdi = self.next_to_read()
        if self.rdi >= 0:
            self.start_bgreader()

    @micropython.viper
    def init_reverse_bits(self):
        p8rb = ptr8(addressof(self.rb))
        for i in range(256):
            v = i
            r = 0
            for j in range(8):
                r <<= 1
                r |= v & 1
                v >>= 1
            p8rb[i] = r

    # convert PPM line RGB888 to RGB565, bits reversed
    @micropython.viper
    def ppm2pixel(self):
        p8 = ptr8(addressof(self.PPM_line_buf))
        p8rb = ptr8(addressof(self.rb))
        xi = 0
        yi = 0
        yn = 2 * int(self.xres)
        while yi < yn:
            r = p8[xi]
            g = p8[xi + 1]
            b = p8[xi + 2]
            p8[yi] = p8rb[(r & 0xF8) | ((g & 0xE0) >> 5)]
            p8[yi + 1] = p8rb[((g & 0x1C) << 3) | ((b & 0xF8) >> 3)]
            xi += 3
            yi += 2

    def read_scanline(self):
        bytpp = self.bpp // 8  # on screen
        rdi = self.rdi % self.ncache
        self.bg_file.readinto(self.PPM_line_buf)
        if self.slide_xres[self.rdi] != self.xres:
            self.bg_file.seek(self.slide_pos[self.rdi] +
                              3 * self.slide_xres[self.rdi] *
                              (self.cache_ty[rdi] + 1))
        self.ppm2pixel()
        # write PPM_line_buf to screen
        addr = self.xres * (rdi * self.yres + self.cache_ty[rdi])
        # DMA transfer <= 2048 bytes each
        # DMA transfer must be divided in N buffer uploads
        # buffer upload <= 256 bytes each
        nbuf = 8
        astep = 200
        abuf = 0
        self.cs.on()
        self.rgtr(0x16, self.i24(addr))
        for j in range(nbuf):
            self.rgtr(0x18, self.PPM_line_buf[abuf:abuf + astep])
            abuf += astep
        self.rgtr(0x17, self.i24(nbuf * astep // bytpp - 1))
        self.cs.off()

    # file should be already closed when calling this
    def next_file(self):
        #print("next_file")
        filename = self.fullpath(self.direntries[self.slide_fi[self.rdi]][0])
        self.bg_file = open(filename, "rb")
        rdi = self.rdi % self.ncache
        # Y->seek to first position to read from
        self.bg_file.seek(self.slide_pos[self.rdi] +
                          3 * self.slide_xres[self.rdi] * self.cache_ty[rdi])
        print("%d RD %s" % (self.rdi, filename))

    # background read, call it periodically
    def bgreader(self, timer):
        if self.rdi < 0:
            self.finished = 1
            self.timer.deinit()
            return
        rdi = self.rdi % self.ncache
        if self.cache_ti[rdi] != self.cache_li[rdi]:
            # cache contains different image than the one to be loaded
            # y begin from top
            self.cache_ti[rdi] = self.cache_li[rdi]
            self.cache_ty[rdi] = 0
            # y end depends on cache content
            # if bottom part is already in cache, reduce tyend
            if self.cache_bi[rdi] == self.cache_ti[rdi]:
                self.cache_tyend[rdi] = self.cache_by[rdi]
            else:
                self.cache_tyend[rdi] = self.yres
            # update self.rdi after cache_ti[rdi] has changed
            self.rdi = self.cache_ti[rdi]
            rdi = self.rdi % self.ncache
        # after self.rdi and cache_ty has been updated
        # call next file
        if self.prev_rdi != self.rdi or self.bg_file == None:
            # file changed, close and reopen
            if self.bg_file:  # maybe not needed, python will auto-close?
                self.bg_file.close()
                self.bg_file = None
            self.next_file()
            self.prev_rdi = self.rdi
        if self.cache_ty[rdi] < self.cache_tyend[rdi]:
            # file read
            self.read_scanline()
            self.cache_ty[rdi] += 1
            if self.cache_ty[rdi] > self.cache_by[rdi]:
                self.cache_by[rdi] = self.cache_ty[rdi]
        if self.cache_ty[rdi] >= self.cache_tyend[rdi]:
            # slide complete, close file, find next
            self.cache_ty[rdi] = self.yres
            self.cache_bi[rdi] = self.cache_li[rdi]
            self.cache_by[rdi] = 0
            self.bg_file = None
            self.rdi = self.next_to_read()
            if self.rdi < 0:
                self.finished = 1
                return
        self.timer.init(mode=Timer.ONE_SHOT, period=0, callback=self.bgreader)

    def start_bgreader(self):
        if self.finished:
            self.finished = 0
            self.timer.init(mode=Timer.ONE_SHOT,
                            period=1,
                            callback=self.bgreader)

    # convert integer to 24-bit RGTR parameter
    def i24(self, i: int):
        return bytearray([
            self.rb[(i >> 16) & 0xFF], self.rb[(i >> 8) & 0xFF],
            self.rb[i & 0xFF]
        ])

    # x is bytearray, length 1-256
    def rgtr(self, cmd, x):
        self.spi.write(bytearray([self.rb[cmd], self.rb[len(x) - 1]]))
        self.spi.write(x)

    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(2)
        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(0)
        return b

    def poke(self, addr, data):
        self.ctrl(2)
        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(0)
Beispiel #12
0
class Temperature():
    def __init__(self, state):
        self.state = state
        self.adc = ADC(config.ADC)
        self.solar_pin = Pin(config.SOLAR_GPIO, mode=Pin.OUT)
        self.solar_pin.off()
        self.tank_pin = Pin(config.TANK_GPIO, mode=Pin.OUT)
        self.tank_pin.off()
        self.timer = Timer(-1)
        self.counter = 0
        self.solar_temp = [self.read_solar_temp()] * config.AVERAGE
        self.tank_temp = [self.read_tank_temp()] * config.AVERAGE
        self.update()

    def update(self):
        self.counter = (self.counter + 1) % config.AVERAGE
        self.solar_temp[self.counter] = self.read_solar_temp()
        self.tank_temp[self.counter] = self.read_tank_temp()
        if self.counter == 1:
            self.state.set(
                solar_temp=round(sum(self.solar_temp) / config.AVERAGE),
                tank_temp=round(sum(self.tank_temp) / config.AVERAGE),
            )

    def read_solar_temp(self):
        self.solar_pin.on()
        return config.solar_adc_to_temp(self.read_adc())

    def read_tank_temp(self):
        self.tank_pin.on()
        return config.tank_adc_to_temp(self.read_adc())

    def read_adc(self):
        status_led.invert()
        n = 5
        val = 0
        for i in range(n):
            sleep_ms(100)
            val += self.adc.read()
        self.solar_pin.off()
        self.tank_pin.off()
        status_led.invert()
        return val / n

    def start(self, state):
        self._sched = False
        self.timer.deinit()

        def _cb(_):
            self._sched = False
            self.update()

        def cb(_):
            if not self._sched:
                self._sched = True
                schedule(_cb, 0)

        self.timer.init(period=round(config.FREQ * 1000), callback=cb)

    def stop(self, state):
        self.timer.deinit()
Beispiel #13
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()
                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()
                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(".col") \
            or filename.endswith(".sg") \
            or filename.endswith(".sms") \
            or filename.endswith(".gg") \
            or filename.endswith(".snes") \
            or filename.endswith(".smc") \
            or filename.endswith(".bin") \
            or filename.endswith(".BIN") \
            or filename.endswith(".dsk") \
            or filename.endswith(".sfc"):
                import ld_nes
                s = ld_nes.ld_nes(self.spi, self.cs)
                s.ctrl(2)
                s.load_stream(open(filename, "rb"))
                s.ctrl(1)
                s.ctrl(0)
                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
            else:
                self.direntries.append([fname, 0, stat[6]])  # file
            gc.collect()
Beispiel #14
0
class driver:
    def __init__(self,
                 specific,
                 dc,
                 mosi,
                 cs,
                 clk,
                 busy,
                 reset=-1,
                 miso=34,
                 rotation=0):
        self.dc = Pin(dc, Pin.OUT)
        self.cs = Pin(cs, Pin.OUT)
        self.busy = Pin(busy, Pin.IN)
        self.rst = None
        if reset >= 0:
            self.rst = Pin(reset, Pin.OUT)
        self.spi = SPI(-1,
                       baudrate=2000000,
                       polarity=0,
                       phase=0,
                       bits=8,
                       firstbit=SPI.MSB,
                       sck=Pin(clk),
                       mosi=Pin(mosi),
                       miso=Pin(miso))
        self.spibyte = bytearray(1)
        self.rb = bytearray(256)  # reverse bits
        self.init_reverse_bits()
        if rotation == 0:
            self.DATA_ENTRY = 0
            self.X_START = specific.width - 1
            self.Y_START = specific.height - 1
            self.X_END = 0
            self.Y_END = 0
        if rotation == 1:
            self.DATA_ENTRY = 6
            self.X_START = specific.width - 1
            self.Y_START = 0
            self.X_END = 0
            self.Y_END = specific.height - 1
        if rotation == 2:
            self.DATA_ENTRY = 3
            self.X_START = 0
            self.Y_START = 0
            self.X_END = specific.width - 1
            self.Y_END = specific.height - 1
        if rotation == 3:
            self.DATA_ENTRY = 5
            self.X_START = 0
            self.Y_START = specific.height - 1
            self.X_END = specific.width - 1
            self.Y_END = 0
        self.width = specific.width
        self.height = specific.height
        self.specific = specific
        self.refresh = bytearray(1)

    @micropython.viper
    def init_reverse_bits(self):
        p8rb = ptr8(addressof(self.rb))
        for i in range(256):
            v = i
            r = 0
            for j in range(8):
                r <<= 1
                r |= v & 1
                v >>= 1
            p8rb[i] = r

    @micropython.viper
    def init(self):
        self.reset()
        self.send_command(DRIVER_OUTPUT_CONTROL)
        self.send_data(int(self.height) - 1)
        self.send_data((int(self.height) - 1) >> 8)
        self.send_data(0x00)  # GD = 0, SM = 0, TB = 0
        if int(self.specific.IL) == 3820:
            # waveshare 2.9" BW 128x296
            self.send_command(BOOSTER_SOFT_START_CONTROL)
            self.send_data(0xD7)
            self.send_data(0xD6)
            self.send_data(0x9D)
            self.send_command(WRITE_VCOM_REGISTER)
            self.send_data(0xA8)
            self.send_command(SET_DUMMY_LINE_PERIOD)
            self.send_data(0x1A)  # 4 dummy lines per gate
            self.send_command(SET_GATE_TIME)
            self.send_data(0x08)  # 2us per line
        if int(self.specific.IL) == 3829:
            # heltec 1.54" BW 200x200
            self.send_command(BORDER_WAVEFORM_CONTROL)
            self.send_data(0x01)
            self.send_command(TEMPERATURE_SENSOR_SELECTION)
            self.send_data(0x80)  # built-in temperature sensor
            self.send_command(DISPLAY_UPDATE_CONTROL_2
                              )  # Load Temperature and waveform setting
            self.send_data(0xB1)
            self.send_command(MASTER_ACTIVATION)
            self.wait_until_idle()
        self.send_command(DATA_ENTRY_MODE_SETTING)  # screen rotation
        self.send_data(self.DATA_ENTRY)
        self.set_full_refresh()

    @micropython.viper
    def set_lut(self, lut):
        p8 = ptr8(addressof(lut))
        self.send_command(WRITE_LUT_REGISTER)
        for i in range(30):
            self.send_data(p8[i])

    @micropython.viper
    def _spi_transfer(self, data: int):
        p8 = ptr8(addressof(self.spibyte))
        p8[0] = data
        self.cs.off()
        self.spi.write(self.spibyte)
        self.cs.on()

    @micropython.viper
    def send_command(self, command: int):
        self.dc.off()
        self._spi_transfer(command)

    @micropython.viper
    def send_data(self, data: int):
        self.dc.on()
        self._spi_transfer(data)

    @micropython.viper
    def wait_until_idle(self):
        while (self.busy()):  # 0: idle, 1: busy
            sleep_ms(100)

    @micropython.viper
    def reset(self):
        if self.rst:
            self.rst.on()
            sleep_ms(200)
            self.rst.off()
            sleep_ms(10)
            self.rst.on()
            sleep_ms(200)
        else:
            self.send_command(SW_RESET)
            self.wait_until_idle()

    @micropython.viper
    def set_memory_area(self, x_start: int, y_start: int, x_end: int,
                        y_end: int):
        self.send_command(SET_RAM_X_ADDRESS_START_END_POSITION)
        self.send_data(x_start >> 3)
        self.send_data(x_end >> 3)
        self.send_command(SET_RAM_Y_ADDRESS_START_END_POSITION)
        self.send_data(y_start)
        self.send_data(y_start >> 8)
        self.send_data(y_end)
        self.send_data(y_end >> 8)

    @micropython.viper
    def set_memory_pointer(self, x: int, y: int):
        self.send_command(SET_RAM_X_ADDRESS_COUNTER)
        self.send_data(x >> 3)
        self.send_command(SET_RAM_Y_ADDRESS_COUNTER)
        self.send_data(y)
        self.send_data(y >> 8)
        self.wait_until_idle()

    @micropython.viper
    def write_frame(self, frame_buffer, cmd: int):
        self.set_memory_area(self.X_START, self.Y_START, self.X_END,
                             self.Y_END)
        self.set_memory_pointer(self.X_START, self.Y_START)
        self.send_command(cmd)
        p8 = ptr8(addressof(frame_buffer))
        for i in range(int(len(frame_buffer))):
            self.send_data(p8[i])

    @micropython.viper
    def write_frame_rb(self, frame_buffer, cmd: int):
        p8 = ptr8(addressof(frame_buffer))
        p8rb = ptr8(addressof(self.rb))
        self.send_command(cmd)
        for i in range(int(len(frame_buffer))):
            self.send_data(p8rb[p8[i]])

    @micropython.viper
    def set_full_refresh(self):
        if self.specific.lut_full_refresh:
            self.set_lut(self.specific.lut_full_refresh)
        p8 = ptr8(addressof(self.refresh))
        p8[0] = int(self.specific.full_refresh)

    @micropython.viper
    def set_partial_refresh(self):
        if self.specific.lut_partial_refresh:
            self.set_lut(self.specific.lut_partial_refresh)
        p8 = ptr8(addressof(self.refresh))
        p8[0] = int(self.specific.partial_refresh)

    @micropython.viper
    def refresh_frame(self):
        self.send_command(DISPLAY_UPDATE_CONTROL_2)
        self.send_data(int(self.refresh[0]))
        self.send_command(MASTER_ACTIVATION)
        self.send_command(TERMINATE_FRAME_READ_WRITE)
        self.wait_until_idle()

    @micropython.viper
    def display_frame(self, frame_buffer):
        if int(self.DATA_ENTRY) & 4:  # fix missing framebuf.MONO_VMSB
            self.write_frame_rb(frame_buffer, WRITE_RAM)
        else:
            self.write_frame(frame_buffer, WRITE_RAM)
        self.refresh_frame()

    # after this, call epd.init() to awaken the module
    @micropython.viper
    def sleep(self):
        self.send_command(DEEP_SLEEP_MODE)
Beispiel #15
0
class ShiftRegisterSpeedTest:
    def __init__(self):
        # === Shift Register ===
        self.clock = Pin(5, Pin.OUT)
        self.data = Pin(4, Pin.OUT)
        self.latch = Pin(2, Pin.OUT)
        self.row_max = 5  # Five rows of transistor drivers
        self.col_max = 8  # Eight columns of shift registers
        self.bitmap = []
        self.bit_values = [1, 2, 4, 8, 16, 32, 64, 128]

        # === Column Transistors ===
        self.previous_row = 0
        self.row_pins = [
            Pin(0, Pin.OUT),
            Pin(15, Pin.OUT),
            Pin(13, Pin.OUT),
            Pin(12, Pin.OUT),
            Pin(14, Pin.OUT)
        ]

        self.bitmap.append([1, 0, 0, 0, 0, 0, 0, 0])  # row 0
        self.bitmap.append([2, 0, 0, 0, 0, 0, 0, 0])  # row 1
        self.bitmap.append([3, 0, 0, 0, 0, 0, 0, 0])  # row 2
        self.bitmap.append([4, 0, 0, 0, 0, 0, 0, 0])  # row 3
        self.bitmap.append([5, 0, 0, 0, 0, 0, 0, 0xff])  # row 4

    @micropython.native
    def shift_out(self, bits):
        for i in range(8):
            #value = bits & (1 << i)  # Is bit set or cleared?
            if bits & self.bit_values[i] > 0:
                self.data.on()
            else:
                self.data.off()
            self.clock.on()  # pulsing clock HIGH then LOW to shift data
            self.clock.off()

    # def shift_out(self, bits):
    #     for i in range(8):
    #         value = bits & (1 << i)  # Is bit set or cleared?
    #         self.data.value(1 if value > 0 else 0)
    #         self.clock.on()  # pulsing clock HIGH then LOW to shift data
    #         self.clock.off()

    @micropython.native
    def refresh(self, timer):
        #new_row = self.previous_row + 1 if (self.previous_row + 1) < self.row_max else 0
        new_row = self.previous_row + 1
        if new_row >= self.row_max:
            new_row = 0

        # == Shift out all the columns for new row (8 digits x 8 bits = 64 bits) ==
        self.latch.off()  # Don't show changes to the bits on the output lines
        for c in range(self.col_max):
            segment_bits = self.bitmap[new_row][c]
            self.shift_out(segment_bits)

        # == Flip it ==
        # Turn off current row
        self.row_pins[self.previous_row].off()

        # Latch data for new row
        self.latch.on()  # Show data on output lines

        # Turn on new row
        self.row_pins[new_row].on()
        self.previous_row = new_row  # This will be the new column, next time round.

    def main(self):
        flash = Timer(0)
        flash.init(freq=1 * self.row_max * self.col_max,
                   mode=Timer.PERIODIC,
                   callback=self.refresh)

        while True:
            for i in range(64):
                time.sleep(1)
Beispiel #16
0
class Display:
    def __init__(self):
        self.en_5V = Pin(5, Pin.OUT)
        self.pin_hrdy = Pin(21, mode=Pin.IN)
        self.pin_reset = Pin(22, mode=Pin.OUT)
        self.pin_cs = Pin(15, mode=Pin.OUT)
        self.spi = SPI(baudrate=2400000,
                       polarity=0,
                       phase=0,
                       bits=8,
                       firstbit=SPI.MSB,
                       sck=Pin(14),
                       mosi=Pin(13),
                       miso=Pin(12))

    def On(self):
        self.en_5V.on()
        self.en_5V.value(1)
        self.pin_cs.on()
        self.pin_reset.on()
        print("Display enabled")

    def Off(self):
        self.en_5V.off()
        self.pin_cs.off()
        self.pin_reset.off()
        print("Display disabled")

    def WaitforReady(self):
        while self.pin_hrdy.value() == 0:
            machine.idle()

    def WriteCmd(self, Cmd1, Cmd2):
        self.WaitforReady()
        self.pin_cs.value(0)
        self.WaitforReady()
        self.spi.write(bytearray([0x60, 0x00]))  #Praeamble Cmd
        self.WaitforReady()
        self.spi.write(bytearray([Cmd1, Cmd2]))
        self.pin_cs.value(1)

    def WriteData(self, Data, AnzData):
        self.WaitforReady()
        self.pin_cs.value(0)
        self.WaitforReady()
        self.spi.write(bytes([0x00, 0x00]))  #Praeamble Write
        self.WaitforReady()
        a = 0
        while a < AnzData:
            self.spi.write(bytearray([Data[a], Data[a + 1]]))
            self.WaitforReady()
            a += 2  #Immer 2 Schritte pro Runde
        self.pin_cs.value(1)
        self.WaitforReady()

    def WriteReg(self, Addr, Data, AnzData):
        self.WaitforReady()
        self.pin_cs.value(0)
        self.WaitforReady()
        self.spi.write(bytes([0x60, 0x00]))  #Praeamble Write
        self.WaitforReady()
        self.spi.write(bytes([0x00, 0x11]))  #CMD Write Reg
        self.pin_cs.value(1)
        self.WaitforReady()
        self.pin_cs.value(0)
        self.WaitforReady()
        self.spi.write(bytes([0x00, 0x00]))  #Praeamble Write
        self.WaitforReady()
        self.spi.write(Addr)  #write address of register
        self.WaitforReady()
        a = 0
        while a < AnzData:
            self.spi.write(bytearray([Data[a], Data[a + 1]]))
            self.WaitforReady()
            a += 2  #Immer 2 Schritte pro Runde
        self.pin_cs.value(1)
        self.WaitforReady()

    def ReadReg(self, Addr, AnzData, Data):
        self.WriteCmd(0x00, 0x10)  #Read Register Command
        self.WriteData(Addr, 2)  #read Address Packet
        self.ReadData(Data, AnzData)

    def ReadData(self, Data, AnzData):
        self.WaitforReady()
        self.pin_cs.value(0)
        self.WaitforReady()
        self.spi.write(bytes([0x10, 0x00]))  #Praeamble Read
        self.WaitforReady()
        print('Start Read')
        self.spi.read(1)
        self.WaitforReady()

        for a in range(AnzData):
            self.WaitforReady()
            Data.append(self.spi.read(1))
        #print(Data)
        self.pin_cs.value(1)
        self.WaitforReady()

    def send_data_over_spi(self, picture_data_spi):
        #Auflösung
        PixB = 1200
        PixBx = [0x04, 0xB0]
        PixH = 825
        PixHx = [0x03, 0x39]
        BpP = 4  # Bit per Pixel

        self.pin_cs.value(1)

        #Display Initialisation
        #--------------------------------------------------

        #Reset
        print('ResetSPI')
        self.pin_reset.value(0)
        time.sleep(0.5)
        self.pin_reset.value(1)
        self.WaitforReady()

        print('reset')
        #Cmd SYS_RUN
        print('System_Run')
        self.WriteCmd(0x00, 0x01)

        #-Load Picture-----------------------------------------
        print('Load Picture')

        #Write Image Buffer Adress in Register Command
        print('Load Picture -Buffer Adress')

        LISAR = bytes([0x02, 0x0A])
        WordH = [0x00, 0x11]
        self.WriteReg(LISAR, WordH, 2)

        LISAR = bytes([0x02, 0x08])
        WordL = [0xA1, 0xE0]
        self.WriteReg(LISAR, WordL, 2)

        #Write Area Image Info
        print('Load Picture -Area Info')
        #AreaImgInfo=[0+EndianType, BpP+Rotate, X, X, Y, Y, PixB, PixB, PixH, PixH,]
        BitperPix = {2: 0x00, 4: 0x20, 8: 0x30}
        AreaImgInfo = [
            0x01,
            BitperPix.get(4), 0x00, 0x00, 0x00, 0x00, 0x04, 0xB0, 0x03, 0x39
        ]

        self.WriteCmd(0x00, 0x21)  #LD_IMAGE_AREA
        self.WriteData(AreaImgInfo, 10)

        #Write Picture Data
        print('Load Picture -Data')

        self.pin_cs.value(0)
        #Praeamble Data
        self.spi.write(bytes([0x00, 0x00]))
        self.WaitforReady()

        #print(len(picture_data_spi))
        pix = int(PixB * BpP / 8)
        foo = bytes(1200)

        # for i in range(PixH):
        #     line = picture_data_spi[(i*pix):((i+1)*pix)]
        #     print(str((i*(pix+1)+1))+ ":"  + str((i+1)*(pix+1)))
        #     self.spi.write(line) #eine Zeile=1200 pixel
        #     #if(i%10==0):
        #         #print(str(i/PixH*100) + " %")

        #Send the data
        self.spi.write(picture_data_spi)

        self.pin_cs.value(1)

        #Send Load Image End
        print('Load Picture -End')
        print('picture end')
        self.WriteCmd(0x00, 0x22)

        #Display Area Command
        print('Disp Area Cmd')
        #AreaImgInfo = [X, X, Y, Y, PixB, PixB, PixH, PixH, Mode, Mode]
        AreaCmd = [
            0x00, 0x00, 0x00, 0x00, PixBx[0], PixBx[1], PixHx[0], PixHx[1],
            0x00, 0x02
        ]
        self.WriteCmd(0x00, 0x34)  #Disp Area Cmd
        self.WriteData(AreaCmd, 10)
Beispiel #17
0
from machine import Pin
import time

pinEnabled = Pin(5, Pin.OUT,value=0)
pinStep = Pin(4, Pin.OUT)
pinDirection = Pin(0, Pin.OUT)

stepsPerRevolution = 200

while True:

    pinDirection.on()

    for i in range(0,stepsPerRevolution):
        pinStep.on()
        time.sleep_ms(10)
        pinStep.off()
        time.sleep_ms(10)

    pinDirection.off()

    for i in range(0,stepsPerRevolution):
        pinStep.on()
        time.sleep_ms(10)
        pinStep.off()
        time.sleep_ms(10)    
Beispiel #18
0
class BatteryMonitor:

    ADC_MAX = 1023
    BATTERY_MAX_V = 4.2
    SOLAR_MAX_V = 6

    def __init__(self):
        self.sela = Pin(4, Pin.OUT)
        self.selb = Pin(5, Pin.OUT)
        self.selc = Pin(14, Pin.OUT)
        self.charge_en = Pin(12, Pin.OUT)
        self.adc = ADC(0)

    def connect_solar_panel(self) -> None:
        self.charge_en.off()

    def disconnect_solar_panel(self) -> None:
        self.charge_en.on()

    def select_solar_panel(self) -> None:
        self.sela.off()
        self.selb.off()
        self.selc.off()

    def select_battery(self) -> None:
        self.sela.on()
        self.selb.off()
        self.selc.off()

    def read_adc(self) -> float:
        return self.adc.read()

    def read_battery_voltage(self) -> None:
        """ Battery voltage is between 0 and 4.2 """
        self.disconnect_solar_panel()
        self.select_battery()
        adc_reading = self.read_adc()
        volt = adc_reading / BatteryMonitor.ADC_MAX * BatteryMonitor.BATTERY_MAX_V * 1.122

        print("Battery ADC: " + str(adc_reading))
        print("Battery Voltage: " + str(volt))
        self.connect_solar_panel()
        return volt

    def read_solar_voltage(self) -> None:
        """ Battery voltage is between 0 and 4.2 """
        self.disconnect_solar_panel()
        self.select_solar_panel()
        adc_reading = self.read_adc()
        volt = adc_reading / BatteryMonitor.ADC_MAX * BatteryMonitor.SOLAR_MAX_V * 1.037

        print("Solar ADC: " + str(adc_reading))
        print("Solar Voltage: " + str(volt))
        self.connect_solar_panel()
        return volt
Beispiel #19
0
from machine import Pin

sta_if = network.WLAN(network.STA_IF)  # create station interface
sta_if.active(True)  # activate the interface
sta_if.scan()  # scan for access points
sta_if.isconnected()  # check if the station is connected to an AP
sta_if.connect('CloudCube_TPE_Office', 'cloudcube54729082')  # connect to an AP
sta_if.config('mac')  # get the interface's MAC adddress
print("sta_if.ifconfig=")
sta_if.ifconfig()  # get the interface's IP/netmask/gw/DNS addresses

ap_if = network.WLAN(network.AP_IF)  # create access-point interface
ap_if.active(True)  # activate the interface
ap_if.config(essid='ESP-micropython-Tony',
             authmode=network.AUTH_WPA_WPA2_PSK,
             password="******")  # set the ESSID of the access point

while True:
    p2 = Pin(2, Pin.OUT)  # create output pin on GPIO16
    p2.on()  # set pin to "on" (high) level
    time.sleep(1)
    p2.off()  # set pin to "off" (low) level
    time.sleep(1)
    p2.value(1)  # set pin to on/high
"""
p2 = Pin(2, Pin.IN)     # create input pin on GPIO2
print(p2.value())       # get value, 0 or 1
p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation
"""
Beispiel #20
0
import credentials
import dht
from machine import Pin
import network
import ubinascii
import ujson
import urequests
from utime import sleep_ms

sleep_ms(4000)
sensor = dht.DHT22(Pin(4))
blue_led = Pin(2, Pin.OUT)

while True:
    data_dict = {}
    sensor.measure()
    print("Measured")
    data_dict['mac_id'] = str(
        ubinascii.hexlify(network.WLAN().config('mac'), ':').decode())
    data_dict['temp'] = str(sensor.temperature())
    data_dict['hum'] = str(sensor.humidity())
    blue_led.off()
    print("Sending data...")
    response = urequests.post(credentials.endpoint,
                              data=ujson.dumps(data_dict),
                              headers={'Content-Type': 'application/json'})
    print("Server response: ", response.text)
    blue_led.on()
    sleep_ms(3000)
Beispiel #21
0
class WebServer:
    TITLE = "LED Control"
    GPIO_NUM = 2

    def __init__(self):
        self.pin = Pin(self.GPIO_NUM)
        self.pin.init(Pin.OUT)
        self.led_off()

    def led_off(self):
        self.pin.on()

    def led_on(self):
        self.pin.off()

    def ok(self, socket, query):
        socket.write("HTTP/1.1 OK\r\n\r\n")
        socket.write("<!DOCTYPE html><title>" + self.TITLE + "</title><body>")
        socket.write(self.TITLE + " status: ")
        if not self.pin.value():
            socket.write("<span style='color:green'>ON</span>")
        else:
            socket.write("<span style='color:red'>OFF</span>")

        socket.write("<br>")

        if not self.pin.value():
            socket.write("<form method='POST' action='/off?" + query.decode() +
                         "'>" + "<input type='submit' value='turn OFF'>" +
                         "</form>")
        else:
            socket.write("<form method='POST' action='/on?" + query.decode() +
                         "'>" + "<input type='submit' value='turn ON'>" +
                         "</form>")

    def err(self, socket, code, message):
        socket.write("HTTP/1.1 " + code + " " + message + "\r\n\r\n")
        socket.write("<h1>" + message + "</h1>")

    def handle(self, socket):
        (method, url, version) = socket.readline().split(b" ")
        if b"?" in url:
            (path, query) = url.split(b"?", 2)
        else:
            (path, query) = (url, b"")
        while True:
            header = socket.readline()
            if header == b"":
                return
            if header == b"\r\n":
                break

        if version != b"HTTP/1.0\r\n" and version != b"HTTP/1.1\r\n":
            self.err(socket, "505", "Version Not Supported")
        elif method == b"GET":
            if path == b"/":
                self.ok(socket, query)
            else:
                self.err(socket, "404", "Not Found")
        elif method == b"POST":
            if path == b"/on":
                self.led_on()
                self.ok(socket, query)
            elif path == b"/off":
                self.led_off()
                self.ok(socket, query)
            else:
                self.err(socket, "404", "Not Found")
        else:
            self.err(socket, "501", "Not Implemented")

    def run(self):
        server = socket.socket()
        server.bind(('0.0.0.0', 80))
        server.listen(1)
        while True:
            try:
                (sckt, sockaddr) = server.accept()
                self.handle(sckt)
            except:
                sckt.write("HTTP/1.1 500 Internal Server Error\r\n\r\n")
                sckt.write("<h1>Internal Server Error</h1>")
                sckt.close()
class ST7735(framebuf.FrameBuffer):
    def __init__(self):
        self.baudrate = 27000000
        self.cs = Pin(5, Pin.OUT, value=1)
        self.dc = Pin(23, Pin.OUT, value=1)
        self.rst = Pin(18, Pin.OUT, value=1)
        self.spi = SPI(1,
                       baudrate=self.baudrate,
                       polarity=0,
                       phase=0,
                       bits=8,
                       firstbit=SPI.MSB,
                       sck=Pin(13),
                       mosi=Pin(15))

        self.enable_lcd_power()

        self.rst.on()
        time.sleep_ms(5)
        self.rst.off()
        time.sleep_ms(20)
        self.rst.on()
        time.sleep_ms(150)

        self.width = 80
        self.height = 160
        self.buffer = bytearray(self.width * self.height * 2)
        super().__init__(self.buffer, self.width, self.height, framebuf.RGB565)
        self.init_display()

    def enable_lcd_power(self):
        i2c = I2C(1, scl=Pin(22), sda=Pin(21), freq=100000)
        i2c.writeto_mem(0x34, 0x28, b'\xff')
        axp192_reg12 = i2c.readfrom_mem(0x34, 0x12, 1)[0]
        axp192_reg12 |= 0x0c
        i2c.writeto_mem(0x34, 0x12, bytes([axp192_reg12]))

    def init_display(self):
        for cmd, data, delay in [
            (0x01, None, 150),
            (0x11, None, 500),
            (0xb1, b'\x01\x2c\x2d', None),
            (0xb2, b'\x01\x2c\x2d', None),
            (0xb3, b'\x01\x2c\x2d\x01\x2c\x2d', None),
            (0xb4, b'\x07', None),
            (0xc0, b'\xa2\x02\x84', None),
            (0xc1, b'\xc5', None),
            (0xc2, b'\x0a\x00', None),
            (0xc3, b'\x8a\x2a', None),
            (0xc4, b'\x8a\xee', None),
            (0xc5, b'\x0e', None),
            (0x20, None, None),
            (0x36, b'\xc8', None),
            (0x3a, b'\x05', None),
            (0x2a, b'\x00\x02\x00\x81', None),
            (0x2b, b'\x00\x01\x00\xa0', None),
            (0x21, None, None),
            (0xe0,
             b'\x02\x1c\x07\x12\x37\x32\x29\x2d\x29\x25\x2b\x39\x00\x01\x03\x10',
             None),
            (0xe1,
             b'\x03\x1d\x07\x06\x2e\x2c\x29\x2d\x2e\x2e\x37\x3f\x00\x00\x02\x10',
             None),
            (0x13, None, 10),
            (0x29, None, 100),
            (0x36, b'\xcc', 10),
        ]:
            self.write_cmd(cmd)
            if data:
                self.write_data(data)
            if delay:
                time.sleep_ms(delay)
        self.fill(0)
        self.show()

    def show(self):
        self.write_cmd(0x2a)
        self.write_data(b'\x00\x1a\x00\x69')
        self.write_cmd(0x2b)
        self.write_data(b'\x00\x01\x00\xa0')
        self.write_cmd(0x2c)
        self.write_data(self.buffer)

    def write_cmd(self, cmd):
        self.dc.off()
        self.cs.off()
        self.spi.write(bytes([cmd]))
        self.cs.on()

    def write_data(self, buf):
        self.dc.on()
        self.cs.off()
        self.spi.write(buf)
        self.cs.on()
Beispiel #23
0
from machine import Pin

#Create a GPIO pin and assign it relay
#The pin to control the relay
relay = Pin(0, Pin.OUT)

while True:
    if True:    #Condition to evaluate whether to turn relay on or off
        relay.on() # Setting relay to on
    else relay.off()

Beispiel #24
0
class DDS():
    def __init__(self,
                 Pin_clk=27,
                 Pin_mosi=26,
                 Pin_miso=25,
                 Pin_rst=32,
                 Pin_up=15):
        # self.Pin_clk = Pin_clk
        # self.Pin_mosi = Pin_mosi
        # self.Pin_miso = Pin_miso
        # self.Pin_rst = Pin_rst
        # self.Pin_up = Pin_up
        self.dds_clk = Pin(Pin_clk, Pin.OUT)  #spi clk
        self.dds_up = Pin(Pin_up, Pin.OUT)
        self.dds_rst = Pin(Pin_rst, Pin.OUT)
        self.dds_data = Pin(Pin_mosi, Pin.OUT)  #spi mosi
        self.dds_spi = SPI(baudrate=300000,
                           polarity=0,
                           phase=0,
                           bits=8,
                           firstbit=SPI.MSB,
                           sck=Pin(Pin_clk),
                           mosi=Pin(Pin_mosi),
                           miso=Pin(Pin_miso))

        self.dds_init()

    def dds_init(self):
        self.dds_clk.off()
        self.dds_up.off()
        #reset
        self.dds_rst.off()
        self.dds_rst.on()
        self.dds_rst.off()
        #clk
        self.dds_clk.off()
        self.dds_clk.on()
        self.dds_clk.off()
        #up
        self.dds_up.off()
        self.dds_up.on()
        self.dds_up.off()

    def rev_str(self, a):
        temp = ''
        for ii in range(len(a)):
            temp = temp + a[-ii - 1]
        return temp

    #写入32位,从高至低(MSB)
    def write_oneword(self, addr, word):
        for i in range(4):
            worda = "0b" + word[8 * i:8 * (i + 1)]
            worda = int(worda)
            print(hex(worda))
            worda = struct.pack('b', worda)
            self.dds_spi.write(worda)

        #写入地址8位
        addra = "0b" + addr[0:8]
        addra = int(addra)
        print(hex(addra))
        addra = struct.pack('b', addra)
        self.dds_spi.write(addra)

        self.dds_up.on()
        self.dds_up.off()

    def set_freq(self, freq):
        freq = (int)(freq * 4294.967295 / 180)
        freq = int2bin.int2bin(freq, 4)
        print("origin freq : " + freq)

        y = self.rev_str(freq)
        print("reverse freq: " + y)

        addr = self.rev_str(int2bin.int2bin(0x01, 1))
        print("rev addr: " + addr)

        self.write_oneword(addr, y)
Beispiel #25
0
class ADC16():

    def __init__(self):
        self.spi = SPI(1)
        self.SCK=Pin('PA5',Pin.OUT)
        self.DO = Pin('PA6',Pin.OUT)
        self.DI = Pin('PA7',Pin.OUT)
        self.CS = Pin('PA4',Pin.OUT)
        self.RESET = Pin('PC5',Pin.OUT)
        self.DRDY = Pin('PC4',Pin.OUT) 

        self.bsp_DelayMS(10)
	
    #     self.TM7705_ResetHard()	#/* 硬件复位 */
        
    #     #/*
    #      #   在接口序列丢失的情况下,如果在DIN 高电平的写操作持续了足够长的时间(至少 32个串行时钟周期),
    #      #   TM7705 将会回到默认状态。
    #     #*/	
    #     self.bsp_DelayMS(5)
    
    #     self.TM7705_SyncSPI()		#/* 同步SPI接口时序 */
    
    #     self.bsp_DelayMS(5)
    
    #    # /* 配置时钟寄存器 */
    #     self.TM7705_WriteByte(REG_CLOCK | WRITE | CH_1)		#	/* 先写通信寄存器,下一步是写时钟寄存器 */
        
    #     self.TM7705_WriteByte(CLKDIS_0 | CLK_4_9152M | FS_50HZ)	#/* 刷新速率50Hz */
    #     #//TM7705_WriteByte(CLKDIS_0 | CLK_4_9152M | FS_500HZ);#	/* 刷新速率500Hz */
        
    #    # /* 每次上电进行一次自校准 */
    #     self.TM7705_CalibSelf(1)	#/* 内部自校准 CH1 */
    #     self.bsp_DelayMS(5)
    
    def bsp_DelayMS(self,t):
        time.sleep_ms(t)

    
    def TM7705_ResetHard(self):
        self.RESET.on()
        self.bsp_DelayMS(1)
        self.RESET.off()
        self.bsp_DelayMS(2)
        self.RESET.on()
        self.bsp_DelayMS(1)

    def TM7705_SyncSPI(self):
        self.CS.off()
        self.TM7705_Send8Bit(0xFF)
        self.TM7705_Send8Bit(0xFF)
        self.TM7705_Send8Bit(0xFF)
        self.TM7705_Send8Bit(0xFF)
        self.CS.on()

    
    

    def TM7705_Send8Bit(self,data):
        data = data%256 
         
        self.spi.write(struct.pack('B',data))

    def TM7705_WriteByte(self,data):
        self.CS.off()
        self.TM7705_Send8Bit(data) 
        self.CS.on() 

    def TM7705_Write3Byte(self,data):
        self.CS.off()
        self.TM7705_Send8Bit(data>>16)
        self.TM7705_Send8Bit(data>>8)
        self.TM7705_Send8Bit(data)
        self.CS.on()

#     def TM7705_ReadByte(self):
#         read = 0 
#         self.CS.off()
#         read = self.spi.read()
#         print(read)
#         self.CS.on()
#         return read 

#     def TM7705_Read2Byte(self):
#         self.TM7705_ReadByte()
        
#     def TM7705_Read3Byte(self):
#         self.TM7705_ReadByte()
#    ##################################待更改     
            

    def TM7705_WaitDRDY(self):
        while (self.DRDY.value()):
            time.sleep_ms(200)
        
        #等待校准


    def TM7705_WriteReg(self,_RegID,_RegValue):
        bits = 0
        if _RegID == REG_COMM or _RegID ==REG_SETUP or _RegID == REG_CLOCK:
            bits = 8
        elif _RegID ==REG_ZERO_CH1 or _RegID ==REG_FULL_CH1  or _RegID ==REG_ZERO_CH2 or _RegID ==REG_FULL_CH2 :
            bits=24
        
        self.TM7705_WriteByte(_RegID | WRITE)
        if bits==8:
            self.TM7705_WriteByte(_RegValue)
        else :
            self.TM7705_Write3Byte(_RegValue)

        

    def TM7705_CalibSelf(self,_ch):
        if _ch==1:
            # /* 自校准CH1 */
            self.TM7705_WriteByte(REG_SETUP | WRITE | CH_1)#;	#/* 写通信寄存器,下一步是写设置寄存器,通道1 */		
            self.TM7705_WriteByte(MD_CAL_SELF | __CH1_GAIN_BIPOLAR_BUF | FSYNC_0)#;#/* 启动自校准 */
            self.TM7705_WaitDRDY()#;	/* 等待内部操作完成 --- 时间较长,约180ms */
        
        elif _ch == 2:
            #   /* 自校准CH2 */
            self.TM7705_WriteByte(REG_SETUP | WRITE | CH_2)#;	/* 写通信寄存器,下一步是写设置寄存器,通道2 */
            self.TM7705_WriteByte(MD_CAL_SELF | __CH2_GAIN_BIPOLAR_BUF | FSYNC_0)#	/* 启动自校准 */
            self.TM7705_WaitDRDY()
            




        
#####read adc 
    def TM7705_ReadAdc(self,_ch):
        read = 0
        for ii in range(2):
            self.TM7705_WaitDRDY()
            if _ch == 1:
                self.TM7705_WriteByte(0x38)
            elif _ch == 2:
                self.TM7705_WriteByte(0x39)
        #read2byte
             
            read = self.spi.read()
         
        return read   
Beispiel #26
0
#Pull each pin up with an external resistor to 3.3v
#You cannot pull them in software because they do not have internal pull-up resistors !
p36 = Pin(36, Pin.IN)
p39 = Pin(39, Pin.IN)
p34 = Pin(34, Pin.IN)
p35 = Pin(35, Pin.IN)

# Antenna placeholder, when things go wrong...
AnT = 'OOPS...'

# Relay output pins see wiring diagram
Pin2 = Pin(2, Pin.OUT)  # Relay 1
Pin4 = Pin(4, Pin.OUT)  # Relay 2
Pin5 = Pin(5, Pin.OUT)  # Relay 3
# Make sure all realys are in the off possition(Dummy Load)
Pin2.off(), Pin4.off(), Pin5.off()


def manualAntenna():
    oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
    old_ant = 99

    while (True):

        if 1 == p36.value() and 1 == p39.value() and 1 == p34.value(
        ) and 1 == p35.value():
            print('Auto Antenna while in Manual Mode')
            autoAntenna()

        oled.fill(0)
        oled.text('MANUAL', 1, 1)
Beispiel #27
0
    get_stm32()  #data_value

    try:
        if stm32_flag:
            esp32_up()
            print("up ok")
            stm32_flag = False
    except:
        print("up wrong")

    try:
        esp32_down()
        print("down ok")
    except:
        print("down wrong")
    #超标
    if data_value[0] > data_down[0] or data_value[1] > data_down[1]:
        data_value[2] = 1
        alert_pin.on()  #报警
    else:
        data_value[2] = 0
        alert_pin.off()

    led_pin.off()
    time.sleep(1)
    led_pin.on()

    # print("once")
    time.sleep(2)
            q = requests.post(urlsong)
        except Exception:  #catch all exceptions
            print('Exception')
            #reset()
        #e=sys.exc_info()[0]
        #print("<p>Error:%s</p>"%e)
    #results = r.json()
    #print (results)


client = MQTTClient('lights', 'mqtt.kpi.fei.tuke.sk', 80)
client.set_callback(on_message)
client.connect()
client.subscribe('best/alarm')
client.subscribe('best/state')

print("ready")

while True:
    client.check_msg()
    if button1.value() == 1:
        print('reset')
        client.publish('best/reset', 'True')
        ledAlarm.off()
        sleep(0.5)
    if button2.value() == 1 and ledAlarm.value() == 0:
        print('changeStateAlarm')
        client.publish('best/set', 'True')
        sleep(0.5)
    sleep(0.1)
Beispiel #29
0
# University of Cape Coast, Ghana
# Copyright (c) U.Raich, May 2020
# The program was released under the GNU Public License

from machine import Pin
import sys, time

print("Testing the push button")
print("Program written for the course on IoT at the")
print("University of Cape Coast, Ghana")
print("Copyright: U.Raich")
print("Released under the Gnu Public License")

_PB_PIN = 17
_LED_PIN = 2

pushButton = Pin(_PB_PIN, Pin.IN, Pin.PULL_UP)
led = Pin(_LED_PIN, Pin.OUT)
led.off()


def stateChange(pb):
    print("state: ", pb.value())
    if pb.value():
        led.off()
    else:
        led.on()


pushButton.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=stateChange)
Beispiel #30
0
from machine import Pin, ADC
from utime import sleep, sleep_ms

#global values
THRESHOLD = 0.63
DELAY = 1800

#init
sensor = ADC(26)
conversion_factor = 3.3 / (65535)
sens_ctl = Pin(22, Pin.OUT)
sens_ctl.off()
led = Pin(7, Pin.OUT)
led.off()

#led flash
sleep(1)
led.on()
sleep_ms(200)
led.off()
sleep_ms(200)
led.on()
sleep_ms(200)
led.off()

#wait to normalize readings
sleep(300)

print('start')
while True:
    sens_ctl.on()
# 残10分から表示し、時間ぎれで点滅+ブザー鳴らす。
# 2017-03-21 by penkich
# 
from machine import Pin,I2C,Timer
from neopixel import NeoPixel
import time

npix = 4 # 1セグを構成するNeoPixelの個数
t = 50 # 時間設定(分) 

pin = Pin(4,Pin.OUT) # NeoPixelの信号線を接続
np = NeoPixel(pin, 7 * npix)
buz = Pin(5,Pin.OUT) # 圧電ブザーを接続
buz.on() # 起動時に少し鳴らす
time.sleep(1)
buz.off()

def seg7(n,rgb):
    data = [0xfc,0x60,0xda,0xf2,0x66,0xb6,0xbe,0xe4,0xfe,0xe6,0xee]
    x = data[n] >> 1
    out = []
    for i in range(7): 
        if x % 2:
            out.append(rgb)
        else:
            out.append(blank)
        x = x >> 1
    out.reverse()
    tmp = []
    for x in out:
        tmp = tmp + x # 1次配列に変換
#--------------------------------------------------------------
from machine import Pin, Signal
#use the pins as an output , and give them timple names
led_blue = Pin(21, Pin.OUT)
led_red = Pin(22, Pin.OUT)

#--------------------------------------------------------------
# Turn On
led_blue.value(1)

#--------------------------------------------------------------
#Turn Off
led_blue.value(0)

#--------------------------------------------------------------
# or by using the signal class
# we can use the simpler on/off syntax
# this also covers the case where value(0) would turn on the

led_blue = Signal(Pin(21, Pin.OUT))
led_red = Signal(Pin(22, Pin.OUT))

# Even better:
led_blue.on()
led_red.on()

#--------------------------------------------------------------
led_blue.off()
led_red.off()