Ejemplo n.º 1
0
from mpu9250 import MPU9250
from fusion_async import Fusion # Using async version
import ssd1306
import time

switch = Pin(38, Pin.IN)
i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))
imu = MPU9250(i2c)

# Activation OLED
i2cOLED = machine.I2C(scl=machine.Pin(15), sda=machine.Pin(4))
reset_oled = machine.Pin(16, machine.Pin.OUT)
reset_oled.value(0)
time.sleep(.05)
reset_oled.value(1)
oled = ssd1306.SSD1306_I2C(128, 64, i2cOLED)  # 128 x 64 pixels

# User coro returns data and determines update rate.
# For 9DOF sensors returns three 3-tuples (x, y, z) for accel, gyro and mag
# For 6DOF sensors two 3-tuples (x, y, z) for accel and gyro
async def read_coro():
    #imu.mag_trigger()
    await asyncio.sleep_ms(20)  # Plenty of time for mag to be ready
    return imu.accel.xyz, imu.gyro.xyz, imu.mag.xyz

fuse = Fusion(read_coro)

async def mem_manage():         # Necessary for long term stability
    while True:
        await asyncio.sleep_ms(100)
        gc.collect()
Ejemplo n.º 2
0
hSize = 48  # Hauteur ecran en pixels | display heigh in pixels
wSize = 64  # Largeur ecran en pixels | display width in pixels

oledIsConnected = False

# init ic2 object
i2c = machine.I2C(scl=machine.Pin(pinScl),
                  sda=machine.Pin(pinSda))  #ESP8266 5/4

# Scan le bus i2c et verifie si le BME280 et l'ecran OLED sont connectes
# Scan i2c bus and check if BME2 and OLDE display are connected
print('Scan i2c bus...')
devices = i2c.scan()
if len(devices) == 0:
    print("No i2c device !")
else:
    print('i2c devices found:', len(devices))
    for device in devices:
        if device == addrOled:
            oledIsConnected = True

if oledIsConnected:
    oled = ssd1306.SSD1306_I2C(wSize, hSize, i2c, addrOled)
    oled.fill(0)
    oled.text("192.168.", 0, 0)
    oled.text("1.150", 0, 10)
    oled.show()
else:
    print('! No i2c display')
time.sleep_ms(5000)
Ejemplo n.º 3
0
from machine import I2C, Pin
import ssd1306
import time


wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
    print('connecting to network...')
    wlan.connect('SSID NAME', 'SSID PASSWORD')
    while not wlan.isconnected():
        pass
print('network config:', wlan.ifconfig())

i2c = I2C(sda=Pin(4), scl=Pin(5))
display = ssd1306.SSD1306_I2C(64, 48, i2c)
display.fill(0)

while True:
    print(time.localtime()[5])
    if(time.localtime()[5] % 5 ==0):
        #coinmarket
        response = urequests.get('https://api.coinmarketcap.com/v1/ticker/bitcoin/')
        data_btc = response.json()
        btc_price = data_btc[0]["price_usd"]
        print(btc_price)

        #paribu
        response2 = urequests.get('https://www.paribu.com/ticker')
        data_btc_paribu = response2.json()
        btc_price_tl = data_btc_paribu['BTC_TL']["last"]
Ejemplo n.º 4
0
import ssd1306
from machine import I2C, Pin
from dht import DHT22
from time import sleep

i2c = I2C(-1, Pin(5), Pin(4))
oled = ssd1306.SSD1306_I2C(64, 48, i2c)

dht = DHT22(Pin(2))



def measure_realtime():
    dht.measure()
    sleep(0.2)
    dht.measure()

def term1():
    oled.fill(0)
    oled.invert(0)
    oled.text("GDG Bolu", 0,0)
    oled.text("Sicak", 0,10)
    oled.text("Kanlisin", 0,20)
    oled.text(":)", 0, 30)
    oled.show()


kontrol = False
def term2():
    global kontrol
    oled.fill(0)
Ejemplo n.º 5
0
baudrate=1200
#baudrate=57600

y_start=0

uart = UART(1, baudrate=baudrate,rx=19,tx=21,timeout=10)

index=-1
g=10 # m/s^2
rho=997 # kg/m^3

# set up the display
# i2c == (scl,sda)

