实例介绍
【实例简介】设定连续读取时间后,从COM口获取超声波传感器传来的数据,并把数据写入文本文件,以便3后续分析使用
【实例截图】
【核心代码】
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Threading; using System.IO; namespace CommTest2 { public partial class Form1 : Form { SerialPort MSComm1 = new SerialPort(); string GetTxt = ""; Int32 rTextNum = 0; Int32 SendCount = 0; Int32 GetCount = 0; Int32 ErrCount = 0; Int32 SendLen = 0; Int32 SendTime = 0; Int32 Allsum = 0; Int32 CloseCount = 0; Byte[] arr_command = new Byte[0]; Queue<byte> QU = new Queue<byte>(480); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string[] ports = System.IO.Ports.SerialPort.GetPortNames(); MSComm1.ReadTimeout = 32; timer_send.Enabled = false; SendLen = Convert.ToInt32(TextBox3.Text); int i = 0; foreach (string port in ports) { ComboBox1.Items.Add(port); i ; } if (i > 0) { ComboBox1.SelectedIndex = 0; if (MSComm1.IsOpen) { MSComm1.Close(); } } } private void Button4_Click(object sender, EventArgs e) { if (RadioButton3.Checked) { open_232(); GetTxt = ""; timer2.Enabled = true; 发送一组数(); } else { open_232(); 发送一组数(); } } private void open_232() { if (this.Button4.Text == "打开串口") { try { SendLen = Convert.ToInt32(TextBox3.Text); SendTime = Convert.ToInt32(TextBox1.Text); if (SendLen > 254) SendLen = 2; if (SendTime <= 1) SendTime = 1; Allsum = 0; Array.Resize(ref arr_command, 1); arr_command[0] = (byte)(85); timer_send.Interval = SendTime; timer_send.Enabled = true; MSComm1.ReadTimeout = 200; //MSComm1.DiscardOutBuffer(); MSComm1.PortName = ComboBox1.Text; MSComm1.BaudRate = Convert.ToInt32(ComboBox2.Text); MSComm1.Parity = Parity.None; MSComm1.StopBits = StopBits.One; this.MSComm1.DataReceived = new System.IO.Ports.SerialDataReceivedEventHandler(this.MSComm1_DataReceived); MSComm1.Open(); this.Button4.Text = "关闭串口"; } catch { MessageBox.Show("串口操作失败"); } } else { try { MSComm1.Close(); this.Button4.Text = "打开串口"; timer_send.Enabled = false; } catch { MessageBox.Show("串口操作失败"); } } } private void MSComm1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { if (this.RadioButton2.Checked || RadioButton3.Checked) { int outLen = MSComm1.BytesToRead; byte[] AA = new byte[outLen]; MSComm1.Read(AA, 0, outLen); for (int i = 0; i < outLen; i ) { QU.Enqueue(AA[i]); } } } catch { throw; } } private void 发送一组数() { try { if (MSComm1.IsOpen) { MSComm1.Write(arr_command, 0, 1); //String str_in = ""; //for (int i = 0; i < SendLen; i ) //{ // str_in = (arr_command[i].ToString("X2").PadLeft(2, '0').PadRight(3, ' ')); //} //RichTextBox1.Text = "发送:" str_in "\r\n" RichTextBox1.Text; } else { // RichTextBox1.Text = "请打开串口先!" "\r\n" RichTextBox1.Text; } } catch { } } private void timer1_Tick(object sender, EventArgs e) { try { if (QU.Count >= SendLen) { byte upData = 0; string tempStr = ""; bool IsErr = false; System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding(); byte[] byteArray = new byte[2]; byte tempB = QU.Dequeue(); byteArray[0] = tempB ; tempB = QU.Dequeue(); byteArray[1] = tempB; for (int i = 0; i < 2; i ) { tempStr = (byteArray[i].ToString("X2").PadLeft(2, '0').PadRight(3, ' ')); } 发送一组数(); GetTxt = tempStr "\r\n"; RichTextBox1.Text = tempStr "\r\n" RichTextBox1.Text; rTextNum = rTextNum 1; if (rTextNum > 100) { RichTextBox1.Text = ""; rTextNum = 0; } if (IsErr) { ErrCount ; ToolLabel4.Text = "误码次数:" ErrCount.ToString() "次"; WriteError(tempStr); } GetCount = SendLen; ToolLabel3.Text = "接收字节:" GetCount.ToString() "Byte"; rTextNum = rTextNum 1; if (rTextNum > 200) { RichTextBox1.Text = ""; rTextNum = 0; } } } catch { } } /// <summary> /// 写入错误日志 /// </summary> /// <param name="txt"></param> public static void WriteError(string txt) { try { string datatxt = DateTime.Now.Year.ToString() "-" DateTime.Now.Month.ToString() "-" DateTime.Now.Day.ToString(); StreamWriter sw; if (File.Exists("LOG/" datatxt ".txt") == true) { sw = File.AppendText("LOG/" datatxt ".txt"); } else { sw = File.CreateText("LOG/" datatxt ".txt"); } sw.WriteLine(DateTime.Now " " txt); sw.Close(); sw.Dispose(); } catch { } } public static void WriteTxt(string txt) { try { string datatxt = DateTime.Now.Month.ToString() "_" DateTime.Now.Day.ToString() DateTime.Now.Hour.ToString() DateTime.Now.Minute.ToString() DateTime.Now.Second.ToString(); StreamWriter sw; if (File.Exists("LOG/" datatxt ".txt") == true) { sw = File.AppendText("LOG/" datatxt ".txt"); } else { sw = File.CreateText("LOG/" datatxt ".txt"); } sw.WriteLine(txt); sw.Close(); sw.Dispose(); } catch { } } private void Button1_Click(object sender, EventArgs e) { GetCount = 0; SendCount = 0; ErrCount = 0; QU.Clear(); ToolLabel3.Text = "接收次数:" GetCount.ToString() "次"; ToolLabel4.Text = "误码次数:" ErrCount.ToString() "次"; ToolLabel2.Text = "发送次数:" SendCount.ToString() "次"; } private void Tim_232_sta_Tick(object sender, EventArgs e) { if (MSComm1.IsOpen) { ToolLabel1.Text = "串口状态:开"; } else { ToolLabel1.Text = "串口状态:关"; } } private void timer_send_Tick(object sender, EventArgs e) { try { if (this.RadioButton1.Checked ) { // 发送一组数(); rTextNum = rTextNum 1; SendCount = SendCount 1; ToolLabel2.Text = "发送次数:" SendCount.ToString() "次"; if (rTextNum > 200) { RichTextBox1.Text = ""; rTextNum = 0; } } } catch { } } private void timer2_Tick(object sender, EventArgs e) { CloseCount ; Int32 MaxCount = Convert.ToInt32(textBox2.Text) ; if (CloseCount > MaxCount) { CloseCount = 0; MSComm1.Close(); this.Button4.Text = "打开串口"; timer_send.Enabled = false; timer2.Enabled = false; WriteTxt(GetTxt); GetTxt = ""; } } } }
相关软件
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论