• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

Book – Learn Raspberry Pi Pico W with MicroPython V1_1, section 11.5

Q&A Forum › Category: Raspberry Pi › Book – Learn Raspberry Pi Pico W with MicroPython V1_1, section 11.5
0 Vote Up Vote Down
John White asked 2 months ago

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

Question Tags: Pico W
6 Answers
0 Vote Up Vote Down
FRANCISCO GABRIEL BELMONTE-PEREZ answered 1 month ago

Can you give more details?. What issues are you finding?

0 Vote Up Vote Down
Sara Santos Staff answered 1 month ago

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

0 Vote Up Vote Down
John White answered 1 month ago

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’)

0 Vote Up Vote Down
Sara Santos Staff answered 1 month ago

Hi.
Please share your code using Github or Pastebin so that it keeps indentation.
Regards,
Sara

0 Vote Up Vote Down
John White answered 1 month ago

Sara, Thank you for your assistance. I was able to get it working.

0 Vote Up Vote Down
Sara Santos Staff answered 1 month ago

Ok. Great.
I’m glad you made it work.
I’ll mark this issue as resolved. If you need further help, you just need to open a new question in our forum.
 
Regards, 
Sara

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.