i2c = I2C(-1, Pin(14), Pin(2))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
bme=bme280.BME280(i2c=i2c)

#header_text="-- DEMO @ EPA --"
while True:
    
    index=index+1
    
    oled.fill(0)
    #oled.text(header_text,0,0)
    #oled.text("reading #"+str(index),0,0)
    

    # get pressure readings
    try:
        bme280_params=bme.values
# completely minimal functions to control the lora and the oled
# (no classes, only module variables)

# functions are broken out for easy testing in a notebook cell

from machine import Pin, I2C
import time
import ssd1306
from LightLora import spicontrol, sx127x

oledrst = Pin(16, Pin.OUT)
oledrst.value(1)
i2c = I2C(scl=Pin(15), sda=Pin(4), freq=450000)
o = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3c)


def writeoled(*ss):
    o.fill(0)
    for i, s in enumerate(ss):
        o.text(s, 0, i * 8)
    o.show()


pkt = {}


def _doReceive(sx12, pay):
    if pay and len(pay) > 4:
        pkt["srcAddress"] = pay[0]
        pkt["dstAddress"] = pay[1]
        pkt["srcLineCount"] = pay[2]
Ejemplo n.º 7
0
#    * micropython v1.8.5+ - het moet module importeren ondersteunen
#    * ssd1306.mpy op de ESP8266
#  2017-1027 PePo new for My FeatherWing shield - works!
# ----------------------
from micropython import const
from machine import Pin, I2C
import ssd1306
import time

# 2017_01010 updated I2C constructor
# i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
i2c = I2C(scl=Pin(5), sda=Pin(4))
print('i2c.scan: ', i2c.scan())  #[60]
__WIDTH = const(128)  # screen dimensions
__HEIGHT = const(32)
oled = ssd1306.SSD1306_I2C(__WIDTH, __HEIGHT, i2c)


# several examples ..
def whiteScreen():
    oled.fill(1)
    oled.show()


def clearScreen():
    oled.fill(0)
    oled.show()


# 4 pixels ON in the corners
def pixelsInCorner(w=__WIDTH, h=__HEIGHT):
Ejemplo n.º 8
0
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)
        rssi = str(station.status('rssi'))
        #graphics.fill_rect(1,1,128,10,1)
        oled.text(rssi + 'dBm', 75, 10, 1)

        if 0 == p36.value():
            #pos 4 -0v
            ant = 3
        elif 0 == p39.value():
            #pos3 -12v
            ant = 2
        elif 0 == p34.value():
            #Pos 2 +12v
            ant = 1
        elif 0 == p35.value():
            #Pos1 12vAC
            ant = 0
        else:
            autoAntenna()

        if ant == 0:
            #Position 1
            AnT = 'LONG WIRE'
            Pin2.on()
            sleep(0.1)
            Pin4.on()
            sleep(0.1)
            Pin5.on()

        if ant == 1:
            #Position 2
            AnT = 'BEAM'
            Pin2.off()
            sleep(0.1)
            Pin4.off()
            sleep(0.1)
            Pin5.on()

        if ant == 2:
            #Position 3
            AnT = '40m DIPOLE'
            Pin2.off()
            sleep(0.1)
            Pin4.on()
            sleep(0.1)
            Pin5.on()

        if ant == 3:
            #Position 4
            AnT = 'DUMMY LOAD'
            Pin2.off()
            sleep(0.1)
            Pin4.off()
            sleep(0.1)
            Pin5.off()

        if old_ant != ant:
            old_ant = ant

        graphics.fill_rect(22, 20, 128, 10, 0)
        oled.text('Ant: ' + AnT, 1, 20, 1)
        oled.show()
Ejemplo n.º 9
0
import ssd1306
import machine
import time

print("loading")
WIDTH = 128
HEIGHT = 64
times = 0
i2c = machine.I2C(0)
sensor = machine.ADC(4)
conversion_factor = 3.3 / (65535)

oled = ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c)
oled.fill(0)

oled.text("MicroPython", 15, 0)
oled.text("on Pi Pico", 20, 10)
oled.text("OLED+TEMP", 29, 30)
oled.text("v0.1", 40, 40)
oled.text("01/02 2021", 25, 50)
oled.show()
time.sleep(5)

