使用手机(网页)控制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>
相关推荐
fffzd4 分钟前
STM32:OLED原理
stm32·单片机·嵌入式硬件·iic·oled·嵌入式软件
清风66666610 小时前
基于单片机与DAC0832的双路波形信号发生系统设计
单片机·嵌入式硬件·毕业设计·课程设计·期末大作业
azwsm12 小时前
电路元器件和GPIO控制器
单片机·嵌入式硬件
kebidaixu15 小时前
FreeRTOS 移植到 STM32F407VETX 记录(一)
stm32·单片机·嵌入式硬件
点灯小铭16 小时前
基于单片机的数码管定时插座设计与定时开关功能实现
单片机·嵌入式硬件·毕业设计·课程设计·期末大作业
阿乔外贸日记16 小时前
埃塞俄比亚出口全流程注意事项
大数据·人工智能·智能手机·云计算·汽车
点灯小铭18 小时前
基于单片机的多模式智能洗衣机设计
单片机·嵌入式硬件·毕业设计·课程设计·期末大作业
项目題供诗19 小时前
STM32-AD单通道&AD多通道(十九)
stm32·单片机·嵌入式硬件
南岸的水19 小时前
BMS国标充电解析
单片机·嵌入式硬件·mcu
清风66666619 小时前
基于单片机的可调数控电源设计
单片机·嵌入式硬件·mongodb·毕业设计·课程设计·期末大作业