Exemple #1
0
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

i2c = I2C(scl=Pin(21), sda=Pin(22))
screen = SSD1306_I2C(128, 64, i2c)


def show(message):
    screen.fill(0)
    screen.text('hello esp32!', 0, 0)
    screen.text(message, 0, 15)
    screen.show()


 def SetupOLED():
     global oled
     i2c = I2C(1, sda=Pin(2), scl=Pin(3), freq=400000)
     oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
from machine import I2C, Pin, PWM, ADC, TouchPad
from time import sleep, sleep_ms, sleep_us, ticks_us, ticks_ms 
from math import pi, sin
from neopixel import NeoPixel
from onewire import OneWire
from ds18x20 import DS18X20

#Importation des modules pour les afficheurs OLED 
from ssd1306 import SSD1306_I2C     # module pour commander le OLED
i2c = I2C(-1, Pin(22), Pin(21))     # pin SCK et SDA du OLED
display = SSD1306_I2C(128, 64, i2c) # declaration taille ecran, pins

from sh1106 import SH1106_I2C
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000)
display = SH1106_I2C(128, 64, i2c, Pin(16), 0x3c)
display.sleep(False)

ds_pin = Pin(27)                       # definie pin DS18B20
ds_capteur = DS18X20(OneWire(ds_pin))  # cree l'objet ds_capteur

led_bleue = Pin(2, Pin.OUT)
led_verte = Pin(18, Pin.OUT)
led_jaune = Pin(19, Pin.OUT)
led_rouge = Pin(23, Pin.OUT)

tp1 = TouchPad(Pin(15))
tp2 = TouchPad(Pin(4))

bpA = Pin(25, Pin.IN)
bpB = Pin(34, Pin.IN)
bpC = Pin(39, Pin.IN)
led = Pin(25, Pin.OUT)  # 設定GP25為板上LED為輸出腳
led1 = Pin(18, Pin.OUT)  # 設定GP18為LED1輸出腳
led2 = Pin(21, Pin.OUT)  # 設定GP21為LED2輸出腳

voltage = machine.ADC(2)  # 設定使用ADC2(GP28)
factor = 3.3 / (65535)  # 設定ADC轉換因子

WIDTH = 128  # 設定OLED顯示寬度
HEIGHT = 64  # 設定OLED顯示高度

i2c = I2C(1, scl=Pin(27), sda=Pin(26), freq=400000)  # 設定使用I2C#1,SCL,SDA腳位及時脈頻率
print("I2C Address      : " + hex(i2c.scan()[0]).upper())  # 顯示I2C位址
print("I2C Configuration: " + str(i2c))  # 顯示I2C組態

oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)  # SSD1306 OLED初始化

time_start = utime.ticks_ms()  # 啟動ms計時器

while True:  # 永遠執行循環
    oled.fill(0)  # 清除OLED顯示區(全部填零)

    # 若有收到遠端透過USB虛擬COM傳送命令字串時才進行命令
    # 採異步(不阻塞)命令執行方式完成
    while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        s = sys.stdin.readline().strip()  #從標準輸人讀取一行文字並去除換行符號
        cmd = str(s)  # 將收到的內容轉成字串
        print(cmd)  # 回傳檢查收到之命令內容,可省略

        if cmd == 'G0':  # 若命令為G0
            led1.value(0)  # 熄滅LED1
 # Display Image & text on I2C driven ssd1306 OLED display 
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import framebuf

WIDTH  = 128                                            # oled display width
HEIGHT = 32                                             # oled display height

i2c = I2C(0)                                            # Init I2C using I2C0 defaults, SCL=Pin(GP9), SDA=Pin(GP8), freq=400000
print("I2C Address      : "+hex(i2c.scan()[0]).upper()) # Display device address
print("I2C Configuration: "+str(i2c))                   # Display I2C config


oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)                  # Init oled display