while True:
    reading = sensor.read_u16() * conversion_factor
    temperature = 27 - (reading - 0.706) / 0.001721

    oled.fill(0)
    oled.text("smithmule", 0, 0)
    oled.text("was here 2021", 0, 10)
    oled.text("Clock cycles:", 0, 20)
Ejemplo n.º 10
0
ds.convert_temp()
time.sleep_ms(750)
temp_1w = ds.read_temp(roms[0])
print('t=', temp_1w)

time.sleep_ms(2000)

####################################################################
# test OLED
print('*** Testing display... ***')

import ssd1306

# init display
print('display init...')
display = ssd1306.SSD1306_I2C(128, 32, i2c)  #почем адрес захардкожен?
print('OK')

display.fill(0)
display.text('Hello! =)', 10, 10, 1)
display.show()
time.sleep_ms(5000)
display.fill(0)
display.show()

####################################################################
# test PIR

print('*** Testing PIR... ***')

pir_pin = machine.Pin(14, machine.Pin.IN)
import network
import socket
import struct

#---Variables-----------------------------------------------

host = '192.168.4.1'  #necesitem ip del NCAP, que al primer socket actua com a servidor (host)
port = 2000  #port del primer socket
s = None
data = ''
ssid = 'NCAP'  #dades de la xarxa del NCAP
connection = False
password = '******'

i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))  #inicializa I2C
oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)  #inicializa pantalla
oled.fill(0)  #texto de inicio

#oled.text(">", 120, 25)
oled.text("Welcome!", 30, 25)
oled.invert(0)
oled.show()
utime.sleep_ms(800)

devices = i2c.scan()  #escanea dispositivos conectados por i2c
oled.text("Initializing", 15, 40)
oled.text("......", 40, 50)

oled.show()
utime.sleep_ms(3000)
oled.show()
Ejemplo n.º 12
0

def GetLocalTH():
    ClearDisplay()
    d = dht.DHT11(machine.Pin(4))
    DisplayMsg('{:16}'.format("Local Temp:"), 16)
    DisplayMsg('{:^16}'.format(str(d.temperature())), 24)
    DisplayMsg('{:16}'.format("Local Humidity:"), 40)
    DisplayMsg('{:^16}'.format(str(d.humidity())), 48)
    display.show()


i2c = machine.I2C(scl=machine.Pin(4), sda=machine.Pin(5))
Width = 128
Height = 64
display = ssd1306.SSD1306_I2C(Width, Height, i2c)

CITY = 'City you want the weather from'
API_KEY = 'OpenWeatherAPI'
SSID = 'Name of the WIFI connection'
pwd = 'Wifi connection password'

ReceivedData = Getweather(CITY, API_KEY)
start_time = time.ticks_ms() // 1000

while ConnectWifi(SSID, pwd):
    time_now = time.ticks_ms() // 1000

    if (time_now - start_time) < (3 * 60):
        ShowTime()
        time.sleep(30)
Ejemplo n.º 13
0
 def reset(self):
     pins.oled_reset.off()
     time.sleep_ms(50)
     pins.oled_reset.on()
     
     self.oled = ssd1306.SSD1306_I2C(128, 64, pins.i2c)
Ejemplo n.º 14
0
def initSSD1306():
    Pin(25, Pin.OUT).value(0) #gnd
    Pin(26, Pin.OUT).value(1) #vcc
    i2c = I2C(-1, Pin(27), Pin(14)) 
    return ssd1306.SSD1306_I2C(128, 64, i2c)
Ejemplo n.º 15
0
import ssd1306
import machine
###
i2c = machine.I2C(scl=machine.Pin(2), sda=machine.Pin(0))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)  #creation instance

f = open('lille1.txt')  #ouverture image binaire format texte
listline = f.readlines()  #lit et stocke toutes les lignes du fichier
f.close()

oled.fill(0)

for j in range(len(listline)):  #j est donc le numero de ligne
    compteur = 0
    for i in listline[j]:  #i est donc le numero de colonne
        if i != '\n':
            if int(i) != 0:
                oled.pixel(compteur, j + 10, int(i))
            compteur = compteur + 1
oled.show()
Ejemplo n.º 16
0
from struct import unpack
from cayennelpp import CayenneLPP
from time import sleep
from micropython import const

