" 为了实现网页端控制STM32灯的亮灭,我们需要分为前端和后端两部分。前端负责与用户交互,后端负责与STM32通信。以下是一种可能的实现方法:
前端(网页):
1. HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>STM32灯控制</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>STM32灯控制</h1>
<button id="onBtn">开</button>
<button id="offBtn">关</button>
<script src="stm32_control.js"></script>
</body>
</html>
```
2. JavaScript代码(stm32_control.js):
```javascript
$(document).ready(function() {
$("#onBtn").click(function() {
$.ajax({
type: "POST",
url: "http://localhost:3000/turnOn",
data: {}
});
});
$("#offBtn").click(function() {
$.ajax({
type: "POST",
url: "http://localhost:3000/turnOff",
data: {}
});
});
});
```
后端(Node.js + Express):
1. 安装所需依赖:
```
npm init -y
npm install express
npm install body-parser
```
2. 创建一个名为"app.js"的文件,并添加以下代码:
```javascript
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
const ledPin = 13; // 假设STM32的LED引脚为13
app.post("/turnOn", function(req, res) {
digitalWrite(ledPin, HIGH); // 打开LED
res.sendStatus(200);
});
app.post("/turnOff", function(req, res) {
digitalWrite(ledPin, LOW); // 关闭LED
res.sendStatus(200);
});
app.listen(3000, function() {
console.log("Server is running on port 3000");
});
```
注意:这里我们假设你已经了解了如何使用Node.js和Express搭建服务器,以及如何使用Arduino语法进行STM32编程。
要运行后端代码,请在命令行中输入以下命令:
```
node app.js
```
然后,打开浏览器并访问:
```
http://localhost:3000
```
现在,你应该可以看到网页上的“开”和“关”按钮。点击它们将向后端发送请求,从而控制STM32灯的亮灭。"