1.实验清单:
激光测距传感器WT-VL53L0 L1距离模块1个 ,维特智能USB转4路TTL串口数据采集板1块,type-c数据接口1根
接线说明:
红色 模块电源,3.3V 或 5V 输入
绿色 串行数据输入(RX),TTL 电平
黄色 串行数据输出(TX),TTL 电平
黑色 接地-负极
2.添加串口通讯组件
3.源代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace distanceTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//禁止捕获对错误线程的调用,必须加这一句才会报错。
try
{
string[] Portlist = System.IO.Ports.SerialPort.GetPortNames();
for (int i = 0; i < Portlist.Length; i++)
{
comboBox1.Items.Add(Portlist[i]);
}
comboBox1.SelectedIndex = 0;
comboBox2.SelectedIndex = 0;
}
catch
{
MessageBox.Show(“初始化检查失败,请检查串口的连接使用情况!\n程序将自动退出!”,“串口初始化”,MessageBoxButtons.OK,MessageBoxIcon.Warning);
this.Close();
Application.Exit();
}
}
/// <summary>
/// 获得字符串中开始和结束字符串中间的值
/// </summary>
/// <param name="str">字符串</param>
/// <param name="begin">开始</param>
/// <param name="end">结束</param>
/// <returns></returns>
public static string GetValue(string str, string begin, string end)
{
Regex rg = new Regex("(?<=(" + begin + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(str).Value;
}
/// 判断字符串中是否包含数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumber(String str)
{
bool result = false;
for (int i = 0; i < str.Length; i++)
{
if (Char.IsNumber(str, i))
{
result = false;
}
else
{
result = true;
}
}
return result;
}
private void button1_Click(object sender, EventArgs e)//开始测距
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
timer1.Enabled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//串口收到数据时触发接收事件,开始接收数据
{
textBox1.AppendText(serialPort1.ReadExisting().Replace(" ", ""));
textBox2.Text = textBox1.Text.Substring(textBox1.Text.Length - 8, 4);
if (IsNumber(textBox2.Text))
{
label3.Text = "正在测量距离...";
}
else
{
string str = textBox2.Text; //我们抓取当前字符当中的数字部分
string result = System.Text.RegularExpressions.Regex.Replace(str, @"[^0-9]+", "");
textBox3.Text = result;
}
}
private void button2_Click(object sender, EventArgs e)//关闭测量
{
serialPort1.Close();
timer1.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)//设置接收字符串信息编码为GB2312
{
serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");
}
private void button3_Click(object sender, EventArgs e)//如果距离小于35厘米就报警
{
int i = int.Parse(textBox3.Text);
if (i < 350)//如果小于350毫米,报警。
{
Console.Beep(1777, 300);//设定电脑发出1700赫兹的音频,持续时间为0.3秒。
}
}
private void timer1_Tick_1(object sender, EventArgs e)
{
button3.PerformClick();
}
}
}