# Raspberry Pi logo as 32x32 bytearray
buffer = bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|?\x00\x01\x86@\x80\x01\x01\x80\x80\x01\x11\x88\x80\x01\x05\xa0\x80\x00\x83\xc1\x00\x00C\xe3\x00\x00~\xfc\x00\x00L'\x00\x00\x9c\x11\x00\x00\xbf\xfd\x00\x00\xe1\x87\x00\x01\xc1\x83\x80\x02A\x82@\x02A\x82@\x02\xc1\xc2@\x02\xf6>\xc0\x01\xfc=\x80\x01\x18\x18\x80\x01\x88\x10\x80\x00\x8c!\x00\x00\x87\xf1\x00\x00\x7f\xf6\x00\x008\x1c\x00\x00\x0c \x00\x00\x03\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")

# Load the raspberry pi logo into the framebuffer (the image is 32x32)
fb = framebuf.FrameBuffer(buffer, 32, 32, framebuf.MONO_HLSB)

# Clear the oled display in case it has junk on it.
oled.fill(0)

# Blit the image from the framebuffer to the oled display
oled.blit(fb, 96, 0)

# Add some text
oled.text("Raspberry Pi",5,5)
oled.text("Pico",5,15)
Exemple #6
0
# Voir class FrameBuffer pour les méthodes d'écriture et de dessin

from pyb import Pin
from machine import I2C
from ssd1306 import SSD1306_I2C
i2c = I2C(scl=Pin('SCL'), sda=Pin('SDA'))
oled = SSD1306_I2C(128, 32, i2c, 0x3c)
oled.fill(0)
oled.text("Hello David", 0, 0)
oled.text("R =", 0, 10)
oled.show()
# This is fun, but you might as well use a computer monitor.

from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

i2c = I2C(scl=Pin(22, Pin.OUT), sda=Pin(21, Pin.OUT))

oled = SSD1306_I2C(width=128, height=64, i2c=i2c, addr=0x3c)

oled.line(0, 0, 64, 64, 1)
oled.text("Hello World", 0, 0, 1)  # ASCII only
oled.rect(110, 2, 10, 5, 1)
oled.fill_rect(100, 20, 10, 5, 1)
oled.show()
from htu21d import HTU21D
from ssd1306 import SSD1306_I2C
from machine import I2C, Pin
import time

i2c = I2C(scl=Pin(14), sda=Pin(2), freq=100000)
h = HTU21D()
s = SSD1306_I2C(126, 64, i2c)

s.init_display()

while True:
    temp = 'Temp:' + str(h.read_temperature())
    hum = 'Humi:' + str(h.read_humidity())
    print(temp, hum)
    s.fill(0)
    s.text(temp, 20, 20)
    s.text(hum, 20, 40, 4)
    s.show()
    time.sleep(1)
