Ejemplo n.º 1
0
def init_robot():
    print("Imported Libraries")

    print("Initializing...")
    # Turn on Light
    led = Pin(25, Pin.OUT)
    led.high()

    # DRIVER INITIALIZATION
    btn = button.Button(BUTTON_PIN)
    bzz = buzzer.Buzzer(BUZZER_PIN)

    motors = motor.TwoWheel(MOTOR_PINS, AXIL_LENGTH)

    threshold = max(UNIT_SIZE) - MIN_SENSOR_WIDTH
    ping_sensors = list(
        map(lambda pins: ping.PingProximitySensor(pins, threshold), PING_PINS))
    ping_collection = ping.PingProxCollection(ping_sensors)

    dht_sensor = dht.DHT11(Pin(20))

    # MAZE INITIALIZATION
    maze = Maze(MAZE_SIZE)

    # ROBOT INITIALIZATION
    robot = Robot(btn, bzz, motors, ping_collection, dht_sensor, maze,
                  UNIT_SIZE, SOLUTIONS, threshold)

    utime.sleep_ms(100)
    led.low()
    print("Pico Initialized")

    robot.Start()
Ejemplo n.º 2
0
    def Out(self, state):
        pin = Pin(self.pin, Pin.OUT)

        if state == True:
            pin.high()
        else:
            pin.low()
Ejemplo n.º 3
0
class Range_Finder():

    duration = 0
    distance = 0

    def __init__(self, echo_pin, trigger_pin):
        # Initialise the Range Finder
        self.__echo_pin = Pin(echo_pin, Pin.IN)
        self.__trigger_pin = Pin(trigger_pin, Pin.OUT)

    def ping(self):
        self.__trigger_pin.low()
        sleep_us(2)

        self.__trigger_pin.high()
        sleep_us(5)
        self.__trigger_pin.low()
        signalon = 0
        signaloff = 0
        while self.__echo_pin.value() == 0:
            signaloff = ticks_us()
        while self.__echo_pin.value() == 1:
            signalon = ticks_us()
        elapsed_micros = signalon - signaloff
        self.duration = elapsed_micros
        self.distance = (elapsed_micros * 0.343) / 2
        return self.distance
Ejemplo n.º 4
0
class Stepper:
    def __init__(self, id, dir_pin, step_pin, step_callback=None):
        self.dir_pin = Pin(dir_pin, Pin.OUT)
        # at 1_000_000Hz clock a single instruction is 1us
        self._sm = rp2.StateMachine(id,
                                    stepper,
                                    freq=1_000_000,
                                    set_base=Pin(step_pin, Pin.OUT))

        if step_callback is not None:
            self._sm.irq(step_callback)

        self._sm.put(0)
        self._sm.active(1)

    def set_steps_per_second(self, steps_per_second):
        if steps_per_second == 0:
            self._sm.put(0)
            return

        if steps_per_second > 0:
            self.dir_pin.high()
        elif steps_per_second < 0:
            self.dir_pin.low()

        delay = abs(
            round(1_000_000 / steps_per_second)
        ) - 10  # there are 10 instructions in the program for each step
        self._sm.put(delay)
Ejemplo n.º 5
0
class HCSR04:
    """HC-SR04 ultrasonic ranging module class."""
    def __init__(self, trig_Pin, echo_Pin):
        """Initialize Input(echo) and Output(trig) Pins."""
        self._trig = Pin(trig_Pin, Pin.OUT)
        self._echo = Pin(echo_Pin, Pin.IN)
        self._sound_speed = 340  # m/s

    def _pulse(self):
        """Trigger ultrasonic module with 10us pulse."""
        self._trig.high()
        sleep_us(10)
        self._trig.low()

    def distance(self):
        """Measure pulse length and return calculated distance [m]."""
        self._pulse()
        try:
            pulse_width_s = time_pulse_us(self._echo, Pin.high,
                                          30000) / 1000000
        except OSError:
            # Measurement timed out
            return None

        dist_m = (pulse_width_s / 2) * self._sound_speed
        return dist_m

    def calibration(self, known_dist_m):
        """Calibrate speed of sound."""
        self._sound_speed = known_dist_m / self.distance() * self._sound_speed
        print("Speed of sound was successfully calibrated! \n" +
              "Current value: " + str(self._sound_speed) + " m/s")
Ejemplo n.º 6
0
class Motor(object):
    """the motor class has the name attribute and a forward duty and backward duty"""
    def __init__(self, name):
        """Sets up two motors for a robot car
        :param name: left or right
        """
        if name == "left":
            self.pin_speed = 4
            self.pin_direction = 2
        elif name == "right":
            self.pin_speed = 5
            self.pin_direction = 0
        self.motor = PWM(Pin(self.pin_speed), freq=1000, duty=0)
        self.d = 1023
        self.speed = PWM(Pin(self.pin_speed), freq=1000, duty=0)
        self.direction = Pin(self.pin_direction, Pin.OUT)
        self.name = name

    def forward(self):
        self.direction.low()
        self.speed.duty(self.d)

    def backward(self):
        self.direction.high()
        self.speed.duty(self.d)

    def stop(self):
        self.speed.duty(0)

    def dutyset(self, value):
        if 0 <= value <= 1023:
            self.d = value
