使用手机(网页)控制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>
相关推荐
振浩微433射频芯片2 小时前
从门锁到考勤,VRC522B如何在近场读卡场景中“稳坐C位”?
网络·人工智能·单片机·物联网
极客猴子9 小时前
能提取抖音视频文案的APP推荐:短视频文案工具合集
人工智能·智能手机·音视频·语音识别
Groundwork Explorer14 小时前
W5500 网卡编程初始化与使用指南
python·单片机
智闲电子设计15 小时前
STM32 SD 卡 + FatFS 实战:掉电丢数据?f_sync 和簇对齐写救你
stm32·单片机·嵌入式硬件
ヾChen17 小时前
ESP32 OTA 踩坑实录
stm32·单片机·嵌入式硬件·物联网·学习
小僧景贤18 小时前
嵌入式ADC高阶深度解析:基于STM32底层原理、误差溯源、硬件调校与工业级落地
单片机·嵌入式硬件·stm32 adc·工业级高精度采集·adc 误差校准·量产固件开发
黑猫学长呀18 小时前
【驱动开发常见问题】编译出现rm: cannot remove `asm/arch‘: Is a directory
驱动开发·单片机·嵌入式硬件·bug·编译报错·kernrl
雨田言炎18 小时前
STM32专题之内部FLASH详解
笔记·stm32·单片机
Be for thing20 小时前
【嵌入式成长10】STC89C51蜂鸣器|有源/无源蜂鸣器区分、三极管驱动、定时器播放音乐实战
单片机·嵌入式硬件·学习
郎哥编程课堂21 小时前
单片机零基础训练营第2天:嵌入式开发常用的三种进制
单片机·嵌入式硬件