实例介绍
【实例简介】
【实例截图】
【核心代码】
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO.Ports; using System.IO; using System.Threading; using System.Windows.Forms; /* :NUMeric:NORMal:VALue? */ namespace 实验九 { public partial class Form1 : Form { string fileName; FileStream fs; StreamWriter sw; StreamReader sr; string line = ""; //换行符 string recTime = ""; //显示时间 int countWrite = 0;//发送的总字节数 int countRead = 0;//读取的总字节数 int flag = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames()); comboBox1.Text = SerialPort.GetPortNames()[0]; comboBox2.Text = "9600"; comboBox3.Text = "None"; comboBox4.Text = "8"; comboBox5.Text = "One"; button1.BackColor = Color.Green; } private void button1_Click(object sender, EventArgs e) { try { if(button1.Text == "关闭") { serialPort1.Close(); button1.Text = "打开"; button1.BackColor = Color.Green; comboBox1.Enabled = true; comboBox2.Enabled = true; comboBox3.Enabled = true; comboBox4.Enabled = true; comboBox5.Enabled = true; return; } serialPort1.PortName = comboBox1.Text; serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text); switch (comboBox3.SelectedIndex) { case 0: serialPort1.Parity = Parity.None; break; case 1: serialPort1.Parity = Parity.Odd; break; case 2: serialPort1.Parity = Parity.Even; break; } serialPort1.DataBits = Convert.ToInt32(comboBox4.Text); switch (comboBox5.SelectedIndex) { case 0:serialPort1.StopBits = StopBits.None;break; case 1: serialPort1.StopBits = StopBits.One;break; case 2:serialPort1.StopBits = StopBits.Two;break; case 3:serialPort1.StopBits = StopBits.OnePointFive;break; } serialPort1.Open(); comboBox1.Enabled = false; comboBox2.Enabled = false; comboBox3.Enabled = false; comboBox4.Enabled = false; comboBox5.Enabled = false; button1.Text = "关闭"; button1.BackColor = Color.Red; } catch { MessageBox.Show("串口打开失败!"); } } string sendContent; //串口要发送的内容 private void button2_Click(object sender, EventArgs e)//发送按钮 { if (checkBox8.Checked) //定时发送模式 { if (flag == 0) { timer1.Enabled = true; button2.Text = "停止发送"; textWrite.Enabled = false; checkBox5.Enabled = false; checkBox7.Enabled = false; checkBox8.Enabled = false; flag = 1; } else { timer1.Enabled = false; button2.Text = "发送"; textWrite.Enabled = true; checkBox5.Enabled = true; checkBox7.Enabled = true; checkBox8.Enabled = true; flag = 0; } } else SerialPortWrite(); } void SerialPortWrite() { byte[] sendByte; sendContent = textWrite.Text; if (checkBox5.Checked)//启用文件数据源 { sendContent = sr.ReadToEnd(); } if (checkBox7.Checked)//按照十六进制发送 { int hexLength;//十六进制数的个数 if (sendContent.Length % 3 == 0) hexLength = sendContent.Length / 3; else hexLength = sendContent.Length / 3 1; sendByte = new byte[hexLength]; for (int i = 0; i < hexLength; i ) { sendByte[i] = Convert.ToByte(sendContent.Substring(i * 3, 2), 16); } } else//普通发送 { sendByte = new byte[sendContent.Length]; sendByte = Encoding.ASCII.GetBytes(sendContent); } try { serialPort1.Write(sendByte, 0, sendByte.Length); countWrite = sendByte.Length; label9.Text = "发送:" countWrite.ToString(); } catch (InvalidOperationException e) { MessageBox.Show(e.ToString()); return; } if (checkBox6.Checked && !checkBox5.Checked)//是否自动清空 textWrite.Text = ""; } private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { string Hex = ""; string str = ""; string readContent = ""; this.Invoke((EventHandler)(delegate { Thread.Sleep(100); byte[] myByteReceive = new byte[serialPort1.BytesToRead]; serialPort1.Read(myByteReceive, 0,serialPort1.BytesToRead); countRead = myByteReceive.Length; label10.Text = "接收:" countRead.ToString(); if (checkBox4.Checked == true) //暂停接收显示 goto L1; str = System.Text.Encoding.Default.GetString(myByteReceive); if(checkBox9.Checked) ThreadPool.QueueUserWorkItem(new WaitCallback(WriteToFile), str); //str = str.Substring(0, str.IndexOf('\0')); if (checkBox2.Checked) { recTime = "【"; recTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); recTime = " 】 "; readContent = recTime; } if (checkBox3.Checked == true) //十六进制读 { for (int i = 0; myByteReceive[i] != '\0'; i ) Hex = Convert.ToString(myByteReceive[i], 16) " "; readContent = Hex.ToUpper(); } else readContent = str ; readContent = line; if (!checkBox9.Checked) textBoxRead.Text = readContent; L1:; } ) ); //以下为写文件操作 //if (checkBox9.Checked)//接收转向文件 //ThreadPool.QueueUserWorkItem(new WaitCallback(WriteToFile), textBoxRead.Text); } void WriteToFile(object e) { string str = (string)e; sw.Write(str); sw.Flush(); } void WriteToFileJieXi9(object e)//解析之后存入文件中 { string str = (string)e; string temp1;//小数部分 string temp2;//指数部分 string sign;//指数的符号 string nowTime = DateTime.Now.ToString(); nowTime = " "; sw.Write(nowTime); for (int i = 0; i < 6; i ) { temp1 = str.Substring(i * 11, 6); sign = str.Substring(i * 11 7, 1); temp2 = str.Substring(i * 11 8, 2); double f1 = Convert.ToDouble(temp1); int i1 = Convert.ToInt32(temp2); if (sign == "-") i1 = -i1; f1 = f1 * Math.Pow(10, i1); //开始写入 sw.Write(f1); sw.Write("; "); } sw.WriteLine(); sw.Flush(); //关闭流 } void WriteToFileJieXi10(object e)//解析之后存入文件中 { DateTime time = DateTime.Now; sw.WriteLine(time.ToString("yyyy-MM-dd hh:MM:ss ")); byte[] myByte = (byte[])e; //bool yangan, huogan, hongwaixian, shuijin; int kaiguanliang = myByte[4]; if ((kaiguanliang & 128) == 128) //yangan = true; sw.Write("有烟雾 "); else sw.Write("无烟雾 "); if ((kaiguanliang & 64) == 64) //huogan = true; sw.Write("有火感 "); else sw.Write("无火感 "); if ((kaiguanliang & 32) == 32) // hongwaixian = true; sw.Write("有红外线 "); else sw.Write("无红外线 "); if ((kaiguanliang & 16) == 16) // shuijin = true; sw.Write("有水浸 "); else sw.Write("无水浸 "); int wendu; wendu = myByte[7]; wendu = wendu << 8; wendu = myByte[8]; double wendu1 = wendu; wendu1 = wendu1 / 10; sw.Write("温度:" wendu1.ToString()); int shidu; shidu = myByte[9]; shidu = shidu << 8; shidu = myByte[10]; double shidu1 = shidu; shidu1 = shidu1 / 10; sw.Write("湿度" shidu1.ToString()); sw.WriteLine(); sw.Flush(); //关闭流 } private void label6_Click(object sender, EventArgs e) //保存数据,其实就是保存接收区的内容 { SaveFileDialog sfDialog = new SaveFileDialog(); sfDialog.Filter = "TEXT | *.txt"; if (sfDialog.ShowDialog() == DialogResult.OK) { fileName = sfDialog.FileName; fs = new FileStream(fileName, FileMode.Open); fs.Seek(0, SeekOrigin.End); //将文件流指针定位到末尾 sw = new StreamWriter(fs); sw.Write(textWrite.Text); sw.Close(); fs.Close(); } } private void label6_MouseLeave(object sender, EventArgs e) { this.Cursor = Cursors.Arrow; label6.ForeColor = Color.Blue; } private void label7_Click(object sender, EventArgs e) { textBoxRead.Text = ""; } private void label11_Click(object sender, EventArgs e) { textWrite.Text = ""; } private void label7_MouseLeave(object sender, EventArgs e) { this.Cursor = Cursors.Arrow; label7.ForeColor = Color.Blue; } private void label11_MouseLeave(object sender, EventArgs e) { this.Cursor = Cursors.Arrow; label11.ForeColor = Color.Blue; } private void label6_MouseEnter(object sender, EventArgs e) { label6.ForeColor = Color.Red; this.Cursor = Cursors.Hand; } private void label7_MouseEnter(object sender, EventArgs e) { label7.ForeColor = Color.Red; this.Cursor = Cursors.Hand; } private void label11_MouseEnter(object sender, EventArgs e) { label11.ForeColor = Color.Red; this.Cursor = Cursors.Hand; } private void label12_MouseEnter(object sender, EventArgs e) { label12.ForeColor = Color.Red; this.Cursor = Cursors.Hand; } private void label12_MouseLeave(object sender, EventArgs e) { this.Cursor = Cursors.Arrow; label12.ForeColor = Color.Blue; } private void label12_Click(object sender, EventArgs e)//文件载入 { OpenFileDialog sfDialog = new OpenFileDialog(); sfDialog.Filter = "TEXT | *.txt"; if (sfDialog.ShowDialog() == DialogResult.OK) { fileName = sfDialog.FileName; fs = new FileStream(fileName, FileMode.Open); sr = new StreamReader(fs); textWrite.Text = sr.ReadToEnd(); } } private void checkBox1_CheckedChanged(object sender, EventArgs e)//自动换行显示 { if (checkBox1.Checked) line = "\x0d\x0a"; else line = ""; } private void checkBox2_CheckedChanged(object sender, EventArgs e) //显示接收时间 { if (checkBox2.Checked) { line = "\x0d\x0a"; checkBox1.Checked = true; checkBox1.Enabled = false; } else { checkBox1.Enabled = true; } } private void checkBox5_CheckedChanged(object sender, EventArgs e)//启用文件数据源发送 { if(checkBox5.Checked == true) { OpenFileDialog sfDialog = new OpenFileDialog(); sfDialog.Filter = "TEXT | *.txt"; if (sfDialog.ShowDialog() == DialogResult.OK) { fileName = sfDialog.FileName; fs = new FileStream(fileName, FileMode.Open); sr = new StreamReader(fs); textWrite.Text = "发送此文件中的数据\x0d\x0a" fileName; textWrite.ReadOnly = true; } else { checkBox5.Checked = false; } } else { fs.Close(); sr.Close(); textWrite.Text = ""; textWrite.ReadOnly = false; } } private void checkBox7_CheckedChanged(object sender, EventArgs e)//按十六进制发送 { if (checkBox7.Checked && !checkBox5 .Checked)//若同时启用了文件源,则不需要变换 { if(textWrite.Text != "") { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(textWrite.Text); textWrite.Text = ""; foreach(byte b in bytes) { textWrite.Text = Convert.ToString(b, 16) " "; } textWrite.Text = textWrite.Text.ToUpper(); } } } private void checkBox8_CheckedChanged(object sender, EventArgs e)//自动发送 { if (checkBox8.Checked) { int timeSpan; try { timeSpan = Convert.ToInt32(textBox1.Text); } catch (FormatException) { MessageBox.Show("发送周期不合法", "错误"); checkBox8.Checked = false; return; } checkBox6.Checked = false; checkBox6.Enabled = false; timer1.Interval = timeSpan; } } private void timer1_Tick(object sender, EventArgs e) { SerialPortWrite(); } private void button3_Click(object sender, EventArgs e) { countRead = 0; countWrite = 0; } private void checkBox9_CheckedChanged(object sender, EventArgs e)//接收转向文件 { if (checkBox9.Checked) { SaveFileDialog sfDialog = new SaveFileDialog(); sfDialog.Filter = "TEXT | *.txt"; if (sfDialog.ShowDialog() == DialogResult.OK) { fileName = sfDialog.FileName; fs = new FileStream(fileName, FileMode.Open); fs.Seek(0, SeekOrigin.End); //将文件流指针定位到末尾 sw = new StreamWriter(fs); textBoxRead.Text = "接收转向至文件: \x0d\x0a " fileName; label6.Enabled = false; label7.Enabled = false; checkBox4.Enabled = false; } else { checkBox9.Checked = false; } } else { sw.Close(); fs.Close(); textBoxRead.Text = ""; label6.Enabled = true; label7.Enabled = true; checkBox4.Enabled = true; } } } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论