Exemple #9
0
def init_sensors(kind):
    global bme680, si7021, sht31, pmsx003, anemo, vane, rain
    global cwop, display

    # ===== pin configuration, see also Projects/kicad/esp32-weather/README.md
    if kind == "lolin-d32":
        scl0, sda0 = 23, 22  # bme680, si7021, sht31
        scl1, sda1 = 18, 4  # oled
        scl2, sda2 = 13, 12  # expansion
        pm_tx, pm_rx = 25, 26  # pmsa003
        anemo_pin = 39  # anemometer pulse
        vane_pin = 36  # wind vane analog
        rain_pin = 34  # rain pulse
        pow_3v3 = 32  # active-low power for anemo/vane/rain/pmsa003
    else:
        raise ("Unknown board kind: " + kind)

    # ===== init devices

    # show splash screen on display
    from ssd1306 import SSD1306_I2C

    try:
        scl1_pin = machine.Pin(scl1)
        sda1_pin = machine.Pin(sda1)
        display = SSD1306_I2C(
            128, 64, machine.I2C(scl=scl1_pin, sda=sda1_pin, freq=1000000))
        display.fill(1)
        display.fill_rect(10, 10, 108, 44, 0)
        display.text("WCC Weather", 20, 20, 1)
        display.show()
    except Exception as e:
        display = None
        log.warning("No display: %s", e)

    # start power for anemo, vane, etc.
    pow_3v3_pin = machine.Pin(pow_3v3, machine.Pin.OUT)
    pow_3v3_pin(0)

    # I2C bus for primary sensors
    scl0_pin = machine.Pin(scl0)
    sda0_pin = machine.Pin(sda0)
    i2c0_dev = machine.I2C(scl=scl0_pin, sda=sda0_pin, freq=100000)

    # BME680 temperature/humidity/pressure/voc
    from bme680 import BME680

    try:
        bme680 = BME680(i2c0_dev)
        bme680.set_gas_heater_temperature(320)
        bme680.set_gas_heater_duration(100)
        log.info("Found BME680")
    except Exception as e:
        bme680 = None
        log.warning("No BME680 found: %s", e)

    # SI7021 temperature/humidity
    from si7021 import Si7021

    try:
        si7021 = Si7021(i2c0_dev)
        si7021.convert()
        log.info("Found Si7021")
    except Exception as e:
        si7021 = None
        log.warning("No Si7021 found: %s", e)

    # SHT31 temperature/humidity
    from sht31 import SHT31

    try:
        sht31 = SHT31(i2c0_dev)
        sht31.convert()
        log.info("Found SHT31")
    except Exception as e:
        sht31 = None
        log.warning("No SHT31 found: %s", e)

    # PMSx003 PM sensor
    from pms_x003 import PMSx003

    try:
        pmsx003 = PMSx003(tx=pm_tx, rx=pm_rx)
        log.info("Found PMSx003")
    except Exception as e:
        pmsx003 = None
        log.warning("No PMSx003 found: %s", e)

    # Anemometer and wind vane
    from wind import Anemo, Vane
    from counter import Counter

    try:
        # configure pin with pull-up
        machine.Pin(anemo_pin, mode=machine.Pin.IN)
        anemo_ctr = Counter(0, anemo_pin)
        anemo_ctr.filter(10)  # 10us filter
        anemo = Anemo(anemo_ctr, 2.5)  # 2.5 mph per Hz
        anemo.start()
    except Exception as e:
        anemo = None
        log.exc(e, "Anemometer failed to init")
    try:
        vane = Vane(vane_pin, 140, 1600, 15)
        vane.start()
    except Exception as e:
        vane = None
        log.exc(e, "Wind vane failed to init")

    # init rain gauge
    pass

    # init CWOP
    try:
        from cwop import send_wx

        cwop = send_wx
    except ImportError:
        log.warning("Cannot import CWOP, skipping")
Exemple #10
0
 def __init__(self, i2c: machine.I2C, width: int = 128, height: int = 32):
     """Initialize the SSD1306 screen with a given width, height, and I2C
     connection.
     """
     self.ssd_screen = SSD1306_I2C(width, height, i2c)
Exemple #11
0
from utime import sleep_ms, ticks_ms, ticks_diff
from ujson import dumps
from ucollections import OrderedDict

from wlan_manager import WLAN_Manager
from mqtt_manager import MQTT_Manager

from sensor_manager import Sensor_DS18B20
from board_manager import D1, D2, D4

from ssd1306 import SSD1306_I2C

i2c = I2C(scl=Pin(D1), sda=Pin(D2))

sensor = Sensor_DS18B20(D4)
oled = SSD1306_I2C(128, 64, i2c, 0x3c)
oled.text("Loading ...", 0, 0)
oled.show()

wlan_client = WLAN_Manager()
mqtt_client = MQTT_Manager()


def reconnect(attempts=0):
    wlan_client.start(attempts=attempts)
    success = wlan_client.check() and mqtt_client.check()
    if success:
        mqtt_client.broker.subscribe(TOPIC_SUB)
    return success

Exemple #12
0
 def __init__(self, i2c, width, height):
     self._i2c = i2c
     self._width = width
     self._height = height
     self._oled = SSD1306_I2C(width, height, i2c)
Exemple #13
0
SIZE_OF_INITIAL_COLONY = 0.4  # where 1 is the whole map
UPDATE_DELAY = 0  # additional delay between population updates

