# ESP32 and Mycropython: Programming your Hardware
# Author: Mordechai Bar Natan
#
# Lesson 4: Add OLED display
# https://wokwi.com/projects/394060981841594369
#
# Remember:
# On a LED, the long leg is the anode (+). Connect it to pin #2.
# The short leg is the cathode (-). Connect it to GND.
# On a momentary switch (button), connect one side to pin #16 and the other side to GND.
# The display has 4 connections: GND, VCC (to 3.3V), SCL (pin #22) & SDA (pin #21)
#
# References
# https://docs.micropython.org/en/latest/library/machine.Pin.html
# https://docs.micropython.org/en/latest/esp8266/tutorial/ssd1306.html#ssd1306
from machine import Pin, SoftI2C, ADC, PWM
from time import sleep
from ssd1306 import SSD1306_I2C
oled_scl_pin = 22 # Orange cable
oled_sda_pin = 21 # Blue cable
red_led_pin = 2
button_pin = 4
i2c = SoftI2C(scl=Pin(oled_scl_pin), sda=Pin(oled_sda_pin), freq=4000000)
oled_w = 128 # display width (0..127)
oled_h = 64 # display hight (0..63)
red_led_state = 0
button_state = 0
oled = SSD1306_I2C(oled_w, oled_h, i2c) # oled will be the display bject
red_led = Pin(red_led_pin, Pin.OUT)
button = Pin(button_pin, Pin.IN, Pin.PULL_UP)
oled.fill(0) # clear the display
oled.text('RED LED OFF', 10, 10) # initial status
oled.show() # show the display
# toggle the LED when the button is pressed and display LED status
while True:
last_state = button_state
button_state = button.value()
if button_state == 0 and last_state == 1:
red_led_state = not(red_led_state)
red_led.value(red_led_state)
oled.fill(0)
if red_led.value() == True:
oled.text('RED LED ON', 10, 10)
else:
oled.text('RED LED OFF', 10, 10)
oled.show()
sleep(0.1)