Ejemplo n.º 7
0
class Stepper:
    """
    Handles  A4988 hardware driver for bipolar stepper motors
    """
    def __init__(self, dir_pin, step_pin):
        self.step_pin = Pin(step_pin, Pin.OUT)
        self.dir_pin = Pin(dir_pin, Pin.OUT)
        self.dir = 0
        self.pulserate = 100
        self.count = 0
        self.speed = 0

    def do_step(self):  # called by timer interrupt every 100us
        if self.dir == 0:
            return
        self.count = (self.count + 1) % self.pulserate
        if self.count == 0:
            self.step_pin.high()
            pass
            self.step_pin.low()

    def set_speed(self, speed):
        self.speed = speed

        # set direction
        if self.speed > 0:
            self.dir = 1
            self.dir_pin.high()
        elif self.speed < 0:
            self.dir = -1
            self.dir_pin.low()
        else:
            self.dir = 0
        if abs(self.speed) > 0:
            self.pulserate = 10000 // abs(self.speed)
Ejemplo n.º 8
0
class motor(object):
    def __init__(self, name):
        self.forward_speed = 1023
        if name == "left":
            self.pin_speed = 4
            self.pin_direction = 2
        elif name == "right":
            self.pin_speed = 5
            self.pin_direction = 0

        self.speed = PWM(Pin(self.pin_speed), freq=1000, duty=0)
        self.direction = Pin(self.pin_direction, Pin.OUT)
        self.name = name

    def forward(self):
        self.direction.low()
        self.duty(1023)

    def backward(self):
        self.direction.high()
        self.duty(1023)

    def stop(self):
        self.duty(0)

    def duty(self, d):
        PWM(Pin(self.pin_speed), freq=1000, duty=d)

    def set_forward_speed(self, duty):
        self.forward_speed = duty
Ejemplo n.º 9
0
class motor(object):
    """the motor class has the name attribute and a forward duty and backward duty"""
    def __init__(self, name, forward_duty, backward_duty):
        if name == "left":
            self.pin_speed = 4
            self.pin_direction = 2
        elif name == "right":
            self.pin_speed = 5
            self.pin_direction = 0

        self.speed = PWM(Pin(self.pin_speed), freq=1000, duty=0)
        self.direction = Pin(self.pin_direction, Pin.OUT)
        self.name = name
        self.forward_duty = forward_duty
        self.backward_duty = backward_duty

    def forward(self):
        """turns a motor on in the forward direction"""
        self.direction.low()
        self.duty(self.forward_duty)

    def backward(self):
        """turns a motor on in the backward direction"""
        self.direction.high()
        self.duty(self.backward_duty)

    def stop(self):
        """stops a motor"""
        self.duty(0)

    def duty(self, d):
        """specifies the duty associated with the pin """
        PWM(Pin(self.pin_speed), freq=1000, duty=d)
Ejemplo n.º 10
0
class Relay(object):
    def __init__(self, pin_number=5):
        self._pin = Pin(pin_number, Pin.OUT)

    @property
    def status(self):
        return 'on' if self.state else 'off'

    @property
    def state(self):
        return self._pin.value()

    @state.setter
    def state(self, status):
        self._pin.high() if status else self._pin.low()

    def toggle(self):
        self.state = not self.state

    def activate(self):
        self.state = True

    def deactivate(self):
        self.state = False

    def pulse(self, timeout=1):
        self.activate()
        time.sleep(float(timeout))
        self.deactivate()