# Constants
WORLD_WIDTH = 64  # number of cells horizontally
WORLD_HEIGHT = 32  # number of cells vertically
CELL_SIZE = 2  # side of single cell in pixels
CENTER_X = int(WORLD_WIDTH / 2)
CENTER_Y = int(WORLD_HEIGHT / 2)

# Variables
cells = []  # array where Cell objects will be stored

# Init oled display
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled = SSD1306_I2C(WORLD_WIDTH * CELL_SIZE, WORLD_HEIGHT * CELL_SIZE, i2c)
oled.rotate(True)


class Cell:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.live = False

    def change_state(self):  # changes state of the cell to opposite
        self.live = not self.live
        if self.live:
            draw_cell(self.x, self.y, LIVE_CELL_COLOUR)
        else:
            draw_cell(self.x, self.y, BACKGROUND_COLOUR)
Exemple #14
0
# import shell

#__all__ = ["SystemOS"]

# class SystemOS:

from ssd1306 import SSD1306_I2C
from cmd import Cmd
""" Constants """
WIDTH = const(128)
HEIGHT = const(64)
#pscl = machine.Pin(5)  # GPIO4_CLK , machine.Pin.OUT_PP)
#psda = machine.Pin(4)  # GPIO5_DAT, machine.Pin.OUT_PP)
#i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
oled = SSD1306_I2C(WIDTH, HEIGHT,
                   machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)))


class Kernel:

    default_controller = 'http://control.maison.apoui.net/setrelay'

    def __init__(self):
        gc.collect()
        self.handle()

    def system_release(self, build):
        oled.text('<APOUI-SYSTEMS>', 0, 0)
        oled.text('---------------', 0, 10)
        oled.text('> KERNEL [OK]', 0, 20)
        oled.show()
Exemple #15
0
AP_MODE = False  # 'True' para modo AP; 'False' para modo Station
SSID = ''
PWD = ''

# ============ Inicialização do LED UV ============
led = Pin(2, Pin.OUT)
led.on()

# ============ CONFIGURAÇÃO OLED ===============
if OLED:
    from machine import I2C
    from ssd1306 import SSD1306_I2C

    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
    oled = SSD1306_I2C(64, 48, i2c)
    oled.fill(0)
    oled.show()

    oled_x = 64  # Dimensão da tela no eixo x
    oled_y = 48  # Dimensão da tela no eixo y
    fontSize = 8  # Tamanho do caractere em pixel

    def centerX(msg):
        if len(msg) > (oled_x / fontSize):
            return 0

        return int((oled_x - len(msg) * fontSize) / 2)

    def oledUvcInf(isOn, tempo=0):
        if isOn:  # Se a luz UVC está ligada
Exemple #16
0
from machine import I2C, Pin
from ssd1306 import SSD1306_I2C
from picodilo_sans import a
import framebuf
from time import sleep

sda = Pin(0)
scl = Pin(1)
id = 0

i2c = I2C(id=id, sda=sda, scl=scl)

oled = SSD1306_I2C(width=128, height=64, i2c=i2c)
oled.init_display()
oled.text("test", 1, 1)
oled.show()
sleep(1)

with open('test image.pbm', 'rb') as f:
    f.readline()  # magic number
    f.readline()  # creator comment
    f.readline()  # dimensions
    data = bytearray(f.read())
fb = framebuf.FrameBuffer(data, 128, 64, framebuf.MONO_HLSB)

images = []
for n in range(1, 5):
    with open('frame0%s.pbm' % n, 'rb') as f:
        f.readline()  # magic number
        f.readline()  # creator comment
        f.readline()  # dimensions
