-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
294 lines (249 loc) · 10.3 KB
/
Copy pathmain.py
File metadata and controls
294 lines (249 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""
Proyecto de investigacion
manejo de sensor as7341 adafruit
by Jordan del Aguila
azul -> sda Pin(25) verde -> slc Pin(26) blanco -> 3.3v negro -> GND
# --- PASO 1: configurar_smux_f1_f4() ---
# pos valor canal longitud color
0x01 -> ADC0 = F1 415nm Violeta
0x05 -> ADC1 = F2 445nm Azul índigo (izquierdo)
0x0C -> ADC1 = F2 445nm Azul índigo (derecho, suma con 0x05)
0x00 -> ADC2 = F3 480nm Azul (izquierdo)
0x0F -> ADC2 = F3 480nm Azul (derecho, suma con 0x00)
0x05 -> ADC3 = F4 515nm Verde azulado (izquierdo)
0x0D -> ADC3 = F4 515nm Verde azulado (derecho, suma -> dividir por 2)
0x08 -> ADC4 = Clear Luz total sin filtro
0x11 -> ADC4 = Clear Luz total sin filtro (redundante)
0x13 -> ADC5 = NIR Infrarrojo cercano
# --- PASO 2: configurar_smux_f5_f8() ---
# pos valor canal longitud color
0x06 -> ADC0 = F5 555nm Verde puro (izquierdo)
0x09 -> ADC0 = F5 555nm Verde puro (derecho, suma con 0x06)
0x04 -> ADC1 = F6 590nm Amarillo (izquierdo)
0x0E -> ADC1 = F6 590nm Amarillo (derecho, suma con 0x04)
0x07 -> ADC2 = F7 630nm Naranja-Rojo (izquierdo)
0x0A -> ADC2 = F7 630nm Naranja-Rojo (derecho, suma con 0x07)
0x03 -> ADC3 = F8 680nm Rojo (izquierdo)
0x0E -> ADC3 = F8 680nm Rojo (derecho, suma con 0x03)
0x08 -> ADC4 = Clear Luz total sin filtro
0x11 -> ADC4 = Clear Luz total sin filtro (redundante)
0x13 -> ADC5 = NIR Infrarrojo cercano
MQTT configuración
ID cliente = PDcOJxgPKiA4GzwBORE8CzU
Nombre de usuario = PDcOJxgPKiA4GzwBORE8CzU
contraseña = 6owovZELMcmYJ9U+34KT8sCm
"""
from machine import Pin, I2C
from umqtt.simple import MQTTClient
import network, ntptime, time
#configurar internet
WIFI_SSID = "WIFI-ITM"
WIFI_PASSWORD = "" #A
THINGSPEAK_MQTT_SERVER = "mqtt3.thingspeak.com"
THINGSPEAK_CHANNEL_ID = "3283767"
MQTT_CLIENT_ID = "PDcOJxgPKiA4GzwBORE8CzU"
MQTT_USERNAME = "PDcOJxgPKiA4GzwBORE8CzU"
MQTT_PASSWORD = "6owovZELMcmYJ9U+34KT8sCm"
PUBLISH_INTERVAL = 20
#i2c protocolo de comunicacion sensor <> esp32
#configuracion hardware
i2c = I2C(0, scl=Pin(26), sda=Pin(25), freq=400000)
AS7341_ADDR = 0x39
#metodos de comunicacion y lectura
def escribir_registro(reg, value):
i2c.writeto_mem(AS7341_ADDR, reg, bytes([value]))
def leer_registro(reg):
return i2c.readfrom_mem(AS7341_ADDR, reg, 1)[0]
def leer_canal(reg_lsb):
data = i2c.readfrom_mem(AS7341_ADDR, reg_lsb, 2)
return (data[1] << 8) | data[0] #[0] porque el sensor devuelve bits pero convertimos a numero decimales
#<<8 desplaza 8 bits a la izquierda
# 2. Inicialización
print("Escaneando I2C...")
if AS7341_ADDR in i2c.scan():
print(f"Sensor encontrado en 0x{AS7341_ADDR:02x}")
else:
raise Exception("No se encontró el sensor. Revisa el cableado.")
device_id = leer_registro(0x92)
print(f"Device ID: 0x{device_id:02x}")
#SMUX es el que decide que canal mostrar, ya que el sensor solo muestra de a 6 canales
def configurar_smux_f1_f4():
escribir_registro(0xAF, 0x10) # SMUX modo escritura
escribir_registro(0x00, 0x30) # F3 izq -> ADC2
escribir_registro(0x01, 0x01) # F1 izq -> ADC0
escribir_registro(0x02, 0x00)
escribir_registro(0x03, 0x00)
escribir_registro(0x04, 0x00)
escribir_registro(0x05, 0x42) # F4 izq -> ADC3 / F2 izq -> ADC1
escribir_registro(0x06, 0x00)
escribir_registro(0x07, 0x00)
escribir_registro(0x08, 0x50) # Clear -> ADC4
escribir_registro(0x09, 0x00)
escribir_registro(0x0A, 0x00)
escribir_registro(0x0B, 0x00)
escribir_registro(0x0C, 0x20) # F2 der -> ADC1
escribir_registro(0x0D, 0x04) # F4 der -> ADC3
escribir_registro(0x0E, 0x00)
escribir_registro(0x0F, 0x30) # F3 der -> ADC2
escribir_registro(0x10, 0x01) # F1 der -> ADC0
escribir_registro(0x11, 0x50) # Clear -> ADC4
escribir_registro(0x12, 0x00)
escribir_registro(0x13, 0x06) # NIR -> ADC5
escribir_registro(0x80, 0x11)
while leer_registro(0x80) & 0x10:
time.sleep_ms(10)
def configurar_smux_f5_f8():
escribir_registro(0xAF, 0x10) # SMUX modo escritura
escribir_registro(0x00, 0x00)
escribir_registro(0x01, 0x00)
escribir_registro(0x02, 0x00)
escribir_registro(0x03, 0x40) # F8 izq -> ADC3
escribir_registro(0x04, 0x02) # F6 izq -> ADC1
escribir_registro(0x05, 0x00)
escribir_registro(0x06, 0x10) # F5 izq -> ADC0
escribir_registro(0x07, 0x03) # F7 izq -> ADC2
escribir_registro(0x08, 0x50) # Clear -> ADC4
escribir_registro(0x09, 0x10) # F5 der -> ADC0
escribir_registro(0x0A, 0x03) # F7 der -> ADC2
escribir_registro(0x0B, 0x00)
escribir_registro(0x0C, 0x00)
escribir_registro(0x0D, 0x00)
escribir_registro(0x0E, 0x24) # F8 der -> ADC2 / F6 der -> ADC1
escribir_registro(0x0F, 0x00)
escribir_registro(0x10, 0x00)
escribir_registro(0x11, 0x50) # Clear -> ADC4
escribir_registro(0x12, 0x00)
escribir_registro(0x13, 0x06) # NIR -> ADC5
escribir_registro(0x80, 0x11)
while leer_registro(0x80) & 0x10:
time.sleep_ms(10)
def esperar_medicion():
escribir_registro(0x80, 0x01)#PON apagar SP_EN
time.sleep_ms(10)
escribir_registro(0x80,0x03) #SP_EN ON
timeout = 50 # máximo 500ms
while timeout > 0:
if leer_registro(0xA3) & 0x40:
return True
time.sleep_ms(10)
timeout -= 1
print("Timeout esperando medición")
return False
#configuracion de datos y envio a internet
def conectar_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Conectando al WiFi...", end="")
timeout = 20
while not wlan.isconnected() and timeout>0:
print(".", end="")
time.sleep(0.5)
timeout -= 1
if wlan.isconnected():
print("\nWiFi conectado. IP:", wlan.ifconfig()[0])
else:
print("\nNo se pudo conectar al WiFi")
return False
print("Sincronizando hora con servidor NTP...")
try:
ntptime.settime()
print("Hora sincronizada con NTP")
except Exception as e:
print("No se pudo sincronizar la hora:", e)
def conectar_mqtt():
client = MQTTClient(
MQTT_CLIENT_ID,
THINGSPEAK_MQTT_SERVER,
user=MQTT_USERNAME,
password=MQTT_PASSWORD,
port=1883, #8883
ssl=False #True
)
client.connect()
print("Conectado a ThingSpeak MQTT como device.")
return client
def enviar_datos(client, f1, f2, f3, f4, f5, f6, f7, f8):
topic = f"channels/{THINGSPEAK_CHANNEL_ID}/publish"
payload = (f"field1={f1}&field2={f2}&field3={f3}&field4={f4}"
f"&field5={f5}&field6={f6}&field7={f7}&field8={f8}")
try:
client.publish(topic, payload)
print("Datos espectrales enviados a ThingSpeak")
print(f"Espectro: {f1}, {f2}, {f3}, {f4}, {f5}, {f6}, {f7}, {f8}")
print("/" * 40)
except Exception as e:
print("Error enviando datos:", e)
def hora_local():
t = time.localtime()
UTC_Colombia = -5
hora = (t[3] + UTC_Colombia) % 24
minuto = t[4]
segundo = t[5]
return hora, minuto, segundo
#configuracion
escribir_registro(0x87, 0x02) #ganancia
escribir_registro(0x80, 0x01) #PON
escribir_registro(0x81, 0x0A) #tiempo de integración (ATIME)
datos_acumulados = []
ultimo_segundo = time.ticks_ms()
print("1. Conectando WiFi...")
conectar_wifi()
print("2. Conectando MQTT...")
try:
client = conectar_mqtt()
print("Broker conectado")
except Exception as e:
print("Error de MQTT:", e)
# Inicializar variables de tiempo y acumulados
ultimo_segundo = time.ticks_ms()
datos_acumulados = []
# 4. Ejecución
print("Iniciando sensor...")
for _ in range(2):
configurar_smux_f1_f4()
esperar_medicion()
configurar_smux_f5_f8()
esperar_medicion()
print("Listo. Leyendo...")
print("-" * 60)
try:
while True:
#paso 1 = leer canales 1 al 4
configurar_smux_f1_f4()
if esperar_medicion():
f1 = leer_canal(0x95) # ADC0 -> F1 415nm
f2 = leer_canal(0x97) // 2 # ADC1 -> F2 445nm (doble fotodiodo, normalizar)
f3 = leer_canal(0x99) // 2 # ADC2 -> F3 480nm (doble fotodiodo, normalizar)
f4 = leer_canal(0x9B) // 2 # ADC3 -> F4 515nm (doble fotodiodo, normalizar)
clear = leer_canal(0x9D) // 2 # ADC4 -> Clear (doble fotodiodo, normalizar)
nir = leer_canal(0x9F) # ADC5 -> NIR
#paso 2 = canales 5 al 8
configurar_smux_f5_f8()
if esperar_medicion():
f5 = leer_canal(0x95) // 2 # ADC0 -> F5 555nm (doble fotodiodo, normalizar)
f6 = leer_canal(0x97) // 2 # ADC1 -> F6 590nm (doble fotodiodo, normalizar)
f7 = leer_canal(0x99) // 2 # ADC2 -> F7 630nm (doble fotodiodo, normalizar)
f8 = leer_canal(0x9B) // 2 # ADC3 -> F8 680nm (doble fotodiodo, normalizar)
print(f" F1 (415nm): {f1:5d} | F2 (445nm): {f2:5d} | F3 (480nm): {f3:5d} | F4 (515nm): {f4:5d}")
print(f" F5 (555nm): {f5:5d} | F6 (590nm): {f6:5d} | F7 (630nm): {f7:5d} | F8 (680nm): {f8:5d}")
print(f" ---- Canal Clear: {clear:5d} | Canal NIR: {nir:5d} ----")
print("-" * 60)
print(f"DATA:{f1},{f2},{f3},{f4},{f5},{f6},{f7},{f8}")
if time.ticks_diff(time.ticks_ms(), ultimo_segundo) >= 1000:
lectura_actual = [f1, f2, f3, f4, f5, f6, f7, f8]
datos_acumulados.append(lectura_actual)
print(f"Muestra {len(datos_acumulados)}/20 guardada...")
ultimo_segundo = time.ticks_ms()
if len(datos_acumulados) >= 20:
promedios = []
for col in range(8):
suma_canal = 0
for fila in datos_acumulados:
suma_canal += fila[col]
promedios.append(suma_canal / 20)
enviar_datos(client, *promedios)
datos_acumulados = []
time.sleep(0.5)
except KeyboardInterrupt:
print("Lectura detenida.")