使用手机(网页)控制ESP32S3的LED亮灭

作者 : admin 本文共2416个字,预计阅读时间需要7分钟 发布时间: 2024-06-17 共1人阅读

1)ESP32S3

#include 
#include 



const char* ssid = "TP-LINKxxxxx";
const char* password = "yyyyyy";
int led = 5;
int led2 = 10;
const char* serverURL = "http://192.168.0.105:8888/getled";


void setup() {
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);

  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("正在连接到WiFi...");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print("已连接到 ");
  Serial.println(ssid);
  Serial.print("IP地址:");
  Serial.println(WiFi.localIP());

}

void loop() {

    HTTPClient http;
    String url = serverURL;
    while(true){
    if (WiFi.status() == WL_CONNECTED) {
          
          // 链接url
          http.begin(url); 
          int httpResponseCode = http.GET();
          // 返回值
          String recstr = http.getString(); 

          if (recstr == "off") {
                digitalWrite(led, LOW);
                digitalWrite(led2, LOW);
                Serial.println("led is off");
           } else {
                digitalWrite(led, HIGH);
                digitalWrite(led2, HIGH);
                Serial.println("led is on");
           }
          // http.end();
      }
    }
}

服务器端 NodeJS+KOAJS

const Koa = require('koa');
const app = new Koa();
const router = require("koa-router")();
const { koaBody } = require('koa-body');
const url = require('url');
const fs = require('fs');

app.use(koaBody());


 
// 解决跨域问题的中间件
const cors = async (ctx, next) => {
    // 设置响应头来允许跨域资源共享
    ctx.set('Access-Control-Allow-Origin', '*'); // 允许任何源
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); // 允许的 HTTP 方法
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Accept'); // 允许的 HTTP 头
   
    if (ctx.method === 'OPTIONS') {
      // 对于预检请求直接返回
      ctx.body = 204;
    } else {
      // 非 OPTIONS 请求则继续执行后续中间件
      await next();
    }
  };
   
  // 使用中间件
  app.use(cors);



// 开灯关灯逻辑,前端访问更新这里的文件的值
router.get("/setled", async ctx => {
    const queryObject = url.parse(ctx.url, true).query;
    // 这里设置了一个参数len 如果是20开灯, 否则是关灯,其实这里可以使用一个比较好的参数比较好
    if(queryObject.len === '20'){
        // 写入文件on
        const data = "on";
        const filePath = './file.txt';
        fs.writeFile(filePath,data,'utf8', (err) => {
            if(err) {
                return console.log(err);
            }
            console.log("写入成功")
        });
    } else {
        // 写入文件off
        const data = "off";
        const filePath = './file.txt';
        fs.writeFile(filePath,data,'utf8', (err) => {
            if(err) {
                return console.log(err);
            }
            console.log("写入成功")
        });
    }
    ctx.body = "led is changed";
})


// 硬件访问的地址,开灯或者关灯配置(读取文件中的值)
router.get("/getled", async ctx => {
    try {
        // 同步读取文件
        const data = fs.readFileSync('file.txt', 'utf8');
        console.log(data);
        ctx.body = data;
      } catch (err) {
        console.error(err);
      }
})


app.use(router.routes());
app.use(router.allowedMethods());

// app.use(async (ctx) => {
//   console.log("ctx",ctx);
//   ctx.body = 'ok';
// });

app.listen(8888,'0.0.0.0', () => {
  console.log('Server is running at http://localhost:8888');
});

前端 Vue2


  
    

{{ msg }}

h3 { margin: 40px 0 0; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; }

使用手机(网页)控制ESP32S3的LED亮灭插图

使用手机(网页)控制ESP32S3的LED亮灭插图(1)

使用手机(网页)控制ESP32S3的LED亮灭插图(2)

本站无任何商业行为
个人在线分享 » 使用手机(网页)控制ESP32S3的LED亮灭
E-->