实例介绍
【实例简介】
介绍利用c#的serialport组件来和设备串口进行通讯的例子
【实例截图】
【核心代码】
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Text; using System.IO; using System.Diagnostics; using System.Threading; namespace Serial_Demo { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.RichTextBox rtfTerminal; private System.Windows.Forms.Button btn_dial; private AxMSCommLib.AxMSComm com; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txt_phoneno; private System.Windows.Forms.Button btn_disconnect; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txt_sendmessage; private System.Windows.Forms.Button btn_sendmessage; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label Message; private System.Windows.Forms.Panel panel1; public Form1() { InitializeComponent(); // Initialize the COM Port control InitComPort(); } private void InitComPort() { // Set the com port to be 1 com.CommPort = 1; // This port is already open, then close. if (com.PortOpen) com.PortOpen=false; // Trigger the OnComm event whenever data is received com.RThreshold = 1; // Set the port to 9600 baud, no parity bit, 8 data bits, 1 stop bit (all standard) com.Settings = "9600,n,8,1"; // Force the DTR line high, used sometimes to hang up modems //com.DTREnable = true; com.RTSEnable=true; // No handshaking is used com.Handshaking = MSCommLib.HandshakeConstants.comNone; // Use this line instead for byte array input, best for most communications com.InputMode = MSCommLib.InputModeConstants.comInputModeText; // Read the entire waiting data when com.Input is used com.InputLen = 0; // Don't discard nulls, 0x00 is a useful byte com.NullDiscard = false; // Attach the event handler com.OnComm = new System.EventHandler(this.OnComm); com.PortOpen = true; } private void OnComm(object sender, EventArgs e) // MSCommLib OnComm Event Handler { // Wait for Some mili-seconds then process // The response. Thread.Sleep(200); if (com.InBufferCount > 0) { try { // If you want to receive data in Binary mode // Remove below 2 comment lines // And comment lines for Process response in // Text mode. //byte[] b1=(byte[])com.Input; //ProcessResponseBinary(b1); // Process response in Text mode. string response=(string)com.Input; ProcessResponseText(response); } catch(Exception ex) { MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK,MessageBoxIcon.Information); } } } // If you receive binary data as response. private void ProcessResponseBinary(byte[] response) { for(int i=0; i< response.Length; i ) { rtfTerminal.AppendText(response[i].ToString() " "); } rtfTerminal.AppendText("\n"); } // If you receive Text data as response private void ProcessResponseText(string input) { // Send incoming data to a Rich Text Box if( input.Trim().Equals("RING")) { Message.Text="Ring..."; } else if( input.Trim().Equals("CONNECT 9600")) { MessageBox.Show(input.Trim(), this.Text, MessageBoxButtons.OK,MessageBoxIcon.Information); } else { MessageBox.Show(input.Trim(), this.Text, MessageBoxButtons.OK,MessageBoxIcon.Information); Message.Text=input.Trim(); } // Append output response to RichText Box rtfTerminal.AppendText(input "\n"); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.rtfTerminal = new System.Windows.Forms.RichTextBox(); this.btn_dial = new System.Windows.Forms.Button(); this.com = new AxMSCommLib.AxMSComm(); this.label6 = new System.Windows.Forms.Label(); this.txt_phoneno = new System.Windows.Forms.TextBox(); this.btn_disconnect = new System.Windows.Forms.Button(); this.Message = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.txt_sendmessage = new System.Windows.Forms.TextBox(); this.btn_sendmessage = new System.Windows.Forms.Button(); this.label8 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); ((System.ComponentModel.ISupportInitialize)(this.com)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // rtfTerminal // this.rtfTerminal.Location = new System.Drawing.Point(0, 136); this.rtfTerminal.Name = "rtfTerminal"; this.rtfTerminal.Size = new System.Drawing.Size(280, 112); this.rtfTerminal.TabIndex = 1; this.rtfTerminal.Text = ""; // // btn_dial // this.btn_dial.Location = new System.Drawing.Point(8, 72); this.btn_dial.Name = "btn_dial"; this.btn_dial.TabIndex = 8; this.btn_dial.Text = "Dial"; this.btn_dial.Click = new System.EventHandler(this.btn_dial_Click); // // com // this.com.Enabled = true; this.com.Location = new System.Drawing.Point(160, 104); this.com.Name = "com"; this.com.Size = new System.Drawing.Size(38, 38); this.com.TabIndex = 14; // // label6 // this.label6.BackColor = System.Drawing.Color.Transparent; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label6.ForeColor = System.Drawing.SystemColors.Highlight; this.label6.Location = new System.Drawing.Point(8, 8); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(64, 23); this.label6.TabIndex = 15; this.label6.Text = "GSM No:"; // // txt_phoneno // this.txt_phoneno.Location = new System.Drawing.Point(88, 8); this.txt_phoneno.Name = "txt_phoneno"; this.txt_phoneno.Size = new System.Drawing.Size(168, 20); this.txt_phoneno.TabIndex = 16; this.txt_phoneno.Text = ""; // // btn_disconnect // this.btn_disconnect.Location = new System.Drawing.Point(184, 72); this.btn_disconnect.Name = "btn_disconnect"; this.btn_disconnect.TabIndex = 17; this.btn_disconnect.Text = "Disconnect"; this.btn_disconnect.Click = new System.EventHandler(this.btn_disconnect_Click); // // Message // this.Message.BackColor = System.Drawing.Color.Transparent; this.Message.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Message.ForeColor = System.Drawing.Color.MidnightBlue; this.Message.Location = new System.Drawing.Point(0, 248); this.Message.Name = "Message"; this.Message.Size = new System.Drawing.Size(280, 23); this.Message.TabIndex = 18; // // label7 // this.label7.BackColor = System.Drawing.Color.Transparent; this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label7.ForeColor = System.Drawing.SystemColors.Highlight; this.label7.Location = new System.Drawing.Point(8, 40); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(72, 32); this.label7.TabIndex = 19; this.label7.Text = "Message:"; // // txt_sendmessage // this.txt_sendmessage.Location = new System.Drawing.Point(88, 40); this.txt_sendmessage.Name = "txt_sendmessage"; this.txt_sendmessage.Size = new System.Drawing.Size(168, 20); this.txt_sendmessage.TabIndex = 20; this.txt_sendmessage.Text = ""; // // btn_sendmessage // this.btn_sendmessage.Location = new System.Drawing.Point(96, 72); this.btn_sendmessage.Name = "btn_sendmessage"; this.btn_sendmessage.TabIndex = 21; this.btn_sendmessage.Text = "Send"; this.btn_sendmessage.Click = new System.EventHandler(this.btn_sendmessage_Click); // // label8 // this.label8.BackColor = System.Drawing.Color.Transparent; this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label8.ForeColor = System.Drawing.SystemColors.Highlight; this.label8.Location = new System.Drawing.Point(0, 112); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(160, 24); this.label8.TabIndex = 22; this.label8.Text = "Received messages:"; // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.btn_dial); this.panel1.Controls.Add(this.btn_disconnect); this.panel1.Controls.Add(this.txt_phoneno); this.panel1.Controls.Add(this.label6); this.panel1.Controls.Add(this.label7); this.panel1.Controls.Add(this.txt_sendmessage); this.panel1.Controls.Add(this.btn_sendmessage); this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(280, 104); this.panel1.TabIndex = 23; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(280, 269); this.Controls.Add(this.panel1); this.Controls.Add(this.label8); this.Controls.Add(this.rtfTerminal); this.Controls.Add(this.com); this.Controls.Add(this.Message); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Serial Demo"; ((System.ComponentModel.ISupportInitialize)(this.com)).EndInit(); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void btn_dial_Click(object sender, System.EventArgs e) { if( txt_phoneno.Text.Trim().Equals("")) { MessageBox.Show("Please Specify Phone Number", this.Text, MessageBoxButtons.OK,MessageBoxIcon.Information); txt_phoneno.Focus(); return; } if(! com.PortOpen ) com.PortOpen=true; // GSM Command Dial a Modem // ATD<phonenumber>\n string gsm_command="ATD"; string phone_number=txt_phoneno.Text.Trim(); string command1=gsm_command phone_number "\n"; byte[] command_to_dial=System.Text.ASCIIEncoding.Default.GetBytes(command1); com.Output=command_to_dial; Message.Text="Dialing..."; } private void btn_disconnect_Click(object sender, System.EventArgs e) { // If com port is open then close it // to disconnect connection if( com.PortOpen ) { com.PortOpen=false; MessageBox.Show("Disconnected...", this.Text, MessageBoxButtons.OK,MessageBoxIcon.Information); Message.Text=""; rtfTerminal.Text=""; } } private void btn_sendmessage_Click(object sender, System.EventArgs e) { string msg=""; if( txt_sendmessage.Text.Trim().Equals("")) { MessageBox.Show("Please Specify Command", this.Text, MessageBoxButtons.OK,MessageBoxIcon.Information); txt_sendmessage.Focus(); return; } if(! com.PortOpen ) com.PortOpen=true; // To send text messages // If you are using GSM Modem and you want to send // Command then use GetByes of your message // To send Byte data from com port msg=txt_sendmessage.Text.Trim() "\n"; com.Output = System.Text.ASCIIEncoding.Default.GetBytes(msg); // Or Else If systems are connected with Serial // Cable, Output simple text directly // com.Output= txt_sendmessage.Text; Message.Text="Message Sent...."; } } }
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论