Exemple #17
0
def run(so):
    pin_in = []
    oled_width = 1
    oled_heigth = -1
    oled = 0
    adc = 0
    i2c_msg = 0
    send_type = 0  # 0: data, 1: nfc, 2: adc
    #so.settimeout(0.05)
    disp = False
    data = b''
    rdr = 0
    nfc = '0'
    while (1):
        #so.setsockopt(socket.TCP_NODELAY,1)

        s = b''
        '''try:
            s=so.recv(1024)
        except:
            pass'''

        s = bytes(recv_msg(so))

        d = s
        print(len(s))
        if (len(s) == 1):  # send NFC
            nfc = '0'
            send_type = 1
            if (rdr):
                (stat, _) = rdr.request(rdr.REQIDL)
                if stat == rdr.OK:
                    (stat, raw_uid) = rdr.anticoll()
                    if stat == rdr.OK:
                        nfc = ":%02x%02x%02x%02x:" % (raw_uid[0], raw_uid[1],
                                                      raw_uid[2], raw_uid[3])

        elif (len(s) == 2):  # set Input Pin
            if (not (int(s) in pin_in)):
                pin_in.append(int(s))

        elif (len(s) == 3):  # set Output Pin
            pin = int(int(s) / 10)
            Pin(pin, Pin.OUT).value(int(s) % 10)
            if pin in pin_in:
                pin_in.remove(pin)

        elif (len(s) == 4):  # read ADC
            pin = int(s)
            adc = ADC(pin)
            send_type = 2
            if pin in pin_in:
                pin_in.remove(pin)

        elif (len(s) == 8):  # read I2C
            #print("i2c")
            s = int(s)
            nbytes = s % 100
            s = int(s / 100)
            addr = s % 100
            s = int(s / 100)
            scl = s % 100
            sda = int(s / 100)
            #print(sda,scl,addr,nbytes)

            i2c = I2C(-1, scl=Pin(scl), sda=Pin(sda))
            i2c_msg = i2c.readfrom(addr, nbytes)
            send_type = 3
            #print(i2c_msg)

        elif (len(s) == 9):  # set PWM
            s = int(s)
            duty = s % 10000
            s = int(s / 10000)
            freq = s % 1000 + 1
            pin = int(s / 1000)
            PWM(Pin(pin), freq=freq, duty=duty)
            if pin in pin_in:
                pin_in.remove(pin)

        elif (len(s) == 10):  # set NFC
            s = s.decode()
            sda = int(s[-2:])
            s = int(s[:-2])
            rst = s % 100
            s = int(s / 100)
            miso = s % 100
            s = int(s / 100)
            mosi = s % 100
            s = int(s / 100)
            sclk = s % 100
            from mfrc522 import MFRC522
            rdr = MFRC522(sclk, mosi, miso, rst, sda)

        elif (len(s) == 11):  # set Neopixel
            s = int(s)
            val = [0, 0, 0]
            val[2] = (s % 1000)
            s = int(s / 1000)
            val[1] = (s % 1000)
            s = int(s / 1000)
            val[0] = (s % 1000)
            pin = int(s / 1000)
            np = neopixel.NeoPixel(Pin(pin), 1)
            np[0] = val
            np.write()
            if pin in pin_in:
                pin_in.remove(pin)

        elif (len(s) == 12):  #set Display
            s = s.decode()
            disp = int(s[-2:])
            s = s[:-2]
            s = int(s)
            oled_heigth = s % 1000
            s = int(s / 1000)
            oled_width = s % 1000
            s = int(s / 1000)
            scl = s % 100
            sda = int(s / 100)
            i2c = I2C(-1, scl=Pin(scl), sda=Pin(sda))
            print(disp, oled_heigth, oled_width, sda, scl)

            if (disp == 0):
                from sh1106 import SH1106_I2C
                oled = SH1106_I2C(oled_width, oled_heigth, i2c)
            elif (disp == 1):
                from ssd1306 import SSD1306_I2C
                oled = SSD1306_I2C(oled_width, oled_heigth, i2c)

        elif (len(s) != 0):
            p = bytearray(s)
            fbuf = framebuf.FrameBuffer(p, oled_width, oled_heigth,
                                        framebuf.MONO_HLSB)
            oled.blit(fbuf, 0, 0)
            oled.show()

        #****** send ******#
        msg = 0
        if (send_type == 0):
            for p in pin_in:
                msg += ((not Pin(p, Pin.IN, Pin.PULL_UP).value()) << p)

        try:
            if (send_type == 0):
                so.send(str(msg).encode())
            elif (send_type == 1):
                so.send(str(nfc).encode())
            elif (send_type == 2):
                so.send(str(adc).encode())
            elif (send_type == 3):
                so.send(i2c_msg)

            send_type = 0
        except:
            import machine
            machine.reset()
