ESP8266|RPi pico 通过ESP8266搭建web服务器(树莓派pico通过esp8266联网)

前言

软件准备

根据树莓派官网的介绍,基于Raspberry pi pico我们可以搭建两种开发环境: Micropython和C/C++

关于开发环境的搭建,国内已经有很多优秀的课程了,我是参考韦东山百问网出的教程搭建的开发环境:

硬件准备

在开始实验之前,需要准备好一下的硬件:
Raspberry pi pico开发板
在这里插入图片描述

ESP8266串口wifi
在这里插入图片描述

接线

uart0我用于串口模块连接到PC显示串口信息,所以我从uart1开始使用,uart1分配给ESP8266使用。

pico引脚ESP8266引脚
VBUSVCC、CH-EN
GNDGND
UART1TX Pin6U0RXD
UART1RX Pin7U0TXD

在这里插入图片描述

C/C++实现代码

/**
 * Copyright (c) 2008-2021 深圳百问网科技有限公司<https://www.100ask.net/>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <string.h>
#include <stdio.h>
#include <math.h>
#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "hardware/gpio.h"
#include "hardware/uart.h"

#define UART_ID uart1
#define BAUD_RATE 115200

#define UART_TX_PIN 4
#define UART_RX_PIN 5

#define RECV_BUFFER 256
char recv_buf[RECV_BUFFER];
int buff_count = 0;

void core1_entry() 
{
    memset(recv_buf,'0',RECV_BUFFER);
    while (1) {
        //printf("%c", uart_getc(UART_ID));
        recv_buf[buff_count++] = uart_getc(UART_ID);         
        if(buff_count >= RECV_BUFFER )   buff_count = 0;
    }
}

int main() {
    stdio_init_all();

    // Set up our UART with the required speed.
    uart_init(UART_ID, BAUD_RATE);

    // Set the TX and RX pins by using the function select on the GPIO
    // Set datasheet for more information on function select
    gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART);
    gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);

    multicore_launch_core1(core1_entry);

    printf("Setting up network on ESP8266...\n");
    printf("  - Setting CWMODE to 1 station mode...\n");
    uart_puts(UART_ID, "AT+CWMODE=1\r\n");
    sleep_ms(2000);
    printf("  - Joining Wifi ...'\n");
    uart_puts(UART_ID, "AT+CWJAP=\"baiwenwang\",\"www.100ask.org\"\r\n");
    sleep_ms(5000);
    printf("done!\n\n");

    printf("Starting Webserver port on ESP8266...\n");
    sleep_ms(1000);
    printf("  - Setting CIPMUX for multiple connections...\n");
    uart_puts(UART_ID, "AT+CIPMUX=1\r\n");
    sleep_ms(2000);
    printf("  - Starting CIPSERVER on port 80...\n");
    uart_puts(UART_ID, "AT+CIPSERVER=1,80\r\n");
    printf("done!\n\n");

    sleep_ms(1000);
    // 查询本地 IP 地址
    uart_puts(UART_ID, "AT+CIFSR\r\n");
    sleep_ms(1000);
    printf("%s\n", recv_buf);  
    printf("Waiting For connection...\n");
    while (true) {
        if (strstr(recv_buf, "+IPD"))
        {    
            printf("! Incoming connection - sending webpage");
            uart_puts(UART_ID, "AT+CIPSEND=0,108\r\n");  // Send a HTTP response then a webpage as bytes the 108 is the amount of bytes you are sending, change this if you change the data sent below
            sleep_ms(1000);
            uart_puts(UART_ID, "HTTP/1.1 200 OK\r\n");
            uart_puts(UART_ID, "Content-Type: text/html\r\n");
            uart_puts(UART_ID, "Connection: close\r\n");
            uart_puts(UART_ID, "\r\n");
            uart_puts(UART_ID, "<!DOCTYPE HTML>\r\n");
            uart_puts(UART_ID, "<html>\r\n");
            uart_puts(UART_ID, "It Works!\r\n");
            uart_puts(UART_ID, "</html>\r\n");
            sleep_ms(1000);
            uart_puts(UART_ID, "AT+CIPCLOSE=0\r\n");    // close the connection when done.
            sleep_ms(4000);
            printf("\n\nWaiting For connection...\n");
            sleep_ms(250);
            memset(recv_buf,'0',RECV_BUFFER);
            buff_count = 0;
        }
    }
}

实验现象

在这里插入图片描述

Micropython实现代码

#
# Copyright © 2021 深圳百问网科技有限公司 All Rights Reserved.
# https://www.100ask.net
# https://shop502068889.taobao.com/
#
# SPDX-License-Identifier: BSD-3-Clause
#

from machine import UART
import machine
import _thread
import time
recv_buf="" # receive buffer global variable

print('-- ESP8266 Webserver --')
print (' ')
print ('setting up UART Connection...')
uart = UART(1,115200) # create a UART serial connection using UART1 pins and a baud of 115200
print ('done!')
print (' ')

#Function to read serial response from UART serial into buffer one byte at a time
def uartSerialRxMonitor():
    recv=""
    
    while True:
        recv=str(uart.read(1).decode("utf-8"))
        print(recv, end='')
        global recv_buf
        recv_buf=recv_buf+recv

print ('Starting connection to ESP8266...')
_thread.start_new_thread(uartSerialRxMonitor, ()) # start serial monitor as a thread
print ('done!')
print (' ')

print ('Setting up network on ESP8266...')
print ('  - Setting CWMODE to 1 station mode...')
uart.write('AT+CWMODE=1'+'\r\n')
time.sleep(2)
print ('  - Joining Wifi ...')
uart.write('AT+CWJAP="baiwenwang","www.100ask.org"'+'\r\n') # set Wifi network SSID and password here
time.sleep(5)
print ('done!')
print (' ')

print ('Starting Webserver port on ESP8266...')
time.sleep(4)
print ('  - Setting CIPMUX for multiple connections...')
uart.write('AT+CIPMUX=1'+'\r\n')
time.sleep(2)
print ('  - Starting CIPSERVER on port 80...')
uart.write('AT+CIPSERVER=1,80'+'\r\n')
print ('done!')
print (' ')

time.sleep(1)
print (' ')
print ('Waiting For connection...')
while True:
    if '+IPD' in recv_buf: #IPD in serial indicates an incoming connection
        time.sleep(2)
        print ('! Incoming connection - sending webpage')
        uart.write('AT+CIPSEND=0,108'+'\r\n') #Send a HTTP response then a webpage as bytes the 108 is the amount of bytes you are sending, change this if you change the data sent below
        time.sleep(1)
        uart.write('HTTP/1.1 200 OK'+'\r\n')
        uart.write('Content-Type: text/html'+'\r\n')
        uart.write('Connection: close'+'\r\n')
        uart.write(''+'\r\n')
        uart.write('<!DOCTYPE HTML>'+'\r\n')
        uart.write('<html>'+'\r\n')
        uart.write('It Works!'+'\r\n')
        uart.write('</html>'+'\r\n')
        time.sleep(1)
        uart.write('AT+CIPCLOSE=0'+'\r\n') # close the connection when done.
        time.sleep(4)
        print (' ')
        print (' ')
        print ('Waiting For connection...')
        recv_buf=""

实验现象

用到的AT命令:

AT+CWMODE=1
AT+CWJAP="baiwenwang","www.100ask.org"
AT+CIPMUX=1
AT+CIPSERVER=1,80
AT+CIFSR
AT+CIPSEND=0,108 
> HTTP/1.1 200 OK Content-Type: text/html Connection: close <!DOCTYPE HTML> <html>It Works!324</html>

在这里插入图片描述

参考资料

ESP8266 AT指令集

  • 6
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是基于Arduino平台的代码: 首先,需要安装以下库: Adafruit_SSD1306 Wire ESP8266WiFi ESP8266HTTPClient 然后,将HLW8032模块连接到ESP8266的引脚: - VCC -> 3.3V - GND -> GND - SEL -> D1 - CF -> D2 - CF1 -> D3 最后,将0.96 OLED屏幕连接到ESP8266的引脚: - VCC -> 3.3V - GND -> GND - SDA -> D4 - SCL -> D5 代码如下: #include <Wire.h> #include <Adafruit_SSD1306.h> #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> Adafruit_SSD1306 display(128, 64, &Wire, -1); const char* ssid = "your_ssid"; const char* password = "your_password"; float voltage = 0.0; float current = 0.0; float power = 0.0; void setup() { Serial.begin(9600); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); display.clearDisplay(); display.setTextColor(WHITE); display.setTextSize(1); display.setCursor(0,0); display.println("HLW8032 Example"); display.display(); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); pinMode(D1, OUTPUT); digitalWrite(D1, HIGH); } void loop() { HTTPClient http; http.begin("http://192.168.0.100/"); // replace with your server address int httpCode = http.GET(); if (httpCode == HTTP_CODE_OK) { String payload = http.getString(); int index = payload.indexOf(":"); voltage = payload.substring(0, index).toFloat(); payload = payload.substring(index+1); index = payload.indexOf(":"); current = payload.substring(0, index).toFloat(); payload = payload.substring(index+1); power = payload.toFloat(); } http.end(); display.clearDisplay(); display.setCursor(0,0); display.print("Voltage: "); display.print(voltage); display.print("V"); display.setCursor(0,10); display.print("Current: "); display.print(current); display.print("A"); display.setCursor(0,20); display.print("Power: "); display.print(power); display.print("W"); display.display(); delay(1000); } 在这个例子中,ESP8266将通过HTTP请求从服务器获取电压、电流和功率数据,并将其显示在OLED屏幕上。在服务器端,需要编写一个简单的脚本来读取HLW8032模块的数据并将其返回给ESP8266。脚本如下: import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) def read_hlw8032(): GPIO.output(18, GPIO.HIGH) time.sleep(0.00001) GPIO.output(18, GPIO.LOW) voltage = 0.0 current = 0.0 power = 0.0 for i in range(10): GPIO.setup(18, GPIO.IN) while GPIO.input(18) == GPIO.LOW: pass while GPIO.input(18) == GPIO.HIGH: pass GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.LOW) data = [] for j in range(6): byte = 0 for k in range(8): GPIO.setup(18, GPIO.IN) while GPIO.input(18) == GPIO.LOW: pass count = 0 while GPIO.input(18) == GPIO.HIGH: count += 1 if count > 100: break if count > 50: byte |= 1 << (7 - k) data.append(byte) if data[0] == 0x55 and data[1] == 0x55 and data[5] == 0xC0: voltage = ((data[2] << 8) + data[3]) / 100.0 current = ((data[2] << 8) + data[3]) / 1000.0 power = ((data[4] << 8) + data[5]) / 10.0 return voltage, current, power from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def get_data(): voltage, current, power = read_hlw8032() return jsonify({'voltage': voltage, 'current': current, 'power': power}) if __name__ == '__main__': app.run(host='0.0.0.0', port=80) 在这个例子中,使用了Flask框架来编写Web应用程序。该应用程序将在HTTP请求中返回电压、电流和功率数据,并由ESP8266进行处理和显示。请注意,服务器的IP地址需要根据您的网络配置进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

挨踢民工biubiu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值