Please refer to page 516. I have removed the code for the blink LED and BME280 code sections. I would like to add an additional LED to control. I am having issues coding the comunications between main.py and webpage.py. Any pointers or suggestions would be appreciated. Thank you
Hi.
I’m sorry for taking so long to get back to you.
Can you be a little more specific? What have you built so far and what errors did you encounter?
Regards,
Sara
Thank you Francisco and Sara for the reply. I’m having issues controlling a second GPIO pin (Relay 1). My attempts are commented out.
# Rui Santos & Sara Santos – Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-micropython-ebook/
# Import necessary modules
import network
import asyncio
from config import wifi_ssid, wifi_password
import socket
import time
from machine import Pin
# Constant variable to save the HTML file path
HTML_FILE_PATH = “webpage.html”
# Create several LEDs
#led_blink = Pin(0, Pin.OUT)
relay_0_control = Pin(0, Pin.OUT) # Relay 0
relay_1_control = Pin(1, Pin.OUT) # Relay 1
#onboard_led = Pin( 2, Pin.OUT)
# Initialize LED state_0
state_0 = ‘OFF’
state_1 = ‘OFF’ # State of Relay 1
# Function to read HTML content from the file
def read_html_file():
with open(HTML_FILE_PATH, “r”) as file:
return file.read()
# HTML template for the webpage
def webpage(state_0):
# def webpage(state_0, state_1): # Add Relay 1 to webpage
# Get new sensor readings every time you serve the web page
html_content = read_html_file()
html = html_content.format(state_0=state_0)
# html = html_content.format(state_0=state_0, state_1=state_1) # Add 2nd Relay
print(webpage)
return html
# Init Wi-Fi Interface
def init_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
# Connect to your network
wlan.connect(ssid, password)
# Wait for Wi-Fi connection
connection_timeout = 10
while connection_timeout > 0:
print(wlan.status())
if wlan.status() >= 3:
break
connection_timeout -= 1
print(‘Waiting for Wi-Fi connection…’)
time.sleep(1)
# Check if connection is successful
if wlan.status() != 3:
print(‘Failed to connect to Wi-Fi’)
return False
else:
print(‘Connection successful!’)
network_info = wlan.ifconfig()
print(‘IP address:’, network_info[0])
return True
# Asynchronous functio to handle client’s requests
async def handle_client(reader, writer):
global state_0
print(“Client connected”)
request_line = await reader.readline()
print(‘Request:’, request_line)
# Skip HTTP request headers
while await reader.readline() != b”\r\n”:
pass
request = str(request_line, ‘utf-8’).split()[1] # This gets the second argument
# request_1 = str(request_line, ‘utf-8’).split()[2] # This gets the third argument – Relay 1
print(‘Request:’, request)
# Relay 0
# Process the request and update variables
if request == ‘/lighton?’:
print(‘Relay 0 on’)
relay_0_control.value(1)
state_0 = ‘ON’
elif request == ‘/lightoff?’:
print(‘Relay 0 off’)
relay_0_control.value(0)
state_0 = ‘OFF’
# Relay 1
if request_1 == ‘/lighton?’:
print(‘Relay 1 on’)
relay_1_control.value(1)
state_1 = ‘ON’
elif request_1 == ‘/lightoff?’:
print(‘Relay 1 off’)
relay_1_control.value(0)
state_1 = ‘OFF’
# Generate HTML response
response = webpage(state_0)
# response = webpage(state_0, state_1) # Get state of both relays
# Send the HTTP response and close the connection
writer.write(‘HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n’)
writer.write(response)
await writer.drain()
await writer.wait_closed()
print(‘Client Disconnected’)
#async def blink_led():
# while True:
# led_blink.toggle() # Toggle LED state_0
# await asyncio.sleep(0.5) # Blink interval
async def main():
if not init_wifi(wifi_ssid, wifi_password):
print(‘Exiting program.’)
return
# Start the server and run the event loop
print(‘Setting up server’)
server = asyncio.start_server(handle_client, “0.0.0.0”, 80)
asyncio.create_task(server)
#asyncio.create_task(blink_led())
while True:
print(‘Loop’)
# Add other tasks that you might need to do in the loop
# await asyncio.sleep(5)
# onboard_led.toggle()
# Create an Event Loop
loop = asyncio.get_event_loop()
# Create a task to run the main function
loop.create_task(main())
try:
# Run the event loop indefinitely
loop.run_forever()
except Exception as e:
print(‘Error occured: ‘, e)
except KeyboardInterrupt:
print(‘Program Interrupted by the user’)
Hi.
Please share your code using Github or Pastebin so that it keeps indentation.
Regards,
Sara