实例介绍
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO.Ports;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
using M_BUSConfig.Properties;
using System.Diagnostics;
using System.Xml;
using System.Text.RegularExpressions;
namespace M_BUSConfig
{
public partial class Form1 : Form
{
private byte[] bt = new byte[3846];
int ByteLen = 0;
public Form1()
{
InitializeComponent();
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy-MM-dd HH:mm:ss";
dateTimePicker1.ShowUpDown = true;
//dateTimePicker1.Value = Convert.ToDateTime("2016-01-02 03:04:05");
}
public byte[] GetData(int m_Value)
{
byte[] bt = BitConverter.GetBytes(m_Value);
return bt;
}
private void Init()
{
radioButton1.Checked = true;
progressBar1.Value = 0;
progressBar1.Maximum = 100;
progressBar1.Visible = true;
groupBox9.Enabled = false;
button6.Enabled = true;
button6.Update();
}
/// <summary>
/// 数字正则表达式
/// </summary>
/// <param name="txt"></param>
/// <returns></returns>
public void Data_YZ(TextBox txt, int mylen)
{
string pattern = @"^[0-9]*$";
Match m = Regex.Match(txt.Text, pattern);
//匹配正则表达式
if (!m.Success)//输入的不是数字
{
MessageBox.Show(this, "请输入数字!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
txt.Clear();
return;
}
if (Convert.ToInt32(txt.Text.Trim()) > mylen)
{
MessageBox.Show(this, "数据有效长度不能超过" mylen.ToString() "!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
txt.Clear();
return;
}
}
#region 窗体基本事件
/// <summary>
/// 窗体加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
GetComList();
//集中器配置
Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 退出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(0);
}
/// <summary>
/// 打开或关闭串口
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerialPort_Click(object sender, EventArgs e)
{
if (btnSerialPort.Text.Trim() == "打开串口")
{
try
{
Init();
serialPort1.Dispose();
serialPort1.PortName = CBserialport.Text.Trim();
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.Open();
tabControl1.Enabled = true;
CBserialport.Enabled = false;
btnSerialPort.Text = "关闭串口";
statusBar1.Panels[1].Text = "串口打开";
btnSerialPort.BackColor = System.Drawing.Color.Green;
}
catch
{
MessageBox.Show(this, "串口打开失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
try
{
serialPort1.Close();
tabControl1.Enabled = false;
CBserialport.Enabled = true;
btnSerialPort.Text = "打开串口";
statusBar1.Panels[1].Text = "串口关闭";
btnSerialPort.BackColor = System.Drawing.Color.Red;
}
catch
{
MessageBox.Show(this, "串口关闭失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
/// <summary>
/// 帮助
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
Form4 F4 = new Form4();
F4.ShowDialog();
}
private void 打开LOGToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = System.IO.Directory.GetCurrentDirectory();
path = "\\Log";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = "\\";
System.Diagnostics.Process.Start("explorer.exe", path);
}
private void txtSPZQ_TextChanged(object sender, EventArgs e)
{
if (txtSPZQ.Text.Length > 0)
{
Data_YZ(txtSPZQ, 240);
}
}
private void txtFSZQ_TextChanged(object sender, EventArgs e)
{
if (txtFSZQ.Text.Length > 0)
{
Data_YZ(txtFSZQ, 240);
}
}
private void txtID_TextChanged(object sender, EventArgs e)
{
if (txtID.Text.Length > 0)
{
Data_YZ(txtID, 64000);
}
//if (Convert.ToInt32(txtID) % 256 == 253)
//{
// MessageBox.Show(this, "数据低位不能是0xFD!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
}
#endregion
#region 自定义方法
/// <summary>
/// 判断是否16进制
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
private bool CheckJKMBus16(string hex)
{
bool IsHex = true;
if (hex.Length == 2)
{
for (int i = 0; i < hex.Length; i )
{
if (hex[i] != ' ')
{
int asc = (byte)hex[i];
if ((asc < 48) || ((asc > 57) && (asc < 65)) || ((asc > 70) && (asc < 97)) || (asc > 102))
{
IsHex = false;
}
}
else
{
IsHex = false;
}
}
}
else
{
IsHex = false;
}
return IsHex;
}
/// <summary>
/// 判断是否16进制
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
private bool CheckMRMBus16(string hex)
{
bool IsHex = true;
if (hex.Length > 0)
{
for (int i = 0; i < hex.Length; i )
{
if (hex[i] != ' ')
{
int asc = (byte)hex[i];
if ((asc < 48) || ((asc > 57) && (asc < 65)) || ((asc > 70) && (asc < 97)) || (asc > 102))
{
IsHex = false;
}
}
else
{
IsHex = false;
}
}
}
else
{
IsHex = false;
}
return IsHex;
}
/// <summary>
/// 判断是否BCD码
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
private bool CheckGCBCD(string hex)
{
bool IsHex = true;
if (hex.Length == 14)
{
for (int i = 0; i < hex.Length; i )
{
if (hex[i] != ' ')
{
int asc = (byte)hex[i];
if ((asc < 48) || ((asc > 57)))
{
IsHex = false;
}
}
else
{
IsHex = false;
}
}
}
else
{
IsHex = false;
}
return IsHex;
}
/// <summary>
/// 动态获得本机串口
/// </summary>
private void GetComList()
{
string[] COMPort = SerialPort.GetPortNames();
if (COMPort.Length > 0)
{
CBserialport.Items.Clear();
for (int i = 0; i < COMPort.Length; i )
{
CBserialport.Items.Add(COMPort[i].ToString());
CBserialport.SelectedIndex = 0;
}
}
}
/// <summary>
/// 单表串口数据发送与接收
/// </summary>
/// <param name="bt"></param>
/// <param name="start"></param>
/// <param name="len"></param>
private void SerialPortSendSingleMBus(byte[] bt, int start, int len)
{
serialPort1.Write(bt, start, len);//开始发送
Thread.Sleep(3000);
//接收
int bytes = serialPort1.BytesToRead;
if (bytes > 0)
{
byte[] combuffer = new byte[bytes];
serialPort1.Read(combuffer, 0, bytes);
}
else
{
MessageBox.Show(this, "返回数据失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// 判断是否BCD码
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
private bool Check16(string hex)
{
bool IsHex = true;
if (hex.Length > 0)
{
for (int i = 0; i < hex.Length; i )
{
if (hex[i] != ' ')
{
int asc = (byte)hex[i];
if ((asc < 48) || ((asc > 57) && (asc < 65)) || ((asc > 70) && (asc < 97)) || (asc > 102))
{
IsHex = false;
}
}
else
{
IsHex = false;
}
}
}
else
{
IsHex = false;
}
return IsHex;
}
#endregion
#region 测温模块参数设置
/// <summary>
/// 读取历史数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
progressBar1.Value = 0;
progressBar1.Maximum = 100;
progressBar1.Visible = true;
groupBox9.Enabled = false;
}
}
/// <summary>
/// 读配置指令
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
{
progressBar1.Value = 0;
progressBar1.Maximum = 100;
progressBar1.Visible = false;
groupBox9.Enabled = true;
txtID.ReadOnly = true;
txtFSZQ.ReadOnly = true;
txtSPZQ.ReadOnly = true;
dateTimePicker1.Enabled = false;
}
}
/// <summary>
/// 写配置指令
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
if (radioButton3.Checked)
{
progressBar1.Value = 0;
progressBar1.Maximum = 100;
progressBar1.Visible = false;
groupBox9.Enabled = true;
txtID.ReadOnly = false;
txtFSZQ.ReadOnly = false;
txtSPZQ.ReadOnly = false;
dateTimePicker1.Enabled = true;
}
}
/// <summary>
/// 发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button6_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)//读历史数据
{
byte[] bt = new byte[6];
bt[0] = 0xFA;
bt[1] = 0x01;
bt[2] = 0;
bt[3] = 0;
bt[4] = 0xFB;
bt[5] = 0xFD;
serialPort1.DiscardInBuffer();
serialPort1.Write(bt, 0, bt.Length);//开始发送
Assistant.RecordLog("发送功能码01指令", Assistant.StrToHex(bt, bt.Length));
Thread.Sleep(3000);
//初始化线程threadTimes并使用自定义方法ThreadRData
Thread threadTimes = new Thread(new ThreadStart(ThreadRData));
threadTimes.Start();
}
else if (radioButton2.Checked)//读配置指令
{
#region
byte[] bt = new byte[6];
bt[0] = 0xFA;
bt[1] = 0x02;
bt[2] = 0;
bt[3] = 0;
bt[4] = 0xFC;
bt[5] = 0xFD;
serialPort1.DiscardInBuffer();
serialPort1.Write(bt, 0, bt.Length);//开始发送
Assistant.RecordLog("发送功能码02指令", Assistant.StrToHex(bt, bt.Length));
Thread.Sleep(2000);
//接收
int bytes = serialPort1.BytesToRead;
if (bytes == 15)
{
byte ChkSum = 0;
byte[] combuffer = new byte[bytes];
serialPort1.Read(combuffer, 0, bytes);
Assistant.RecordLog("接收功能码01指令", Assistant.StrToHex(combuffer, combuffer.Length));
//FA 02 00 09 00 02 1E 00 11 03 08 12 30 83 FD
if (combuffer[0] == 0xFA && combuffer[1] == 0x02 && combuffer[2] == 0x00 && combuffer[3] == 0x09 && combuffer[14] == 0xFD)
{
for (int i = 0; i <= 12; i )
{
ChkSum = combuffer[i];
}
if (combuffer[13] == ChkSum)
{
int index = 4;
txtID.Text = Convert.ToString(combuffer[index] * 256 combuffer[index 1]);
index = 2;
txtSPZQ.Text = Convert.ToString(combuffer[index]);
index = 1;
txtFSZQ.Text = Convert.ToString(combuffer[index]);
index = 1;
string mTime = combuffer[index].ToString();
mTime = "-";
mTime = combuffer[index 1].ToString();
mTime = "-";
mTime = combuffer[index 2].ToString();
mTime = " ";
mTime = combuffer[index 3].ToString();
mTime = ":";
mTime = combuffer[index 4].ToString();
mTime = ":";
mTime = "00";
index = 5;
dateTimePicker1.Value = Convert.ToDateTime(mTime);
}
else
{
MessageBox.Show(this, "求和校验失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show(this, "返回数据校验失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show(this, "返回数据失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
}
else if (radioButton3.Checked)//写配置指令
{
#region
//FA 03 00 0C 00 04 1E 00 11 03 08 12 30 01 01 01 8A FD
byte ChkSum = 0;
byte[] bt = new byte[18];
bt[0] = 0xFA;
bt[1] = 0x03;
bt[2] = 0;
bt[3] = 0x0C;
//ID
bt[4] = (byte)(Convert.ToInt32(txtID.Text) >> 8);
bt[5] = (byte)(Convert.ToInt32(txtID.Text));
//刷屏周期
bt[6] = (byte)(Convert.ToInt32(txtSPZQ.Text));
//发送周期
bt[7] = (byte)(Convert.ToInt32(txtFSZQ.Text));
//时间
bt[8] = (byte)(Convert.ToInt32(dateTimePicker1.Value.Year.ToString().Substring(2, 2)));
bt[9] = (byte)(Convert.ToInt32(dateTimePicker1.Value.Month.ToString()));
bt[10] = (byte)(Convert.ToInt32(dateTimePicker1.Value.Day.ToString()));
bt[11] = (byte)(Convert.ToInt32(dateTimePicker1.Value.Hour.ToString()));
bt[12] = (byte)(Convert.ToInt32(dateTimePicker1.Value.Minute.ToString()));
//清最值温度
if (checkBox1.Checked)
{
bt[13] = 1;
}
//清历史温度
if (checkBox2.Checked)
{
bt[14] = 1;
}
//关机状态
if (checkBox3.Checked)
{
bt[15] = 1;
}
for (int i = 0; i <= 15; i )
{
ChkSum = bt[i];
}
bt[16] = ChkSum;
bt[17] = 0xFD;
serialPort1.DiscardInBuffer();
serialPort1.Write(bt, 0, bt.Length);//开始发送
Assistant.RecordLog("发送功能码03指令", Assistant.StrToHex(bt, bt.Length));
Thread.Sleep(2000);
//接收
int bytes = serialPort1.BytesToRead;
if (bytes == 7)
{
byte[] combuffer = new byte[bytes];
serialPort1.Read(combuffer, 0, bytes);
Assistant.RecordLog("接收功能码03指令", Assistant.StrToHex(combuffer, combuffer.Length));
//FA 03 00 01 55 53 FD注:0x55配置成功,0xAA配置内容错误,超出范围
if (combuffer[0] == 0xFA && combuffer[1] == 0x03 && combuffer[2] == 0x00 && combuffer[3] == 0x01 && combuffer[6] == 0xFD)
{
ChkSum = 0;
for (int i = 0; i <= 4; i )
{
ChkSum = combuffer[i];
}
if (combuffer[5] == ChkSum)
{
if (combuffer[4] == 0x55)
{
MessageBox.Show(this, "配置成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (combuffer[4] == 0xAA)
{
MessageBox.Show(this, "配置内容错误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show(this, "求和校验失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show(this, "返回数据校验失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show(this, "返回数据失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
}
}
#endregion
private void CreatCSV()
{
try
{
if (bt.Length == 3846 && bt[0] == 0xfa && bt[1] == 0x01 && bt[3845] == 0xfd)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//设置文件类型
saveFileDialog1.Filter = "CSV文件|*.CSV";
//设置默认文件类型显示顺序
saveFileDialog1.FilterIndex = 2;
//保存对话框是否记忆上次打开的目录
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.FileName = "历史数据";
string Year1 = DateTime.Now.Year.ToString();
string Month1 = DateTime.Now.Month.ToString();
if (Month1.Length == 1)
{
Month1 = "0" Month1;
}
string Day1 = DateTime.Now.Day.ToString();
if (Day1.Length == 1)
{
Day1 = "0" Day1;
}
string Hour1 = DateTime.Now.Hour.ToString();
if (Hour1.Length == 1)
{
Hour1 = "0" Hour1;
}
string Minute1 = DateTime.Now.Minute.ToString();
if (Minute1.Length == 1)
{
Minute1 = "0" Minute1;
}
string SysDataTime = Year1 Month1 Day1 Hour1 Minute1;
string CSVName = "测温模块历史数据" SysDataTime ".CSV";
FileStream fs = new FileStream(CSVName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
string data = "序号,日期,温度,";
sw.WriteLine(data);
for (int i = 0; i < 960; i )
{
int Hour = bt[i * 4 4] * 256 bt[i * 4 5];
int[] mdate = new int[4];
RTC_Get_Date(Hour, mdate);
string RQ = Convert.ToString(mdate[1] "-" mdate[2] " " mdate[3]);
int zfs = 1;
if ((bt[i * 4 6] & 0x80) == 0x80)
{
zfs = -1;
}
float CWSJ = zfs * (float)((bt[i * 4 6] & 0x7f) * 256 bt[i * 4 7]) / 10;
data = (i 1).ToString();
data = ",";
data = RQ;
data = ",";
data = CWSJ.ToString();
data = ",";
sw.WriteLine(data);
}
sw.Close();
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ThreadRData()
{
bt = new byte[3846];
ByteLen = 0;
progressBar1.Maximum = 20;
progressBar1.Value = 0;
int mTimes = 0;
bool istrue = true;
while (istrue)
{
Thread.Sleep(150);
try
{
int bytes1 = serialPort1.BytesToRead;
if (bytes1 > 0)
{
byte[] combuffer = new byte[bytes1];
serialPort1.Read(combuffer, 0, bytes1);
Assistant.RecordLog("读历史数据", Assistant.StrToHex(combuffer, bytes1));//LOG
for (int i = 0; i < bytes1; i )
{
bt[ByteLen i] = combuffer[i];
}
ByteLen = bytes1;
if (progressBar1.Maximum != 20)
{
progressBar1.Value = 1;
}
}
else
{
mTimes ;
Thread.Sleep(1000);
if (mTimes > 10)
{
istrue = false;
button6.Enabled = true;
progressBar1.Value = 0;
MessageBox.Show(this, "读历史数据失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
if (ByteLen == 3846)
{
CreatCSV();
progressBar1.Value = 20;
MessageBox.Show(this, "读历史数据完毕!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
istrue = false;
button6.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
istrue = false;
button6.Enabled = true;
progressBar1.Value = 0;
}
}
}
int[] mon_table = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
void RTC_Get_Date(int Hour, int[] RTC_Time)
{
int daycnt = 0;
int timecount = 0;
int temp = 0;
int temp1 = 0;
timecount = Hour % 24;//剩余一天的小时数
temp = Hour / 24;//天数
if (daycnt != temp)//超过了一天
{
daycnt = temp;
RTC_Time[0] = temp1;//得到年份
temp1 = 0;//从设置得到月份
while (temp >= 28)//超过一个月
{
if (temp >= mon_table[temp1])
{
temp -= mon_table[temp1];
}
else
{
break;
}
temp1 ;
}
RTC_Time[1] = temp1 1; //得到月份
RTC_Time[2] = temp 1; //得到日期
}
else
{
RTC_Time[1] = 1; //得到月份
RTC_Time[2] = 1; //得到日期
}
temp = timecount; //得到秒钟数
RTC_Time[3] = timecount; //得到小时
}
}
}
标签: 串口与测温模块通信
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论