AccessPoint(APモード)
# Note: To connect to the access point, use the SSID and password defined below.
# You can connect to this access point from a smartphone, tablet, or computer.
# After connecting, you can access the device using the IP address shown in the output.
import network
import gc
import time
# Define the SSID (Wi-Fi name) and password for the access point
SSID: str = "Raspberrypi_PICO_W"
PASSWORD: str = "qwertyuiop1234"
gc.collect() # Run garbage collection to free up memory
# Create the access point interface
ap = network.WLAN(network.AP_IF)
# Configure the access point with the defined SSID and password
ap.config(essid=SSID, password=PASSWORD)
# Set a static IP address: (IP address, subnet mask, gateway, DNS)
ap.ifconfig(("192.168.4.1", "255.255.255.0", "192.168.4.1", "8.8.8.8"))
# Activate the access point so it becomes visible to other devices
ap.active(True)
# Display the network configuration
print("Access Point is ready. Connect from your device:")
print("IP Address: {}\nNet Mask: {}\nGateway: {}\nDNS: {}".format(*ap.ifconfig()))
# Keep the script running to maintain the access point
while True:
time.sleep(1) # Sleep to prevent high CPU usage
変数SSIDとPASSWORDは任意の文字列を指定します。
The variables SSID and PASSWORD can be any string.
APモードでボードの温度を表示。
# This script sets up a Raspberry Pi Pico W as a Wi-Fi Access Point (AP)
# It also starts a basic web server that displays the internal temperature
# of the Pico W in a browser. Useful for learning how to use Wi-Fi, HTTP, and sensors.
import network # For handling Wi-Fi networking
import socket # For creating the HTTP server socket
import gc # Garbage collector to free up memory
import time # To add delays
from machine import ADC # To read the built-in temperature sensor
# ====== Wi-Fi Access Point Configuration ======
# Define the SSID (Wi-Fi name) and password
SSID: str = "Raspberrypi_PICO_W"
PASSWORD: str = "qwertyuiop1234"
# Run garbage collection to clean up memory before starting
gc.collect()
# Create a WLAN interface in AP (Access Point) mode
ap = network.WLAN(network.AP_IF)
# Configure the AP with the SSID and password
ap.config(essid=SSID, password=PASSWORD)
# Set static IP configuration for the AP
# Format: (IP Address, Subnet Mask, Gateway, DNS)
ap.ifconfig(("192.168.4.1", "255.255.255.0", "192.168.4.1", "8.8.8.8"))
# Activate the access point so other devices can see and connect to it
ap.active(True)
# Print AP info to the serial console
print("Access Point is ready. Connect from your device:")
print("IP Address: {}\nNet Mask: {}\nGateway: {}\nDNS: {}".format(*ap.ifconfig()))
# ====== Internal Temperature Sensor Setup ======
# The internal temperature sensor is connected to ADC channel 4
sensor_temp = ADC(4)
# Convert raw ADC value (0–65535) to voltage (0–3.3V)
conversion_factor = 3.3 / 65535
# Define a function to read and convert the temperature
def read_temperature():
reading = sensor_temp.read_u16() * conversion_factor # Convert ADC to voltage
# Formula to convert voltage to temperature in Celsius
# Based on RP2040 datasheet: 27 - (V - 0.706) / 0.001721
temperature_c = 27 - (reading - 0.706) / 0.001721
return round(temperature_c, 2)
# ====== HTTP Server Setup ======
# Get IP address and port for the server
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
# Create a socket for incoming connections
server_socket = socket.socket()
server_socket.bind(addr) # Bind socket to the address
server_socket.listen(1) # Listen for 1 connection at a time
print("HTTP server is running. Access http://192.168.4.1 from your browser.")
# ====== Main Loop: Serve Web Page with Temperature ======
while True:
try:
# Wait for a client to connect
client, addr = server_socket.accept()
print("Client connected from", addr)
# Read the HTTP request from the client
request = client.recv(1024)
# Get the current temperature
temperature = read_temperature()
# Create a simple HTML page with the temperature
html = f"""\
HTTP/1.1 200 OK
<!DOCTYPE html>
<html>
<head>
<title>Pico Temperature</title>
<meta http-equiv="refresh" content="5">
<style>
body {{
font-family: Arial, sans-serif;
text-align: center;
padding-top: 50px;
}}
.temp {{
font-size: 2em;
color: #333;
}}
</style>
</head>
<body>
<h1>Raspberry Pi Pico W</h1>
<p class="temp">Internal Temperature: <strong>{temperature:.1f} degree C</strong></p>
<p>(Page refreshes every 5 seconds)</p>
</body>
</html>
"""
# Send the HTTP response to the client
client.send(html)
# Close the connection
client.close()
except Exception as e:
# If something goes wrong, print the error and close the connection
print("Error:", e)
client.close()
温度をグラフ表示してみた
import network
import socket
import gc
import time
from machine import ADC
SSID = "Raspberrypi_PICO_W"
PASSWORD = "qwertyuiop1234"
gc.collect()
ap = network.WLAN(network.AP_IF)
ap.config(essid=SSID, password=PASSWORD)
ap.ifconfig(("192.168.4.1", "255.255.255.0", "192.168.4.1", "8.8.8.8"))
ap.active(True)
print("Access Point is ready. Connect from your device:")
print("IP Address: {}\nNet Mask: {}\nGateway: {}\nDNS: {}".format(*ap.ifconfig()))
sensor_temp = ADC(4)
conversion_factor = 3.3 / 65535
def read_temperature():
reading = sensor_temp.read_u16() * conversion_factor
temperature_c = 27 - (reading - 0.706) / 0.001721
return round(temperature_c, 1)
# Temperature history list (max 20 entries)
history = []
# Simple Web Server
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
server_socket = socket.socket()
server_socket.bind(addr)
server_socket.listen(1)
print("HTTP server running at http://192.168.4.1")
while True:
temperature = read_temperature()
history.append(temperature)
if len(history) > 20:
history.pop(0) # Keep only the last 20 readings
try:
client, addr = server_socket.accept()
print("Client connected from", addr)
request = client.recv(1024)
# Convert temperature list to JavaScript array format
js_data = ','.join(str(t) for t in history)
html = f"""\
HTTP/1.1 200 OK
<!DOCTYPE html>
<html>
<head>
<title>Pico Temperature History</title>
<meta http-equiv="refresh" content="5">
<style>
body {{
font-family: sans-serif;
text-align: center;
margin-top: 40px;
}}
canvas {{
border: 1px solid #ccc;
}}
</style>
</head>
<body>
<h1>Temperature History</h1>
<p>Current Temperature: <strong>{temperature:.1f} degree C</strong></p>
<canvas id="chart" width="300" height="150"></canvas>
<script>
const data = [{js_data}];
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.strokeStyle = 'blue';
let max = Math.max(...data);
let min = Math.min(...data);
let range = max - min || 1;
let scaleX = canvas.width / (data.length - 1);
let scaleY = canvas.height / range;
for (let i = 0; i < data.length; i++) {{
let x = i * scaleX;
let y = canvas.height - (data[i] - min) * scaleY;
if (i === 0) {{
ctx.moveTo(x, y);
}} else {{
ctx.lineTo(x, y);
}}
}}
ctx.stroke();
</script>
<p>(Graph updates every 5 seconds)</p>
</body>
</html>
"""
client.send(html)
client.close()
except Exception as e:
print("Error:", e)
client.close()
コメント