Exemple #18
0
# 
# create empty timer-file file on the flash (save as to rpico in thonny) before first run to provent possible file not found error

# https://www.youtube.com/spidermaf  


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

led = Pin(25, Pin.OUT)
led.off

i2c=I2C(0,sda=Pin(0), scl=Pin(1))

oled = SSD1306_I2C(128, 32, i2c)

oled.text("Timer: 0", 0, 0)
oled.show()
count=0;
prevoius_time = ""
f = open('timer-file')
previous = f.read()
previous = replace("Timer:")
f.close()
oled.text(previous, 0, 24)
oled.show()

while True:
    count+=1
    for i in range(60):
Exemple #19
0
'''
实验名称:水位传感器
版本:v1.0
日期:2021.1
作者:01Studio 【www.01Studio.org】
说明:通过水位传感器对水位测量并显示。
'''

#导入相关模块
import time
from machine import Pin, SoftI2C, ADC
from ssd1306 import SSD1306_I2C

#初始化oled
i2c = SoftI2C(scl=Pin(10), sda=Pin(11))  #软件I2C初始化:scl--> 10, sda --> 11
oled = SSD1306_I2C(128, 64, i2c,
                   addr=0x3c)  #OLED显示屏初始化:128*64分辨率,OLED的I2C地址是0x3c

#初始化ADC1,Pin=27
Water_level = ADC(1)

while True:

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

    value = Water_level.read_u16()  #获取ADC数值

    #显示数值
    oled.text(str(value) + ' (65535)', 0, 40)
    #计算电压值,获得的数据0-4095相当于0-3V,('%.2f'%)表示保留2位小数
Exemple #20
0
    async def recv(reader):
        args = []
        while True:
            s = bytes(await recv_msg(reader))
            #s=await reader.readline()

            print(chr(s[0]))

            msg_type = chr(s[0])

            msg = None

            if msg_type != 'S':
                msg = s.decode()[1:]
                args = list(map(int, msg.split("-")))
                print(args)
            else:
                msg = s[1:]

            if (msg_type == 'f'):  # read NFC
                flag = args[0]

                if flag:
                    send_type[0] = 1
                else:
                    send_type[0] = 0

            elif (msg_type == 'I'):  # set Input Pin
                pin = args[0]
                if (not (pin in pin_in)):
                    pin_in.append(pin)

            elif (msg_type == 'O'):  # set Output Pin
                pin = args[0]
                value = args[1]
                Pin(pin, Pin.OUT).value(value)
                if pin in pin_in:
                    pin_in.remove(pin)

            elif (msg_type == 'A'):  # read ADC
                flag = args[0]

                if flag:
                    pin = args[1]
                    adc_pin[0] = pin
                    if pin in pin_in:
                        pin_in.remove(pin)
                    send_type[0] = 2
                else:
                    adc_pin[0] = -1
                    send_type[0] = 0

            elif (msg_type == 'i'):  # set I2C
                sda_pin = args[0]
                scl_pin = args[1]

                #i2c = [0, 0, 0]

                isqc[0] = I2C(-1, scl=Pin(scl_pin), sda=Pin(sda_pin))

            elif (msg_type == 'c'):  # read I2C
                flag = args[0]

                if flag:
                    addr = args[1]
                    nbytes = args[2]
                    isqc[1] = addr
                    isqc[2] = nbytes
                    send_type[0] = 3
                    print(send_type, isqc)
                else:
                    send_type[0] = 0

            elif (msg_type == 'P'):  # set PWM
                pin = args[0]
                freq = args[1]
                duty = args[2]

                PWM(Pin(pin), freq=freq, duty=duty)
                if pin in pin_in:
                    pin_in.remove(pin)

            elif (msg_type == 'n'):  # set NFC
                sclk = args[0]
                mosi = args[1]
                miso = args[2]
                rst = args[3]
                sda = args[4]
                from mfrc522 import MFRC522
                nfc_rdr[0] = MFRC522(sclk, mosi, miso, rst, sda)

            elif (msg_type == 'N'):  # set Neopixel
                pin = args[0]
                red = args[1]
                green = args[2]
                blue = args[3]

                np = neopixel.NeoPixel(Pin(pin), 1)
                np[0] = [red, green, blue]
                np.write()
                if pin in pin_in:
                    pin_in.remove(pin)

            elif (msg_type == 'D'):  #set Display
                sda = args[0]
                scl = args[1]
                oled_height = args[3]
                oled_width = args[2]
                oled[0] = oled_width
                oled[1] = oled_height
                disp = args[4]

                i2c = I2C(-1, scl=Pin(scl), sda=Pin(sda))
                print(disp, oled_height, oled_width, sda, scl)

                if (disp == 0):
                    from sh1106 import SH1106_I2C
                    oled[2] = SH1106_I2C(oled_width, oled_height, i2c)
                elif (disp == 1):
                    from ssd1306 import SSD1306_I2C
                    oled[2] = SSD1306_I2C(oled_width, oled_height, i2c)

            elif (msg_type == "S"):
                p = bytearray(msg)
                if oled[0] != '' and oled[1] != '':
                    fbuf = framebuf.FrameBuffer(p, oled[0], oled[1],
                                                framebuf.MONO_HLSB)
                    if oled[2] != '':
                        oled[2].blit(fbuf, 0, 0)
                        oled[2].show()

            yield