Ejemplo n.º 11
0
 def identify(self, period_ms=1000):
     led = Pin(25, Pin.OUT)
     while True:
         led.high()
         sleep_ms(period_ms // 2)
         led.low()
         sleep_ms(period_ms // 2)
Ejemplo n.º 12
0
def run():
    led1 = Pin('LED1', Pin.OUT_PP)
    while 1:
        led1 = Pin('LED1', Pin.OUT_PP)
        led1.high()  # turn on
        time.sleep(2)
        led1.low()  # turn off
        time.sleep(2)
Ejemplo n.º 13
0
def signalStart():
    led0 = Pin(0, Pin.OUT)
    led2 = Pin(2, Pin.OUT)
    led0.high()
    for x in range(4):
        led0.value(not led0.value())
        led2.value(not led2.value())
        sleep(0.5)
Ejemplo n.º 14
0
def run():
    print('demo digital I/O')
    led = Pin('LED1', Pin.OUT_PP)
    button = Pin('SW', Pin.IN)
    while 1:
        state = button.value()
        if state == 1:
            led.high()
        else:
            led.low()
Ejemplo n.º 15
0
def main():
    global reset
    reset = 0
    from machine import Pin, I2C
    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
    LED_warning = Pin(12, Pin.OUT) # define pin12 as the ouput pin of the warning LED
    rtc = machine.RTC()  # get system local time
    warning = 0

    i2c.writeto_mem(bus_addr, 02, b'\x01')  # first measurement is not used because we find that the first measurement occationally fails
    time.sleep(1)

    i2c.writeto_mem(bus_addr, 02, b'\x01')  # edit the mode register of the sensor to enable it to work
    data = i2c.readfrom_mem(bus_addr, 03, 6)  # read the second measurement as the initial position of the sensor # registers 03-08 are the output registers of the sensor

    datax = data_reading(MSB=data[0], LSB=data[1]) #registers 3&4 are the x output w

    dataz = data_reading(MSB=data[2], LSB=data[3])#registers 5&6 are the z output w

    datay = data_reading(MSB=data[4], LSB=data[5])#registers 7&8 are the y output w

    print ('initial measurement:', 'X=', datax, 'Y=', datax, 'Z=', dataz, 'time:', rtc.datetime())

    while (warning == 0 and reset == 0):
        i2c.writeto_mem(bus_addr, 02, b'\x01')
        data = i2c.readfrom_mem(bus_addr, 03, 6)

        datax_next = data_reading(MSB=data[0], LSB=data[1])

        dataz_next = data_reading(MSB=data[2], LSB=data[3])

        datay_next = data_reading(MSB=data[4], LSB=data[5])

        changex = datax_next - datax
        changey = datay_next - datay
        changez = dataz_next - dataz
        print ('X=', datax_next, 'Y=', datax_next, 'Z=', dataz_next, 'time:', rtc.datetime())
        payload_before_warning = json.dumps({'X=': datax_next, 'Y=': datay_next, 'Z=': dataz_next, 'time at:': rtc.datetime()})
        client.publish('esys/PentaQ/test', bytes(payload_before_warning, 'utf-8'))

        if abs(changex) >= 100 or abs(changey) >= 100 or abs(changez) >= 100:  # sensitivity set change threshold to be 100 miliGauss
            warning_time = rtc.datetime() #read local time from the RTC when warning occurs
            warning = 1
            LED_warning.high() # LED connected to pin12 indicates the warning
            payload_after_warning = json.dumps({'warning at:': warning_time})
            print('warning at:', warning_time, switch.value())
        time.sleep(0.5)  # measurement frequency

    while (warning == 1 and reset == 0):
        print('warning at:', warning_time, 'reset=', reset)
        client.publish('esys/PentaQ', bytes(payload_after_warning, 'utf-8'))
        time.sleep(0.5)  # warning frequency
Ejemplo n.º 16
0
class LED:
    LED1 = 1
    LED2 = 2
    LED3 = 4
    LED4 = 8

    def __init__(self):
        self.led1 = Pin('PA8', Pin.OUT, Pin.PULL_NONE)
        self.led2 = Pin('PA7', Pin.OUT, Pin.PULL_NONE)
        self.led3 = Pin('PA6', Pin.OUT, Pin.PULL_NONE)
        self.led4 = Pin('PA5', Pin.OUT, Pin.PULL_NONE)

    def out_bdigit(self, led_data):
        if (led_data & self.LED1) == 0:
            self.led1.low()
        else:
            self.led1.high()
        if (led_data & self.LED2) == 0:
            self.led2.low()
        else:
            self.led2.high()
        if (led_data & self.LED3) == 0:
            self.led3.low()
        else:
            self.led3.high()
        if (led_data & self.LED4) == 0:
            self.led4.low()
        else:
            self.led4.high()
def main(use_stream=False):
	s = socket.socket()

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

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


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

	counter = 0
	while True:
		res = s.accept()
		client_s = res[0]
		client_addr = res[1]
		print("Client address:", client_addr)
		print("Client socket:", client_s)
		print("Request:")
		if use_stream:
			# MicroPython socket objects support stream (aka file) interface
			# directly.
			#print(client_s.read(4096))
			val = client_s.read(4096)
			print(val)
			client_s.write(CONTENT % counter)
		else:
			#print(client_s.recv(4096))
			val = client_s.recv(4096)
			print(val)
			client_s.send(CONTENT % counter)
		if "GET /toggle" in val:
			print("Toggling!")
			p.high()
			time.sleep(1)
			p.low()
			machine.reset()
		client_s.close()
		counter += 1
		print()
Ejemplo n.º 18
0
def do_connect():
    sta_if = network.WLAN(network.STA_IF)
    p2 = Pin(2, Pin.OUT)
    sta_if.active(False)
    if not sta_if.isconnected():
        p2.low()
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('TurnipSmart', 'turnip2016')
        while not sta_if.isconnected():
            pass
    if sta_if.isconnected():
        print('connect success')
        p2.high()
        print('network config:', sta_if.ifconfig())
Ejemplo n.º 19
0
class motor2(object):
    """the motor class has the name attribute and a forward duty and backward duty"""
    def __init__(self, name):
        """
        Sets up two motors for a robot car
        :param name:
        :param forward_duty:
        :param backward_duty:
        :param pin_left_speed:
        :param pin_left_direction:
        :param pin_right_speed:
        :param pin_right_direction:
        """
        if name == "left":
            self.pin_speed = 4
            self.pin_direction = 2
        elif name == "right":
            self.pin_speed = 5
            self.pin_direction = 0

        self.d = 0
        self.speed = PWM(Pin(self.pin_speed), freq=1000, duty=self.d)
        self.direction = Pin(self.pin_direction, Pin.OUT)
        self.name = name

    def forward(self):
        """turns a motor on in the forward direction"""
        self.direction.low()
        self.duty(self.d)

    def backward(self):
        """turns a motor on in the backward direction"""
        self.direction.high()
        self.duty(self.d)

    def stop(self):
        """stops a motor"""
        self.duty(0)

    def duty(self, value):
        """
        specifies the duty associated with the pin
        :param value: the duty value
        """
        if 0 <= value <= 1023:
            ### BUG ?  this shoudl set the duty and not create a new PWM???? Check
            self.d = value
Ejemplo n.º 20
0
def run():
    # load config
    with open('config.json', 'r') as config_file:
        config = json.load(config_file)

    # turn led on
    led = Pin(2, Pin.OUT, value=0)

    print('starting up...')
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    static = None

    try:
        with open('static.cfg', 'r') as static_cfg:
            print('found static config')
            static = static_cfg.read().strip().split('\n')
            if len(static) < 4:
                static = None
    except OSError:
        pass

    if static:
        print('using static config: ', static)
        wlan.ifconfig(static)

    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(config['ssid'], config['password'])
        while not wlan.isconnected():
            pass

    if static is None:
        # save wifi config for faster reconnection
        ifconfig = '\n'.join(wlan.ifconfig())
        with open('static.cfg', 'w') as static_cfg:
            print('Saving static config')
            static_cfg.write(ifconfig)

    http_get(config['url'])

    # turn led off
    led.high()
Ejemplo n.º 21
0
class ComLight:
    def __init__(self, com, pin, name, room):
        self.pin = Pin(pin, Pin.OUT)
        self.pin.low()
        self.com = com
        self.topic = '/' + room + '/lights/' + name
        com.subscribe(self.topic, self._on_msg)

    def _on_msg(self, msg):
        val = msg[0] - 48

        if val == 1:
            self.pin.high()
        elif val == 0:
            self.pin.low()

    def gather_info(self):
        return (('sub', 'light', self.topic, 'Send char of 0 or 1 to turn off or on'),)

    def tick(self):
        pass
Ejemplo n.º 22
0
def flashLed2Times():
    p2 = Pin(2, Pin.OUT)
    p2.high()
    t.sleep(2)
    p2.low()
    t.sleep(2)
    p2.high()
    t.sleep(2)
    p2.low()
    t.sleep(2)
    p2.high()
Ejemplo n.º 23
0
def toggleled():
    p0 = Pin(0, Pin.OUT)
    p0.high()
    sleep(1)
    p0.low()
    sleep(1)
    p0.high()
    sleep(1)
    p0.low()
    sleep(1)
    p0.high()
    sleep(1)
Ejemplo n.º 24
0
class motor():
    """Control a motor connected to the L298N Dual motor controller."""
    def __init__(self, forward, backward, speed):
        """forward pin name, backward pin name, speed = (pin name, timer#)
       Need to make sure the given timer # is associated with the speed
       pin or an exception will be raised.  The speed pin must support
       PWM.
       #Examples:
       m1 = motor('Y1', 'Y2', ('Y3', 4))
       m2 = motor('Y5', 'Y6', ('Y4', 4)) """
        self._forward = Pin(forward, Pin.OUT_PP)
        self._backward = Pin(backward, Pin.OUT_PP)
        self._speedControl = pwm(speed[0], speed[1])
        self._speed = 0

    @property
    def speed(self):
        return self._speed

    @speed.setter
    def speed(self, value):
        self._speed = value
        if (value == 0):
            self._forward.low()
            self._backward.low()
        elif (value < 0):
            self._forward.low()
            self._backward.high()
        else:
            self._forward.high()
            self._backward.low()

        self._speedControl.pulse_width_percent = min(100, abs(value))

    def brake(self):
        """ Brake the motor by sending power both directions. """
        self._forward.high()
        self._backward.high()
        self._speedControl.pulse_width_percent = 100
        delay(1000)
        self.speed = 0
Ejemplo n.º 25
0
def turn_on_wifi_led():
    from machine import Pin
    pin = Pin(WIFI_LED_PIN, Pin.OUT)
    pin.high()
Ejemplo n.º 26
0
import pyb
from machine import SPI,Pin
from pyb import UART
import json

#GU620模块初始化
N1 = Pin('Y6', Pin.OUT_PP)#定义通信系统启动引脚
N1.low()
pyb.delay(2000)
N1.high()
pyb.delay(10000)#拉高拉低引脚,启动通信系统
u2 = UART(4,115200,timeout = 50)#定义串口4,设置 波特率为115200
#初始化 HTTP 应用
u2.write('AT+HTTPINIT\r\n')
getURLCMD = 'AT+HTTPPARA=1,"http://old.tpyboard.com/v702/httptest.php?t=123456"\r\n'
#getURLCMD = 'AT+HTTPPARA=1,"https://www.baidu.com"\r\n'
while True:
    if u2.any() > 0:
        dataRead = u2.read()
        print('_dataRead:',dataRead)
        print('-'*30)
        if dataRead.find(b'OK') > -1:
            #AT命令执行成功
            #判断是执行的哪一步操作
            if dataRead.find(b'AT+HTTPINIT') > -1:
                #初始化HTTP成功
                #设置 HTTP 参数值 设置url
                u2.write(getURLCMD)
            elif dataRead.find(b'AT+HTTPPARA=1') > -1:
                #HTTP参数设置成功
                #发起GET请求获取数据
Ejemplo n.º 27
0
"""
Programme Blink d'une LED
Branchement de la LED (pate +) entre la borne S7 (4ème broche en partant du haut à gauche - USB vers le haut)
et la masse (pate -) borne (1ère broche en bas à gauche - USB vers le haut)
"""

from machine import Pin
import time

# On initialise la sortie 7 pour piloter la led
maLED = Pin( "S7", Pin.OUT )


while True: #Equivalent de la boucle loop en arduino
	print("je commence mon blink") # On affiche dans Putty le texte Je commence mon blink
	maLED.high() #La broche S7 au niveau haut - la led est allumée
	time.sleep_ms(500) #Attendre 500 ms
	maLED.low() #La broche S7 au niveau bas - la led est éteinte
	time.sleep_ms(500) #Attendre 500 ms
Ejemplo n.º 28
0
class ST7735():
    def __init__(self, spi, rst=4, ce=5, dc=16, offset=0, c_mode='RGB'):
        self._rst = Pin(rst, Pin.OUT)  # 4
        self._ce = Pin(ce, Pin.OUT)  # 5
        self._ce.high()
        self._dc = Pin(dc, Pin.OUT)  # 16
        self._dc.high()
        self._offset = offset
        self._x = 0
        self._y = 0
        self._width = ST7735_TFTWIDTH
        self._height = ST7735_TFTHEIGHT
        self._color = 0
        self._bground = 0x64bd
        if c_mode == 'RGB':
            self._color_mode = ST7735_MADCTL_RGB
        else:
            self._color_mode = ST7735_MADCTL_BGR

        # SPI
        self._spi = spi

    def command(self, c):
        b = bytearray(1)
        b[0] = c
        self._dc.low()
        self._ce.low()
        self._spi.write(b)  # write 1 byte on MOSI
        self._ce.high()
        # print ('C {0:2x}'.format(c))

    def data(self, c):
        b = bytearray(1)
        b[0] = c
        self._dc.high()
        self._ce.low()
        self._spi.write(b)  # write 1 byte on MOSI
        self._ce.high()
        # print ('D {0:2x}'.format(c))

    def reset(self):
        self._rst.low()
        time.sleep_ms(50)  # sleep for 50 milliseconds
        self._rst.high()
        time.sleep_ms(50)  # sleep for 50 milliseconds

    # begin
    def begin(self):
        self.reset()
        commands = bytearray([  # Initialization commands for 7735B screens
            ST7735_SWRESET,
            DELAY,  #  1: Software reset, 0 args, w/delay
            150,  #     150 ms delay
            ST7735_SLPOUT,
            DELAY,  #  2: Out of sleep mode, 0 args, w/delay
            255,  #     500 ms delay
            ST7735_FRMCTR1,
            3,  #  3: Frame rate ctrl - normal mode, 3 args:
            0x01,
            0x2C,
            0x2D,  #     Rate = fosc/(1x2+40) * (LINE+2C+2D)
            ST7735_FRMCTR2,
            3,  #  4: Frame rate control - idle mode, 3 args:
            0x01,
            0x2C,
            0x2D,  #     Rate = fosc/(1x2+40) * (LINE+2C+2D)
            ST7735_FRMCTR3,
            6,  #  5: Frame rate ctrl - partial mode, 6 args:
            0x01,
            0x2C,
            0x2D,  #     Dot inversion mode
            0x01,
            0x2C,
            0x2D,  #     Line inversion mode
            ST7735_INVCTR,
            1,  #  6: Display inversion ctrl, 1 arg, no delay:
            0x07,  #     No inversion
            ST7735_PWCTR1,
            3,  #  7: Power control, 3 args, no delay:
            0xA2,
            0x02,  #     -4.6V
            0x84,  #     AUTO mode
            ST7735_PWCTR2,
            1,  #  8: Power control, 1 arg, no delay:
            0xC5,  #     VGH25 = 2.4C VGSEL = -10 VGH = 3 * AVDD
            ST7735_PWCTR3,
            2,  #  9: Power control, 2 args, no delay:
            0x0A,  #     Opamp current small
            0x00,  #     Boost frequency
            ST7735_PWCTR4,
            2,  # 10: Power control, 2 args, no delay:
            0x8A,  #     BCLK/2, Opamp current small & Medium low
            0x2A,
            ST7735_PWCTR5,
            2,  # 11: Power control, 2 args, no delay:
            0x8A,
            0xEE,
            ST7735_VMCTR1,
            1,  # 12: Power control, 1 arg, no delay:
            0x0E,
            ST7735_INVOFF,
            0,  # 13: Don't invert display, no args, no delay
            ST7735_MADCTL,
            1,  # 14: Memory access control (directions), 1 arg:
            0xC8,  #     row addr/col addr, bottom to top refresh
            ST7735_COLMOD,
            1,  # 15: set color mode, 1 arg, no delay:
            0x05,  #     16-bit color
            ST7735_CASET,
            4,  #  1: Column addr set, 4 args, no delay:
            0x00,
            0x00,  #     XSTART = 0
            0x00,
            0x7F,  #     XEND = 127
            ST7735_RASET,
            4,  #  2: Row addr set, 4 args, no delay:
            0x00,
            0x00,  #     XSTART = 0
            0x00,
            0x9F,  #     XEND = 159
            ST7735_GMCTRP1,
            16,  #  1: Magical unicorn dust, 16 args, no delay:
            0x02,
            0x1c,
            0x07,
            0x12,
            0x37,
            0x32,
            0x29,
            0x2d,
            0x29,
            0x25,
            0x2B,
            0x39,
            0x00,
            0x01,
            0x03,
            0x10,
            ST7735_GMCTRN1,
            16,  #  2: Sparkles and rainbows, 16 args, no delay:
            0x03,
            0x1d,
            0x07,
            0x06,
            0x2E,
            0x2C,
            0x29,
            0x2D,
            0x2E,
            0x2E,
            0x37,
            0x3F,
            0x00,
            0x00,
            0x02,
            0x10,
            ST7735_NORON,
            DELAY,  #  3: Normal display on, no args, w/delay
            10,  #     10 ms delay
            ST7735_DISPON,
            DELAY,  #  4: Main screen turn on, no args w/delay
            100,  #     100 ms delay
            ST7735_MADCTL,
            1,  # change MADCTL color filter
            0xC0 | self._color_mode
        ])

        argcount = 0
        cmd = 1
        delay = 0
        for c in commands:
            if argcount == 0:  # no arguments collected
                if delay:  # if a delay flagged this is delay value
                    if c == 255:  # if delay is 255ms make it 500ms
                        c = 500
                    time.sleep_ms(c)
                    delay = 0
                else:
                    if cmd == 1:  # need to send command byte
                        self.command(c)  # send coommand
                        cmd = 0  # clear flag to show command sent
                    else:
                        argcount = c & (0xff ^ DELAY
                                        )  # Clear delay bit and get arguments
                        delay = c & DELAY  # set if delay required
                        cmd = 1  # flag command now complete
            else:  # arguments to send
                self.data(c)  # send argument
                argcount -= 1  # decrement the counter

    # display
    def set_addr_window(self, x0, y0, x1, y1):
        self.command(ST7735_CASET)  # Column addr setim

        self.data(0x00)
        self.data(x0 + self._offset)  # XSTART
        self.data(0x00)
        self.data(x1 + self._offset)  # XEND

        self.command(ST7735_RASET)  # Row addr set
        self.data(0x00)
        self.data(y0 + self._offset)  # YSTART
        self.data(0x00)
        self.data(y1 + self._offset)  # YEND

        self.command(ST7735_RAMWR)  # write to RAM

    def pixel(self, x, y, color):

        if (x < 0) or (x >= self._width) or (y < 0) or (y >= self._height):
            return

        self.set_addr_window(x, y, x + 1, y + 1)

        a = (color >> 8) + ((color & 0xff) << 8)  # reverse bytes
        b = bytearray(a.to_bytes(2))
        self._dc.high()
        self._ce.low()
        self._spi.write(b)  # write 1 byte on MOSI
        self._ce.high()

    def draw_block(self, x, y, w, h, color):
        size = w * h
        max_rows = math.floor(500 / h)
        rows = 0
        while rows < h:
            block_rows = min(max_rows, h - rows)
            b = bytes([color >> 8, color & 0xff]) * w * block_rows
            self.draw_bmp(x, y + rows, w, block_rows, b)
            rows = rows + max_rows

    def draw_bmp(self, x, y, w, h, buffer):
        if ((x >= self._width) or (y >= self._height)):
            return
        if (x + w - 1) >= self._width:
            w = self._width - x
        if (y + h - 1) >= self._height:
            h = self._height - y
        self.set_addr_window(x, y, x + w - 1, y + h - 1)
        self._dc.high()
        self._ce.low()
        self._spi.write(buffer)  # write bytes on MOSI
        self._ce.high()

    def fill_screen(self, color):
        self.draw_block(0, 0, self._width, self._height, color)

    def p_char(self, x, y, ch):
        fp = (ord(ch) - 0x20) * 5
        f = open('font5x7.fnt', 'rb')
        f.seek(fp)
        b = f.read(5)
        char_buf = bytearray(b)
        char_buf.append(0)

        # make 8x6 image
        char_image = bytearray()
        for bit in range(8):
            for c in range(6):
                if ((char_buf[c] >> bit) & 1) > 0:
                    char_image.append(self._color >> 8)
                    char_image.append(self._color & 0xff)
                else:
                    char_image.append(self._bground >> 8)
                    char_image.append(self._bground & 0xff)
        self.draw_bmp(x, y, 6, 8, char_image)

    def p_string(self, x, y, str):
        for ch in (str):
            self.p_char(x, y, ch)
            x += 6

    def rgb_to_565(self, r, g, b):
        return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)

    def set_rotation(self, m):
        self.command(ST7735_MADCTL)
        rotation = m % 4  # can't be higher than 3
        if rotation == 0:
            self.data(ST7735_MADCTL_MX | ST7735_MADCTL_MY | self._color_mode)
            self._width = ST7735_TFTWIDTH
            self._height = ST7735_TFTHEIGHT
        elif rotation == 1:
            self.data(ST7735_MADCTL_MY | ST7735_MADCTL_MV | self._color_mode)
            self._width = ST7735_TFTHEIGHT
            self._height = ST7735_TFTWIDTH
        elif rotation == 2:
            self.data(self._color_mode)
            self._width = ST7735_TFTWIDTH
            self._height = ST7735_TFTHEIGHT
        elif rotation == 3:
            self.data(ST7735_MADCTL_MX | ST7735_MADCTL_MV | self._color_mode)
            self._width = ST7735_TFTHEIGHT
            self._height = ST7735_TFTWIDTH
Ejemplo n.º 29
0
esp.osdebug(0)


pin_14 = Pin(14, Pin.OUT, value = 0)
pin_12 = Pin(12, Pin.OUT, value = 0)
pin_13 = Pin(13, Pin.OUT, value = 0)
pin_15 = Pin(15, Pin.OUT, value = 0)
pin_16 = Pin(16, Pin.OUT, value = 0)
pin_5 = Pin(5, Pin.OUT, value = 0)
pin_4 = Pin(4, Pin.OUT, value = 0)
pin_0 = Pin(0, Pin.OUT, value = 0)


while True:
    pin_14.high()
    sleep_ms(500)
    pin_14.low()
    sleep_ms(500)
    pin_12.high()
    sleep_ms(500)
    pin_12.low()
    sleep_ms(500)
    pin_13.high()
    sleep_ms(500)
    pin_13.low()
    sleep_ms(500)
    pin_15.high()
    sleep_ms(500)
    pin_15.low()
    sleep_ms(500)
Ejemplo n.º 30
0
from machine import Pin, SPI
import time
import ubinascii

vref = 3.3
cs = Pin(15, Pin.OUT)
cs.high()
hspi = SPI(1, baudrate=1600000, polarity=0, phase=0)
value = bytearray(2)

while True:
    data = bytearray(2)
    wget = b'\xA0\x00'
    cs.low()
    hspi.write(b'\x01')
    hspi.write(b'\xA0')
    data = hspi.read(1)
    # data = hspi.write_readinto(wget, data)
    cs.high()
    print(str(int(ubinascii.hexlify(data & b'\x0fff'))*vref/4096))
    time.sleep(1)
    # data = data*vref/4096
    # time.sleep(1)
    # print(str(data & b'\x0fff'))
Ejemplo n.º 31
0
class ILI9341:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pages = self.height // 8
        self.buffer = bytearray(self.pages * self.width)
        self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB)

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

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

        self.init_display()
        

    def init_display(self):
        time.sleep_ms(500)
        
        self.write_cmd(0x01)
        
        time.sleep_ms(200)
    
        self.write_cmd(0xCF)
        self.write_data(bytearray([0x00, 0x8B, 0x30]))
    
        self.write_cmd(0xED)
        self.write_data(bytearray([0x67, 0x03, 0x12, 0x81]))

        self.write_cmd(0xE8)
        self.write_data(bytearray([0x85, 0x10, 0x7A]))
    
        self.write_cmd(0xCB)
        self.write_data(bytearray([0x39, 0x2C, 0x00, 0x34, 0x02]))
    
        self.write_cmd(0xF7)
        self.write_data(bytearray([0x20]))

        self.write_cmd(0xEA)
        self.write_data(bytearray([0x00, 0x00]))

        # Power control
        self.write_cmd(0xC0)
        # VRH[5:0]
        self.write_data(bytearray([0x1B]))
        
        # Power control
        self.write_cmd(0xC1)
        # SAP[2:0];BT[3:0]
        self.write_data(bytearray([0x10]))
        
        # VCM control
        self.write_cmd(0xC5)
        self.write_data(bytearray([0x3F, 0x3C]))
    
        # VCM control2
        self.write_cmd(0xC7)
        self.write_data(bytearray([0xB7]))
    
        # Memory Access Control
        self.write_cmd(0x36)
        self.write_data(bytearray([0x08]))
    
        self.write_cmd(0x3A)
        self.write_data(bytearray([0x55]))
    
        self.write_cmd(0xB1)
        self.write_data(bytearray([0x00, 0x1B]))
        
        # Display Function Control
        self.write_cmd(0xB6)
        self.write_data(bytearray([0x0A, 0xA2]))
    
        # 3Gamma Function Disable
        self.write_cmd(0xF2)
        self.write_data(bytearray([0x00]))
        
        # Gamma curve selected
        self.write_cmd(0x26)
        self.write_data(bytearray([0x01]))
    
        # Set Gamma
        self.write_cmd(0xE0)
        self.write_data(bytearray([0x0F, 0x2A, 0x28, 0x08, 0x0E, 0x08, 0x54, 0XA9, 0x43, 0x0A, 0x0F, 0x00, 0x00, 0x00, 0x00]))
    
        # Set Gamma
        self.write_cmd(0XE1)
        self.write_data(bytearray([0x00, 0x15, 0x17, 0x07, 0x11, 0x06, 0x2B, 0x56, 0x3C, 0x05, 0x10, 0x0F, 0x3F, 0x3F, 0x0F]))
        
        # Exit Sleep
        self.write_cmd(0x11)
        time.sleep_ms(120)
        
        # Display on
        self.write_cmd(0x29)
        time.sleep_ms(500)
        self.fill(0)

    def show(self):
        # set col
        self.write_cmd(0x2A)
        self.write_data(bytearray([0x00, 0x00]))
        self.write_data(bytearray([0x00, 0xef]))
        
        # set page 
        self.write_cmd(0x2B)
        self.write_data(bytearray([0x00, 0x00]))
        self.write_data(bytearray([0x01, 0x3f]))

        self.write_cmd(0x2c);

        num_of_pixels = self.height * self.width

        for row in range(0, self.pages):
            for pixel_pos in range(0, 8):
                for col in range(0, self.width):
                    compressed_pixel = self.buffer[row * 240 + col]
                    if ((compressed_pixel >> pixel_pos) & 0x1) == 0:
                        self.write_data(bytearray([0x00, 0x00]))
                    else:
                        self.write_data(bytearray([0xFF, 0xFF]))

    def fill(self, col):
        self.framebuf.fill(col)

    def pixel(self, x, y, col):
        self.framebuf.pixel(x, y, col)

    def scroll(self, dx, dy):
        self.framebuf.scroll(dx, dy)

    def text(self, string, x, y, col=1):
        self.framebuf.text(string, x, y, col)

    def write_cmd(self, cmd):
        self.dc.low()
        self.cs.low()
        self.spi.write(bytearray([cmd]))
        self.cs.high()
        
    def write_data(self, buf):
        self.dc.high()
        self.cs.low()
        self.spi.write(buf)
        self.cs.high()
