先看外观,包括选择串口号、波特率、清空接受框、保存等功能
![](https://i-blog.csdnimg.cn/blog_migrate/a7616c29dc51e26d23ea8b16d620b7f0.png)
本设计的主体如下
//串口接收数据
//private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (this.SP != null)
{
Control.CheckForIllegalCrossThreadCalls = false;
string dataRecive = SP.ReadExisting();
//输出语句println()
//Console.WriteLine(dataRecive);
//使用阻塞io暂停cmd窗口消失
//Console.ReadLine();
//方法1:
// txtReceive.AppendText(DateTime.Now.ToString("yyy-MM-dd hhh:mm ->") + dataRecive);
//方法2:
//this.txtReceive.Text = this.txtReceive.Text + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss ->") + dataRecive + "\n" ;
this.txtReceive.Text = this.txtReceive.Text + dataRecive ;//不知道为什么加了时间,会断成两截
if( dataRecive != null && dataRecive.Length>41)
{
try
{
Con.Open();
string query = "insert into [Table] values('" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "', '" + dataRecive.Substring(0, 2) + "','" + dataRecive.Substring(3, 2) + "','" + dataRecive.Substring(6, 8) + "','" + dataRecive.Substring(6, 8) + "','" + dataRecive.Substring(6, 8) + "','" + dataRecive.Substring(33, 8) + "')";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
//MessageBox.Show("保存成功");
Con.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
Debug.WriteLine(this.receive);//Debug一下结果
//SqlConnection Con = new SqlConnection(@"Data Source=(localdb)\Projects;Initial Catalog=My;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
同时保存入数据库
}
}
注意需要先链接数据库
//函数:链接数据库
SqlConnection Con = new SqlConnection(@"Data Source=LAPTOP-3KOP5ILG;Initial Catalog=My;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); //新建一个全局数据库对象,使用该对象来操作全局的,@""是连接字符串,用于获取/打开SQLserver
其中UWB信号需要的波特率为460800,在前端设计的时候编辑列
初始化串口控件和参数
//初始化串口控件和参数
string[] portList = System.IO.Ports.SerialPort.GetPortNames();
portList = this.GetDistinct(portList).ToArray();
if (portList != null && portList.Length > 0)
{
Array.Sort(portList);
this.cboPortList.Items.Clear();
this.cboPortList.Items.AddRange(portList);
this.cboPortList.SelectedIndex = 0;
}
this.cboBaudRate.SelectedIndex = 10;
this.cboDataBits.SelectedIndex = 2;
this.cboParity.SelectedIndex = 0;
this.cboStopBits.SelectedIndex = 0;