RAND_PCT = const(25)  # %
SCL_PIN = const(27)
SDA_PIN = const(26)

X = WIDTH // DOT_SIZE
Y = HEIGHT // DOT_SIZE
TOTAL = X * Y
board = [
    0 if urandom.randint(0, (100 // RAND_PCT) - 1) else 1 for _ in range(TOTAL)
]
buffer = []
task = []
gen = 0

i2c = I2C(1, scl=Pin(SCL_PIN), sda=Pin(SDA_PIN), freq=400000)
display = SSD1306_I2C(WIDTH, HEIGHT, i2c)
display.fill(0)
display.show()

lock = allocate_lock()

print('Conway\'s Game of Life: matrix size {} x {}'.format(X, Y))


def calculate_cells(is_thread):
    while task:
        try:
            with lock:
                i = task.pop()
        except:
            break
Exemple #22
0
def setupOled():
    global oled
    i2c = I2C(BUS, sda=Pin(SDA), scl=Pin(SCL), freq=400000)
    oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
    oled.fill(0)
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

OLED_WIDTH = 128
OLED_HEIGHT = 64

i2c = I2C(scl=Pin(5), sda=Pin(0))
oled = SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c)

Exemple #24
0
import machine
from ssd1306 import SSD1306_I2C

WIDTH = const(128)
HEIGHT = const (64)
sda_pin = machine.Pin(26)
scl_pin = machine.Pin(25)

i2c = machine.I2C(scl=scl_pin, sda=sda_pin, speed=400000)

ssd = SSD1306_I2C(WIDTH, HEIGHT, i2c)

import freesans20

from writer import Writer
wri2 = Writer(ssd, freesans20, verbose=True)

Writer.set_clip(True, True)
Writer.set_textpos(0, 0)
wri2.printstring('MicroPython\nby LoBo\n10/2017')

ssd.show()
import machine
from utime import sleep
from ssd1306 import SSD1306_I2C

sda=machine.Pin(0)
scl=machine.Pin(1)
i2c=machine.I2C(0,sda=sda, scl=scl, freq=400000)

# Screen size
width=128
height=64
oled = SSD1306_I2C(width, height, i2c)

oled.fill(0)
oled.rect(0, 0, width-1, height-1,1)
oled.show()
Exemple #26
0
def SetupDisplay():
    global oled
    i2c=I2C(1,sda=Pin(2), scl=Pin(3), freq=400000)
    oled = SSD1306_I2C(128, 64, i2c)
'''
实验名称:DAC-蜂鸣器
版本:v1.0
日期:2019.4
作者:01Studio
说明:通过USER按键让DAC输出不同频率的方波来驱动蜂鸣器。
'''

#导入相关模块
from pyb import DAC, Switch
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

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

sw = Switch()  #定义按键对象名字为sw
dac = DAC(1)  #定义DAC对象名字为dac,输出引脚为X5

#定义4组频率值:1Hz、200Hz、1000Hz、5000Hz
freq = [1, 200, 1000, 5000]

# 定义8位精度下方波的值。0、255分别对应输出0V、3.3V。需要定义成字节数组。
buf = bytearray(2)
buf[0] = 0
buf[1] = 255

key_node = 0  #按键标志位
i = 0  #用于选择频率数组
def main():
    # setup sensors
    bus = machine.I2C(scl=machine.Pin(16), sda=machine.Pin(13))
    bme = BME280(i2c=bus)
    oled = SSD1306_I2C(128, 32, bus)

    # setup storage
    card = machine.SDCard()
    os.mount(card, '/card')

    # setup networking
    config = load_config('/card', 'config.yml')
    eth = eth_start(config,
                    mdc=machine.Pin(23),
                    mdio=machine.Pin(18),
                    phy_type=network.PHY_LAN8720,
                    phy_addr=0,
                    clock_mode=network.ETH_CLOCK_GPIO17_OUT,
                    power_pin=machine.Pin(12, machine.Pin.OUT))

    # setup display
    sl = Sparkline(32, 128)
    oled.init_display()
    oled.fill(0x0)
    oled.text('loading', 0, 0)
    oled.show()

    # setup Prometheus metrics
    registry = CollectorRegistry(namespace='prometheus_express')
    metric_beat = Counter('system_heartbeat',
                          'system heartbeat counter',
                          labels=['location'],
                          registry=registry)
    metric_temp = Gauge('sensor_temperature',
                        'temperature data from the sensors',
                        labels=['location', 'sensor'],
                        registry=registry)

    router = Router()
    router.register('GET', '/metrics', registry.handler)
    server = False

    # wait for incoming connection
    while True:
        while not server:
            time.sleep(1)
            server = bind(eth, config)

        bme_reading = bme.read_compensated_data()
        temp_line = ((bme_reading[0] - 12) * 2) % 32
        print('temp line: {}'.format(temp_line))

        oled.fill(0x0)
        sl.push(temp_line)
        sl.draw(oled, 0, 12)
        oled.text(str(bme_reading[0]), 0, 0)
        oled.show()

        location = config['metric_location']
        metric_beat.labels(location).inc(1)
        metric_temp.labels(location,
                           'esp32').set(temp_ftoc(esp32.raw_temperature()))
        metric_temp.labels(location, 'bme280').set(bme_reading[0])

        try:
            server.accept(router)
        except OSError as err:
            print('Error accepting request: {}'.format(err))
        except ValueError as err:
            print('Error parsing request: {}'.format(err))
Exemple #29
0
def map(x, in_min, in_max, out_min, out_max):
    return int((x - in_min) * (out_max - out_min) / (in_max - in_min) +
               out_min)


from machine import I2C, Pin
import network
from ssd1306 import SSD1306_I2C
import time

wlan = network.WLAN()
wlan.active(1)
wlan.connect(WIFI_SSID, WIFI_PASS)

i2c = I2C(scl=Pin(4), sda=Pin(5))
oled = SSD1306_I2C(128, 64, i2c)

oled.text("Connecting", 0, 0)
oled.text(WIFI_SSID, 0, 15)
oled.show()

while not wlan.isconnected():
    pass

while 1:
    oled.fill(0)
    oled.text("Signal: {} dBi".format(wlan.status('rssi')), 0, 0)
    oled.fill_rect(0, 15, map(wlan.status('rssi'), -100, -30, 0, 120), 10, 1)
    oled.show()
    time.sleep_ms(250)
Exemple #30
0
 def showFull(self, num, nx=0):
     self.tca.switch_channel(num)
     oled = SSD1306_I2C(128, 32, self.tca.bus)
     oled.fill(nx)
     oled.show()