import network
import urequests as requests
from machine import Pin, ADC
from time import sleep as delay
import uasyncio as asyncio
ldr = ADC(Pin(33))
# Firebase constants
firebase_url = 'Your Firebase URL'
firebase_secret = 'Your Database Secret'
firebase_endpoint = 'Your desired endpoint'
def connect_to_wifi(ssid='Wokwi-GUEST', password=''):
""" Connecting to Wi-Fi... """
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print('Connecting to Wi-Fi...')
delay(1)
print('Connected to Wi-Fi:', wlan.ifconfig())
async def sendData(traffic: int) -> None:
""" Send data to firebase asnchronously """
url = f"{firebase_url}/{firebase_endpoint}.json?auth={firebase_secret}"
data = {
"traffic_rate": traffic
}
try:
response = requests.put(url, json=data)
if response.status_code == 200:
print(f'Successfully sent {data}')
response.close()
else:
print('Failed to send data')
response.close()
except Exception as e:
print('Error:', str(e))
async def main():
traffic = 0
connect_to_wifi()
while True:
current_value = ldr.read()
if current_value > 2000:
traffic += 2
else:
if traffic < 1:
traffic = 0
else:
traffic -= 1
print(f'Current LDR Value: {current_value}, Traffic Level: {traffic}')
await sendData(traffic)
await asyncio.sleep(2)
asyncio.run(main())