我从网上找的C#程序,串口读取磁传感器数据,有5列数据:Time,XAxis,YAxis,ZAxis,TotalMagnetic。我自己添加了一个连接数据库功能,为什么就是读不进去数据。还有这个分割符是不是这样用的。[pre lang="arduino" line="1" file="C#读并保存到数据库"] #region **接收数据事件**
//当串口的读缓存区有数据到达时会触发DataReceived事件,
//serialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.gb_send.Enabled = isSend;
//数据完整性判断,保证接收完整的数据 //该区域是判断数据的完整性的,我把这几行代码注释掉了。
// if (isSend) //即使不完整我也读出来
//{
// if (serialPort1.BytesToRead != writeByte.Length)
// {
// return;
// }
// }
byte[] readByte = new byte[serialPort1.BytesToRead];
serialPort1.Read(readByte, 0, readByte.Length);
string s = string.Empty;
if (cbx_hex.Checked)
{
for (int i = 0; i < readByte.Length; i++)
{
s += readByte.ToString("X2") + " ";
}
}
else
{
System.Text.UTF8Encoding utf8 = new UTF8Encoding();
s = utf8.GetString(readByte);
}
if (cbx_pause.Checked)
{
SetData("");
}
else
{
SetData(s);
}
receiveLength = readByte.Length;
receiveSum += receiveLength;
this.label_recieve.Text = receiveSum.ToString();
}
/*
* 接收数据是在辅助线程上发生的,而更新UI(即把接收到的数据反映到txt_receive上)是在主线程上发生的
* 如果不加处理,线程不一致,会出现“假死现象
* 开辟新的线程,定义委托,是异步接收方式
* 直接在主线程上接收是同步接收方式
*/
delegate void SetTextCallback(string text);
private void SetData(string text)
{
if (this.txtb_receive.InvokeRequired)
{
if (cbx_newline.Checked)
{
SetTextCallback d = new SetTextCallback(SetData);
this.Invoke(d, new object[] { text+Environment.NewLine});
}
else
{
SetTextCallback d = new SetTextCallback(SetData);
this.Invoke(d, new object[] { text });
}
}
else
{
if (cbx_newline.Checked)
{
//this.txtb_receive.Text += text+Environment.NewLine;//这种方法会多出空行
this.txtb_receive.AppendText(text);
}
else
{
//this.txtb_receive.Text += text + " "; //这个地方是控制增加的,数据库就是在数据发生变化的地放进行检测,保存。
this.txtb_receive.Text += text ; //这个地方是控制增加的,数据库就是在数据发生变化的地放进行检测,保存。
if (conn.State == ConnectionState.Open) //打开数据库为ture,关闭为false
{
//string text1 = Regex.Replace(text, @"[/n/r]", "\t");
string text1 = Regex.Replace(text, "//r//n", "");
string[] strs = text1.Split('\t'); //将字符串text按\t分割。Split是分隔符(这里的分符是arduino中编写的“\t”还是“,”。如果arduino是“\t”在里也是“\t”,如果arduino是“,”这里也是“,”)
// string[] strs = strs1.Split(Environment.NewLine);
if (strs.Length != 5) //就是说这里的字符串长度是5(Time,XAxis,YAxis,ZAxis,TotalMagnetic)这是为了与数据库中存储的数据一一对应。
return; //也就是说下面insert into Arduino(Time,XAxis,YAxis,ZAxis,TotalMagnetic)多加一个字符串的话,这就应该是6
//保存在数据库中的格式Time,XAxis,YAxis,ZAxis,TotalMagnetic之间是“,”号相连的,那后面的也要用"','"号相连
strSQL = "insert into Arduino(Time,XAxis,YAxis,ZAxis,TotalMagnetic) values ('" + double.Parse(strs[0]) + "','" + double.Parse(strs[1]) + "','" + double.Parse(strs[2]) + "','" + double.Parse(strs[3]) + "','" + double.Parse(strs[4]) + "')";
//执行SQL语句
comm = new SqlCommand(strSQL, conn);
sdr = comm.ExecuteReader();
sdr.Close();
}
}
}
txtb_receive.SelectionStart = txtb_receive.Text.Length;
txtb_receive.ScrollToCaret();
}
#endregion [/code] |