import machine
import ssd1306
from machine import I2C, Pin, ADC, Timer
from utime import sleep_us
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
# Configurar LDR
ldr = ADC(Pin(33))
ldr.atten(ADC.ATTN_11DB)
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c, addr=0x3c)
# Abre el archivo CSV en modo de anexar ('a')
with open('datos.csv', 'w') as archivo_csv:
archivo_csv.write('Tiempo,Iluminacion[%]\n')
def oled_print(texto, x, y):
# Tamaño de un carácter (asumiendo 10x10 píxeles)
char_width = 10
char_height = 10
# Calcula las coordenadas en píxeles en función de las coordenadas en caracteres
x_pixels = x * char_width
y_pixels = y * char_height
# Borra solo la región donde se imprimirá el nuevo texto
for i in range(char_height):
for j in range(len(texto) * char_width):
oled.pixel(x_pixels + j, y_pixels + i, 0)
# Imprime el nuevo texto en la posición especificada
oled.text(texto, x_pixels, y_pixels)
# Actualiza la pantalla para mostrar el nuevo texto
oled.show()
def oled_clear():
oled.fill(0)
oled.show()
def fill_area(x_start, y_start, x_end, y_end, color):
for x in range(x_start, x_end + 1):
for y in range(y_start, y_end + 1):
oled.pixel(x, y, color)
sleep_us(1)
def read_sensor_isr(event):
voltage = ldr.read() / 4095 * 3.3
porcentaje = 100 - ((voltage / 3.3) * 100 + 0.5)
porcentaje_formateado = "{:.1f}".format(porcentaje)
oled_print(porcentaje_formateado, 1, 2)
# Abre el archivo CSV en modo de anexar ('a')
with open('datos.csv', 'a') as archivo_csv:
# Escribe los datos en el archivo CSV
archivo_csv.write(f'{event},{porcentaje}\n')
blink_timer = Timer(1)
blink_timer.init(period=1000, mode=Timer.PERIODIC, callback=read_sensor_isr)
oled_print("Sensor LDR:", 0, 0)
oled_print("Iluminacion:", 1, 1)
oled_print("%", 5, 2)