Arduino 雷达测距案例

日期 2025-03-12 分组 Arduino 标签 Arduino标签 案例 4分钟 · 663字

硬件需要

软件需要

步骤

Arduino 代码

1
// trigPin和echoPin是用于超声波传感器的引脚
2
const int trigPin = 9;
3
const int echoPin = 10;
4
// buzzerPin是蜂鸣器的引脚
5
const int buzzerPin = 11;
6
// redLedPin和greenLedPin是LED灯的引脚
7
const int redLedPin = 12;
8
const int greenLedPin = 13;
9
10
// 启动函数
11
void setup() {
12
// 定义每个引脚的模式(是输入还是输出)
13
pinMode(trigPin, OUTPUT);
14
pinMode(echoPin, INPUT);
15
pinMode(buzzerPin, OUTPUT);
38 collapsed lines
16
pinMode(redLedPin, OUTPUT);
17
pinMode(greenLedPin, OUTPUT);
18
19
// 用于初始化串口通信,波特率为9600
20
Serial.begin(9600);
21
}
22
23
// 主循环
24
void loop() {
25
long duration, distance;
26
// 触发超声波传感器发送一个信号
27
digitalWrite(trigPin, LOW);
28
delayMicroseconds(2); // 2微妙
29
digitalWrite(trigPin, HIGH);
30
delayMicroseconds(10); // 10微妙
31
digitalWrite(trigPin, LOW);
32
// 测量信号返回的时间
33
duration = pulseIn(echoPin, HIGH);
34
// 将时间转换为距离 29.1是将微秒转换为厘米的一个常数。
35
distance = (duration / 2) / 29.1;
36
37
// 距离小于10厘米,蜂鸣器和红色LED亮起,绿色LED熄灭;否则,蜂鸣器和红色LED熄灭,绿色LED亮起。
38
if (distance < 10) {
39
digitalWrite(buzzerPin, HIGH);
40
digitalWrite(redLedPin, HIGH);
41
digitalWrite(greenLedPin, LOW);
42
} else {
43
digitalWrite(buzzerPin, LOW);
44
digitalWrite(redLedPin, LOW);
45
digitalWrite(greenLedPin, HIGH);
46
}
47
48
// 将距离值输出到串口监视器
49
Serial.println(distance);
50
51
// 程序暂停100毫秒
52
delay(100);
53
}

.NET 代码

1
using System.IO.Ports;
2
3
namespace ArduinoExperiment
4
{
5
public partial class FormMain : Form
6
{
7
SerialPort serialPort = new SerialPort("COM5", 9600);
8
public FormMain()
9
{
10
InitializeComponent();
11
serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
12
}
13
14
15
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
33 collapsed lines
16
{
17
string data = serialPort.ReadLine();
18
Console.WriteLine(data);
19
this.Invoke(new MethodInvoker(delegate
20
{
21
if (int.TryParse(data, out int distance))
22
{
23
label2.Text = $@"当前距离:{data}";
24
25
if (distance < 10)
26
{
27
label1.Text = "距离过近!";
28
label1.BackColor = System.Drawing.Color.Red;
29
}
30
else
31
{
32
label1.Text = "安全距离!";
33
label1.BackColor = System.Drawing.Color.Green;
34
}
35
}
36
}));
37
}
38
39
private void startButton_Click(object sender, EventArgs e)
40
{
41
Console.WriteLine(1);
42
if (!serialPort.IsOpen)
43
{
44
serialPort.Open();
45
}
46
}
47
}
48
}
上一篇: 上位机行业了解
下一篇: Arduino 传感器使用方法