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

1)ESP32S3

cpp 复制代码
#include <WiFi.h>
#include <HTTPClient.h>



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

javascript 复制代码
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

javascript 复制代码
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="turnon">开灯</button>
    <button @click="turnoff">关灯</button>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'HelloWorld',
  data() {
    return {
      data:'',
    }
  },
  props: {
    msg: String
  },
  methods:{
    turnon(){
      alert('开灯');
      axios.get('http://192.168.0.105:8888/setled?len=20').then( response => {
        this.data = response.data;
        console.log(this.data);
      }).catch(err => {
        console.error("there is an err", err);
      })
    },
    turnoff(){
      alert('关灯');
      axios.get('http://192.168.0.105:8888/setled?len=30').then( response => {
        this.data = response.data;
        console.log(this.data);
      }).catch(err => {
        console.error("there is an err", err);
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
相关推荐
芯岭技术26 分钟前
PY32MD310单片机:高性能、低功耗的32位电机控制微控制器
单片机·嵌入式硬件
小龙报2 小时前
【51单片机】深度解析 51 串口 UART:原理、配置、收发实现与工程化应用全总结
c语言·开发语言·c++·stm32·单片机·嵌入式硬件·51单片机
Lester_11019 小时前
STM32 高级定时器PWM互补输出模式--如果没有死区,突然关闭PWM有产生瞬间导通的可能吗
stm32·单片机·嵌入式硬件·嵌入式软件
小李独爱秋11 小时前
“bootmgr is compressed”错误:根源、笔记本与台式机差异化解决方案深度指南
运维·stm32·单片机·嵌入式硬件·文件系统·电脑故障
进击的小头13 小时前
实战案例:51单片机低功耗场景下的简易滤波实现
c语言·单片机·算法·51单片机
宵时待雨16 小时前
STM32笔记归纳8:时钟
笔记·stm32·单片机·嵌入式硬件
JJRainbow17 小时前
SN75176 芯片设计RS-232 转 RS-485 通信模块设计原理图
stm32·单片机·嵌入式硬件·fpga开发·硬件工程
宁静致远202118 小时前
STM32模拟IIC读取PCF8563
stm32·单片机·嵌入式硬件
三佛科技-1341638421218 小时前
宠物洗澡打泡机方案,宠物泡泡机MCU方案开发设计分享
单片机·嵌入式硬件·物联网·智能家居·pcb工艺·宠物
芯岭技术18 小时前
低成本315/433M接收芯片 XL420 SOP8封装,支持 1527 等常见 OOK编码
单片机·嵌入式硬件