#include <string.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "lwip/tcp.h"
#include "hardware/pwm.h"
#define LED_COUNT 6
uint pins[LED_COUNT] = {2, 3, 4, 5, 6, 7};
uint16_t levels[LED_COUNT] = {0};
void set_pwm(uint pin, uint16_t level) {
gpio_set_function(pin, GPIO_FUNC_PWM);
pwm_set_gpio_level(pwm_gpio_to_slice_num(pin), level);
levels[pin] = level;
}
void all_on() {
for (int i = 0; i < LED_COUNT; i++) set_pwm(pins[i], 4095);
printf("KEY ALL ON\n");
}
void all_off() {
for (int i = 0; i < LED_COUNT; i++) set_pwm(pins[i], 0);
printf("KEY ALL OFF\n");
}
const char *html =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n\r\n"
"<h1>Pico W 6路 PWM 调光</h1>"
"<a href=\"/on\"><button>全部开启</button></a>"
"<a href=\"/off\"><button>全部关闭</button></a>"
"<form action=\"/set\">LED0: <input name=0 size=4><br>"
"LED1: <input name=1 size=4><br>"
"LED2: <input name=2 size=4><br>"
"LED3: <input name=3 size=4><br>"
"LED4: <input name=4 size=4><br>"
"LED5: <input name=5 size=4><br>"
"<button type=submit>应用调光</button></form>";
static err_t http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) {
if (!p) { tcp_close(pcb); return ERR_OK; }
char *r = p->payload;
if (strstr(r, "GET /on")) all_on();
if (strstr(r, "GET /off")) all_off();
for (int i = 0; i < LED_COUNT; i++) {
char key[4]; sprintf(key, "%d=", i);
char *v = strstr(r, key);
if (v) {
int val = atoi(v + 2);
if (val < 0) val = 0;
if (val > 4095) val = 4095;
set_pwm(pins[i], val);
}
}
tcp_write(pcb, html, strlen(html), 0);
pbuf_free(p);
tcp_close(pcb);
return ERR_OK;
}
static err_t http_accept(void *arg, struct tcp_pcb *pcb, err_t err) {
tcp_recv(pcb, http_recv);
return ERR_OK;
}
void http_server() {
struct tcp_pcb *pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, 80);
pcb = tcp_listen(pcb);
tcp_accept(pcb, http_accept);
}
int main() {
stdio_init_all();
for (int i = 0; i < LED_COUNT; i++) {
gpio_init(pins[i]);
gpio_set_dir(pins[i], GPIO_OUT);
}
cyw43_arch_init();
cyw43_arch_enable_sta_mode();
printf("Connecting to WiFi");
while (cyw43_arch_wifi_connect_blocking("Wokwi-GUEST", "", CYW43_AUTH_WPA2_MIXED_PSK)) {
printf(".");
sleep_ms(200);
}
printf(" Connected!\nIP: %s\n", ip4addr_ntoa(netif_ip4_addr(netif_list)));
http_server();
while (1) {
cyw43_arch_poll();
sleep_ms(10);
}
}Loading
pi-pico-w
pi-pico-w