stop = False
#LED_GPIO = const(2)
#led = machine.Pin( LED_GPIO, mode=machine.Pin.OUT )
led = Pin(2, Pin.OUT)
relay1 = Pin(12, Pin.OUT)
temp = 0
pa = 0
hum = 0
i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))
bme = bme280.BME280(i2c=i2c)
d = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)
uart = UART(2, 115200, timeout=300)
s = CCS811.CCS811(i2c=i2c)
rstr = ""


def sendATcommand(ATcommand):
    print("Command: {0}\r\n".format(ATcommand))
    uart.write("{0}\r\n".format(ATcommand))
    rstr = uart.read().decode('utf-8')
    print(rstr)
    return (rstr)


def led_blink(led):
    global stop
Ejemplo n.º 17
0
def initialize_screen():  # Initializes the SSD1306 screen
    global i2c
    global oled
    i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
    oled = ssd1306.SSD1306_I2C(128, 32, i2c)
    oledclear()
Ejemplo n.º 18
0
# ##########################################################

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

DISPLAY_WIDTH = 128  # Width of display in pixels.
DISPLAY_HEIGHT = 32  # Height of display in pixels.

# make i2c
i2c = I2C(scl=Pin(21), sda=Pin(22))
#print(i2c.scan())

# make OLED-display object
oled = ssd1306.SSD1306_I2C(DISPLAY_WIDTH, DISPLAY_HEIGHT, i2c)
# blank oled
oled.fill(0)
oled.show()

# Configure message that will scroll.
#MESSAGE = 'Hello world this is a fun scroller!'
#MESSAGE = 'MicroPython funny  scroller!'
MESSAGE = 'MicropPython Rocks!  '

# Other configuration:
FONT_WIDTH = 8  # Width of font characters in pixels.
FONT_HEIGHT = 8  # Height of the font characters in pixels.
#ORG: AMPLITUDE      = 0.3*(DISPLAY_HEIGHT - FONT_HEIGHT)  # Amplitude of sine wave, in pixels.
AMPLITUDE = 0.5 * (DISPLAY_HEIGHT - FONT_HEIGHT
                   )  # Amplitude of sine wave, in pixels.
Ejemplo n.º 19
0
		# oled.text('{}'.format(winddeg), 40, 22)
	
	try: 
		city = weatherDic['name']								# City name
	except KeyError:
		print('city name miss')
	else:
		print('City: {}'.format(city))
		oled.text('{}'.format(city), 0, 22)



if __name__ == '__main__':
	i2c = I2C(-1, scl=Pin(5), sda=Pin(4)) # initialize access to the I2C bus
	i2c.scan()
	oled = ssd1306.SSD1306_I2C(128, 32, i2c) # the width=128 and height=32
	# runTime = time.time() + 60 # program life time
	
	ConnectWIFI('Columbia University','') # connect esp8266 to a router
	
	locationDic = json.loads(GetLocation()) # get the current location, and transfer the json string to json dictionary

	lat = locationDic['location']['lat'] # latitude
	lng = locationDic['location']['lng'] # longitude

	weatherDic = json.loads(GetWeather(lat, lng)) # get the current weather, and transfer the json string to json dictionary
	
	oled.fill(0)
	ShowWeather(weatherDic, oled)
	oled.show()
	
Ejemplo n.º 20
0
def configure_oled():
    # Configure oled
    i2c = I2C(-1, scl=Pin(22), sda=Pin(21))
    oled = ssd1306.SSD1306_I2C(128, 64, i2c)
    return oled
Ejemplo n.º 21
0
import ssd1306
import time

# define the display size:
width   = 128   # pixels
height  = 64    # pixels

# define i2c pins:
data    = machine.Pin(4)
clk     = machine.Pin(5)

# create i2c object:
i2c = machine.I2C(scl=clk, sda=data)

#create oled object:
oled = ssd1306.SSD1306_I2C(width, height, i2c)

# blank the display:
oled.fill(0)
oled.show()
time.sleep_ms(500)

# the framebuf class contains methods for drawing rectangles
# fill_rect, rect - also use these with height/width of 1 pixel to create lines:

#oled.framebuf.rect(0, 0, 128, 16, 1)
#oled.framebuf.rect(0, 16, 128, 48, 1)
#oled.show()