Ejemplo n.º 32
0
def led_off():
    led = Pin(PIN_LED, Pin.OUT)
    led.high()
Ejemplo n.º 33
0
from machine import Pin
import time

p2 = Pin(2, Pin.OUT)  # create output pin on GPIO2
p2.value(1)  # set pin to high

while True:
    p2.low()  # set pin to low
    p2.value()
    time.sleep(3)  # sleep for 3 second
    p2.high()  # set pin to high
    p2.value()
    time.sleep(3)  # sleep for 3 second
Ejemplo n.º 34
0
''' MMA7455 access demo'''
from machine import Pin, SPI

#setup h/w SPI port 1, speed 400khz, mode=0, cs pin in gpio15
hspi = SPI(1, baudrate=400000, polarity=0, phase=0)
cs = Pin(15, Pin.OUT)
cs.high()


class MMA7455:
    def __init__(self):
        cs.low()
        hspi.read(2)
        cs.high()

    def CS_on(self):
        cs.low()

    def CS_off(self):
        cs.high()

    def SPIread(self, Reg):
        Reg = Reg << 1
        buf = hspi.read(2, Reg)
        return buf

    def SPIwrite(self, Reg, Data):
        Reg = (Reg << 1) | 0x80
        buf = [Reg, Data]
        buf = bytes(buf)
        hspi.write(buf)
	p.high()
	response = RestServer.Response()
	response.code(200)
	response.contentType("text/plain")
	response.data("Aberto")
	return response.build()
def close():
	p.low()
	response = RestServer.Response()
	response.code(200)
	response.contentType("text/plain")
	response.data("Fechado")
	return response.build()

paths = {"/open":open,
	 "/close":close}

p.high()
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('Vilar', 'defarias')

while not wlan.isconnected():
	pass
	
p.low()

server = RestServer.Server(8000)
server.auth("YTpi")
server.start(paths)