C# 串口开发 SerialPort
首先申明下:这个名字对不对我也不太清楚,我是第一次一个人在开发,之前是基于webfrom开发。
哎!无奈为了生活搞起了winfrom,上几个月一家公司,名字我就不说了 也是winform 他对我很好!也很用心的教我,使我对oracle的数据库脚本编程进一步熟悉了, xxx wcf。可是当时我不喜欢winfrom的原因,后来辞职了。现在想想 还是一样又搞 了winfrom ,生活让你变的成熟,理性。感谢你!大勇!
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; using System.Collections; using System.IO.Ports; using System.Threading; using System.Diagnostics; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using System.Reflection; namespace WC_Task { public partial class Form1 : Form { #region 自定义变量 SerialPort spt = new SerialPort(); public string strCOMPort = "COM4";//串口 public int intCOMBaud = 9600;//波特率 string orgStr = ""; string[] getLastNum;//发送数据集合 bool FileExists_timer;//文件存在后是否执行定时器 bool FileExists;//文件是否存在 Thread StarThread; //string filename = @"\ResidentFlash\mainmenuOne.exe"; string filename = @"\ResidentFlash\yjt\yjt.exe";//外部程序目标 string fileNamePath = @"\SDMMC\DriverInfo.dat"; #region 任务栏隐藏 [DllImport("coredll.dll")] public static extern int ShowWindow(int hwnd, int nCmdShow); [DllImport("coredll.dll")] private static extern int FindWindow(string lpClassName, string lpWindowName); #endregion #endregion #region 自定义方法 /// <summary> /// 打开串口 /// </summary> private void OpenSpt() { if (spt.IsOpen) { spt.Close(); } else { spt.PortName = strCOMPort; spt.BaudRate = intCOMBaud; spt.NewLine = "\r\n"; spt.Open(); } } /// <summary> /// 读取文件 /// </summary> /// <param name="filePath">文件路劲</param> public bool FileRead(string filePath) { FileInfo fio = new FileInfo(filePath); byte[] data = new byte[3]; if (!fio.Exists) { return false; } else { using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default)) { string info = sr.ReadLine(); if (!string.IsNullOrEmpty(info)) { data = Convert.FromBase64String(info); orgStr = Encoding.Default.GetString(data, 0, data.Length); if (data.Length > 0) { getLastNum = orgStr.Split(',');//字符分割 LblName_info.Text = getLastNum[0]; LalAge_info.Text = getLastNum[1]; LblSex_info.Text = getLastNum[2]; LblNumber_info.Text = getLastNum[3]; } return true; } else { return false; } } } } /// <summary> /// 发送数据"0F, A5, 31, 34, 23, 23, 23, 23, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, AD, F0"; /// </summary> public void SendSpt(string getLastNum) { byte[] Number_sp = System.Text.Encoding.ASCII.GetBytes(getLastNum); byte[] Number = new byte[26]; Number[0] = 0x0F; Number[1] = 0xA5; Number[2] = 0x31; Number[3] = 0x34; for (int i = 4; i < getLastNum.Length; i++) { Number[i] = Number_sp[i]; } for (int i = 1; i <=23; i++) { Number[24] = (byte)((byte)Number[24] ^ (byte)Number[i]); } Number[25] = 0xF0; if (spt.IsOpen) { try { for (int i = 0; i < 2; i++) { spt.Write(Number, 0, Number.Length); Thread.Sleep(2000); } } catch (Exception ex) { throw ex; } } string dt = DateTime.Now.ToString(); using (StreamWriter wirte=new StreamWriter (@"\ResidentFlash\SendData.txt",true)) { string wirteData = ""; foreach (byte var in Number) { wirteData += var.ToString(); } wirte.WriteLine(wirteData + "---Systime---" + dt); } } /// <summary> /// 打开外部文件 /// </summary> public void OpenOutFile() { ThreadWithState tws = new ThreadWithState(filename, null); StarThread = new Thread(new ThreadStart(tws.ThreadProc)); StarThread.IsBackground = true; StarThread.Start(); } /// <summary> /// 申明委托类(定义参数是方便线程实例化传参数) /// </summary> public class ThreadWithState { private string fileName;//文件路劲 private string t_sp; public ThreadWithState(string fileName, string t_sp) { this.fileName = fileName; this.t_sp = t_sp; } public void ThreadProc() { Process.Start(fileName, null); } } #endregion public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { FileExists = FileRead(fileNamePath); if (FileExists)//文件存在,定时器执行打开串口主动发送数据 { FileExists_timer = true; timer_task.Enabled = true; timer_Send.Enabled = true; } else //文件不存在或者没有数据 { this.Width = 0; this.Height = 0; OpenOutFile(); this.Close(); } int hTaskBarWnd = FindWindow("HHTaskBar", null); ShowWindow(hTaskBarWnd, 0); } /// <summary> /// 文件存在定时器30秒后打开外部程序 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer_task_Tick(object sender, EventArgs e) { if (FileExists_timer) { if (spt.IsOpen) { spt.Close(); } timer_task.Enabled = false; OpenOutFile(); Thread.Sleep(1000); this.Close(); } } /// <summary> /// 打开串口,发送数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer_Send_Tick(object sender, EventArgs e) { if (FileExists) { try { OpenSpt(); SendSpt(getLastNum[3]); timer_Send.Enabled = false; } catch (Exception ex) { throw ex; } } } } }
协议:
本协议的通讯方式 标准RS232通讯;波特率:9600;通讯格式:8N1,8位数据,无奇偶校验位,有1位停止位 通信基本格式: 起始符 信息类型 信息长度 信息内容 校验 结束符 各部分定义如下: 内容 定义 起始符 0F,一个字节,十六进制码 信息类型 一个字节,十六进制码(0F,F0,FF等保留码不用) 信息长度 为2个字节,ASCII码(0~9,A~F,最大长度为256) 信息内容 一组十六进制码,最大长度256 校验 一个字节,十六进制码,是自信息类型起至对象号止所有码的异或和。 结束符 F0,一个字节,十六进制码 (为了保证可靠性,车机下发的结束符为F0 FF)
微软的msdn真的不错 呵呵