INTERVAL = 50
def hallSensor(number_of_measurements, frequency):
    from machine import I2C, Pin
    import esp32
    import time
    """The library to write to the OLED display isn閳ユ獩 
  part of the standard MicroPython library by default. 
  So, you need to upload the library to your ESP32/ESP8266 board. """
    import ssd1306

    oled_rst = Pin(16, Pin.OUT)
    oled_rst.value(1)

    esp32.hall_sensor()  #Measure Hall effect

    # ESP32 Pin assignment
    i2c = I2C(-1, Pin(15), Pin(4))
    #Configure your OLED display using the appropiate pixel resolution
    oled_width = 128
    oled_height = 64
    text_row = []
    for n in range(7):
        text_row.append(
            n * 10 + 4
        )  #this will give you 6 lines with the default text size. print(text_row[n])
    #Create a display object where you will drwa your shapes.
    display = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
    #Optional: Set all pixels off
    display.fill(0)
    #Vertically centered text
    display.text('Hall', 19, text_row[2])
    display.text('Effect', 19, text_row[3])
    display.show()

    #the esp32 is just too slow to execute this function
    """
    def displayText(string1,string2):
  
    def __init__():
      string1=''
      string2=''
  
    i2c = I2C(-1, Pin(15), Pin(4))
    display = ssd1306.SSD1306_I2C(128, 64, i2c)
    display.fill(0)
    #Set the appropiate parameters for x,y coordinated according to font size
    display.text(str(string1), 0,5)
    display.text(str(string2), 0,15)
    display.show()
"""
    def getInternalTemperature():
        temp = round((((esp32.raw_temperature() - 32) / 1.8)), 1)
        return temp


#Calibrate the sensor to neglect local magnestism

    def detect_magnetism():

        i = 0
        local_magnetism = []
        while i < 1000:
            i += 1
            time.sleep_ms(0)
            local_magnetism.append(esp32.hall_sensor())

            #print(local_magnetism,'\n')
        m_avg = sum(local_magnetism) / len(local_magnetism)
        print('Local magnetism measure =', m_avg)
        return m_avg, local_magnetism

    m_avg, local_magnetism = detect_magnetism()

    #Set high-low filter boundary values
    high = round(max(local_magnetism), 2)
    low = round(min(local_magnetism), 2)

    #Activate sensor readings
    i = 0
    j = 0
    while i < number_of_measurements:
        i += 1
        time.sleep(frequency)

        if esp32.hall_sensor() > high or esp32.hall_sensor() < low:
            j += 1
            temp = getInternalTemperature()
            print(1,
                  temp)  #it seems the integrated hall sensor has high variance

            for n in range(80, 120):
                for m in range(25, 45):
                    display.pixel(n, m, 0)
            display.text(str(j), 90, text_row[3])
            display.show()

        else:
            print(0, temp)

        print
Ejemplo n.º 23
0
#import network and socket libraries to connect with wifi and receive data from the server.
import network
import socket
#For Parsing Json data and Getting response from URLs
import urequests
import utime
# Libraries to communicate with the OLED Display
import machine
import ssd1306

#Specifiy Desired Pins For CLK and DATA respectively
i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4))
# 128 is X direction pixels and 32 is y direction pixels
display = ssd1306.SSD1306_I2C(128, 64, i2c)


def connect_Wifi():
    # Fill the Display with 0's
    display.fill(0)
    display.text('connecting....', 0, 0)
    display.show()
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network')
        wlan.connect('SWATI', '8585865764')
        while not wlan.isconnected():
            pass
    print('network config', wlan.ifconfig())
    display.text('Connected', 0, 20)
    display.show()
Ejemplo n.º 24
0
# author: h.serimer 04.2021 https://github.com/eproje/uPy_Course
# Board: Lolin32 Lite
# OLED ile basit osiloskop

from machine import * #machine kutuphanesindeki tum objeler
import ssd1306
import gc

#hardware I2C-0, overclock(1.2Mhz)
oled = ssd1306.SSD1306_I2C(128, 64, I2C(0,freq=1200000))
#ADC input
pot = ADC(Pin(34))
pot.atten(ADC.ATTN_11DB)       #Full range: 3.3v

freq(240000000) #overclock, normalde 160Mhz
y_list = [63] * 128 #128 elemanli baslangic degeri 63 olan dizi OSC gorunumu icin

oled.fill(0)#oled buffer temizlensin onceki calismalardan birseyler kalmis olabilir

print("Program basladi")

while True:
    y = 63-int((pot.read() * 63)/4095)
    y_list[127] = y
    for x in range(0, 127):
        oled.pixel(x,y_list[x],0) #oncekini sil
        y_list[x] = y_list[x+1]   #1 pixel kaydir
        oled.pixel(x,y_list[x], 1)#yeniyi yukle
    oled.show()#oled tazele/yazdir
    gc.collect()#hafiza temizlensin
Ejemplo n.º 25
0
    for x in devices:
        print(hex(x), end=' ')
    print(' ')
"""
devices:  [54, 60]
list devices in hexa
0x36
0x3c
"""

# oled 60, 0x3c
print("create ssd1306 oled")
try:
    #https://randomnerdtutorials.com/micropython-oled-display-esp32-esp8266/
    #oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
    oled = ssd1306.SSD1306_I2C(128, 32, i2c)

    # display version and errors counters from RTC memory
    oled.fill(0)  # with black , 1 with white
    oled.text("Pabou ECS v%s" % version, 0, 2)  # X,Y
    s = r.memory()  #  will print b'\x01\x01\x00\x00\x00'
    s = '%s %s %s %s %s' % (s[0], s[1], s[2], s[3], s[4])  # str to print
    print(s)
    oled.text("flag: %s" % s, 0, 20)  # X,Y
    oled.show()
    sleep(3)

except Exception as e:
    print('Exception create oled ', str(e))

###############################################
Ejemplo n.º 26
0
from machine import I2C, Pin
import settings, network, sntp

oled=False
_i2c=I2C(-1, Pin(settings.scl), Pin(settings.sda))
if 60 in set(_i2c.scan()):
    import ssd1306
    oled=ssd1306.SSD1306_I2C(settings.oledtype[0],settings.oledtype[1],_i2c) # what pixels?
    _t=sntp.asctime()
    _ip=network.WLAN(network.STA_IF).ifconfig()[0]
    _dot2=_ip.index('.', _ip.index('.') + 1)
    # squeezed to 64x48 oled as per wemos D1 shield
    oled.text("pSuite",0,0,1) # txt, x, y, colour
    oled.text(_ip[0:_dot2+1] ,0,10,1)
    oled.text(_ip[_dot2+1:] ,6,20,1)
    oled.text(_t[11:],0,30,1)
    oled.text(_t[0:6]+_t[8:10],0,40,1) # date yy not yyyy ( fits D1 mini oled)
    oled.show()

# better layout option for 128x64 display?

# see framebuf calls: oled uses framebuf:  0=black 1=white
#     http://docs.micropython.org/en/latest/esp8266/library/framebuf.html#module-framebuf
Ejemplo n.º 27
0
# GND   --> GND
# VCC   --> 5v or 3.3v
# DAT   --> D14

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

# ESP32 Pin assignment
i2c = I2C(1, scl=Pin(4),
          sda=Pin(5))  # 5=SDK/SDA  4=SCK/SCL  As per labeling on ESP32 DevKi

# Define the OLED width and height
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

while True:
    try:

        oled.fill(0)

        oled.text('Temperature: ', 0, 0)
        oled.text('NONE', 0, 10)

        oled.text('Humidity: ', 0, 30)
        oled.text('NONE', 0, 40)

        oled.show()

    except OSError as e:
Ejemplo n.º 28
0
def coolingsystem():
    global cooling_pump
    p12 = machine.Pin(12)
    cooling_pump = machine.PWM(p12)
    cooling_pump.freq(0)

    i2c = I2C(scl=Pin(22), sda=Pin(23), freq=100000)  #defining Pins
    oled = ssd1306.SSD1306_I2C(128, 32, i2c)  #accesing the ssd1306 package
    oled.fill(0)  #clears display
    oled.show()  #refreshes display

    def updateOLED(
            waterTempText, ODText, RPMText
    ):  #input should be numbers, int or float, for all 3 variables
        oled.fill(0)  #clears display
        oled.text(("Temp: " + str(waterTempText) + " C"), 0,
                  0)  #shows water temperature
        oled.text(("Intensity: " + str(ODText)), 0, 10)  #shows OD
        oled.text(("M.freq.: " + str(RPMText)), 0, 20)  #shows RPM
        oled.show()  #refreshes display

    p33 = machine.Pin(33, Pin.OUT)
    p33.value(0)

    prev_error = 0
    P = 20000
    I = 1000
    D = 100

    global current_temp
    global Thread_cooling
    start_time = time.time()
    count = 0
    while (True):
        Thread_cooling = True
        count = count + 1
        time.sleep_ms(1000)
        lock.acquire()
        temp_av = 0
        for i in range(0, 200):
            time.sleep_ms(10)
            temp = read_temp(temp_sens)
            temp_av = temp_av + temp
        temp_av = temp_av / 200

        current_temp = temp_av
        error = current_temp - reference_temp

        print('Thermistor temperature: ' + str(current_temp))

        PID = int(
            pid_update(P, I, D, error, current_temp, reference_temp,
                       prev_error))
        if (count % 10) == 0:
            f = open('Temperature.txt', 'a')
            f.write(
                str(time.time() - start_time) + ';' + str(current_temp) + '\n')
            f.close()

        print("PID output: " + str(PID))

        if PID > 40000:
            PID = 40000
        elif PID < 1000:
            PID = 1000

        if PID <= 5000:
            p33.value(1)
        elif PID > 5000:
            p33.value(0)

        print("Power Level for Peltier element: " + str(p33.value()))
        print("Intensity: " + str(intensity_av))
        print("concentration: " + str(concentration))
        updateOLED(current_temp, intensity_av, cooling_pump.freq())

        des_motor_freq = PID
        motor_steps = abs(des_motor_freq - cooling_pump.freq()) / 1000
        motor_steps = int(1 + motor_steps)
        for i in range(0, motor_steps):
            time.sleep_ms(10)
            if abs(des_motor_freq - cooling_pump.freq()) < 1000:
                cooling_pump.freq(cooling_pump.freq() + des_motor_freq -
                                  cooling_pump.freq())
                break
            elif (des_motor_freq - cooling_pump.freq()) > 0:
                cooling_pump.freq(cooling_pump.freq() + 1000)
            else:
                cooling_pump.freq(cooling_pump.freq() - 1000)
        print("Motor frequency: " + str(cooling_pump.freq()))

        lock.release()
        time.sleep(2)
Ejemplo n.º 29
0
import network
import usocket, ussl, utime
import machine, ssd1306
import ujson

import config
import time_utils
import qry
import utils

oled = ssd1306.SSD1306_I2C(config.OLED_WIDTH, config.OLED_HEIGHT,
                           config.OLED_I2C)

sta_if = network.WLAN(network.STA_IF)
sta_if.active(1)

sta_if.connect(config.SSID, config.WPAKEY)

for n in range(0, 10):
    oled.fill(0)
    utils.oled_ml_msg('trying to connect {} sec left..'.format(10 - n), oled)
    utime.sleep(1)

utils.oled_ml_msg('connected {}'.format(sta_if.ifconfig()[0]), oled)

time_utils.init_time()

N_ITEMS = 4
DELAY_BETWEEN_CHECKS = 20

Ejemplo n.º 30
0
#analog clock with ESP8266 and SSD1306 OLED display

import machine, ssd1306, math, time

i2c = machine.I2C(scl=machine.Pin(5),
                  sda=machine.Pin(4))  #setup the I2C protocol for the display
oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)  #set up the display
rtc = machine.RTC()  #initiate the RealTimeClock

#setup clock elements

center = (31, 31)  #center of the clock in pixels
face_radius = 30
long_hand = 25  #length of the minutes hand
short_hand = 15  #length of the hours hand


def coordinates(angle, radius):
    '''calculate coordinates of a point on the circle given angle and radius'''

    x = int(center[0] + radius * math.cos(angle))
    y = int(center[1] + radius * math.sin(angle))

    return x, y


def time_decoder(timestamp):
    '''extract hours and minutes from a timestamp expressed in seconds since Epoch'''

    full_time = time.localtime(timestamp)  #returns a tuple
    hours = full_time[3] % 12  #fourth element is hours in 24hrs format