当前位置:文档之家› C#结合串口通信类实现串口通信源代码

C#结合串口通信类实现串口通信源代码

C#结合串口通信类实现串口通信源代码
C#结合串口通信类实现串口通信源代码

mycom是串口通信类,在本blog前一篇中有完整代码。(C#串口通信编程类(修改版)) 下面是串口通讯测试程序的源代码,将mycom类放在此项目中

可以实现简单的串口通信,希望读者能通过这个程序对串口通信过程有一个初步的了解:

usingSystem;

usingSystem.Drawing;

usingSystem.Collections;

https://www.doczj.com/doc/889348395.html,ponentModel;

usingSystem.Windows.Forms;

usingSystem.Data;

usingSystem.Threading;

namespaceBusApp

{

///

///Form1的摘要说明。

///

publicclassForm1:System.Windows.Forms.Form

{

https://www.doczj.com/doc/889348395.html,bellabel1;

https://www.doczj.com/doc/889348395.html,bellabel2;

privateSystem.Windows.Forms.Buttonbutton1;

privateSystem.Windows.Forms.GroupBoxgroupBox1;

https://www.doczj.com/doc/889348395.html,bellabel3;

https://www.doczj.com/doc/889348395.html,bellabel4;

https://www.doczj.com/doc/889348395.html,bellabel5;

https://www.doczj.com/doc/889348395.html,bellabel6;

privateSystem.Windows.Forms.Buttonbutton2;

privateSystem.Windows.Forms.Buttonbutton3;

privateSystem.Windows.Forms.Buttonbutton4;

privateSystem.Windows.Forms.TextBoxtextBox8;

https://www.doczj.com/doc/889348395.html,bellabel7;

publicintiPort=1;//1,2,3,4

publicintiRate=9600;//1200,2400,4800,9600

publicbytebSize=8;//8bits

publicbytebParity=0;//0-4=no,odd,even,mark,space

publicbytebStopBits=1;//0,1,2=1,1.5,2

publicintiTimeout=1000;

publicmycommycom1=newmycom();

publicbyte[]recb;

privateSystem.Windows.Forms.TextBoxmsg;

privateSystem.Windows.Forms.TextBoxt_port;

privateSystem.Windows.Forms.TextBoxt_rate;

privateSystem.Windows.Forms.TextBoxt_bytesize;

privateSystem.Windows.Forms.TextBoxt_stopbyte;

privateSystem.Windows.Forms.TextBoxt_parity; privateSystem.Windows.Forms.TextBoxt_send; privateSystem.Windows.Forms.Buttonbutton5;//readTimeOut ///

///必需的设计器变量。

///

https://www.doczj.com/doc/889348395.html,ponentModel.Containercomponents=null; publicForm1()

{

InitializeComponent();

}

///

///清理所有正在使用的资源。

///

protectedoverridevoidDispose(booldisposing)

{

if(disposing)

{

if(components!=null)

{

components.Dispose();

}

}

base.Dispose(disposing);

}

#regionWindows窗体设计器生成的代码

///

///设计器支持所需的方法-不要使用代码编辑器修改

///此方法的内容。

///

privatevoidInitializeComponent()

{

this.msg=newSystem.Windows.Forms.TextBox();

https://www.doczj.com/doc/889348395.html,bel1=https://www.doczj.com/doc/889348395.html,bel();

https://www.doczj.com/doc/889348395.html,bel2=https://www.doczj.com/doc/889348395.html,bel();

this.t_send=newSystem.Windows.Forms.TextBox();

this.button1=newSystem.Windows.Forms.Button();

this.groupBox1=newSystem.Windows.Forms.GroupBox(); this.button2=newSystem.Windows.Forms.Button();

this.t_port=newSystem.Windows.Forms.TextBox();

https://www.doczj.com/doc/889348395.html,bel3=https://www.doczj.com/doc/889348395.html,bel();

this.t_rate=newSystem.Windows.Forms.TextBox();

https://www.doczj.com/doc/889348395.html,bel4=https://www.doczj.com/doc/889348395.html,bel();

this.t_bytesize=newSystem.Windows.Forms.TextBox();

https://www.doczj.com/doc/889348395.html,bel5=https://www.doczj.com/doc/889348395.html,bel();

this.t_stopbyte=newSystem.Windows.Forms.TextBox();

https://www.doczj.com/doc/889348395.html,bel6=https://www.doczj.com/doc/889348395.html,bel();

this.t_parity=newSystem.Windows.Forms.TextBox();

this.button3=newSystem.Windows.Forms.Button();

this.button4=newSystem.Windows.Forms.Button();

this.textBox8=newSystem.Windows.Forms.TextBox();

https://www.doczj.com/doc/889348395.html,bel7=https://www.doczj.com/doc/889348395.html,bel();

this.button5=newSystem.Windows.Forms.Button();

this.groupBox1.SuspendLayout();

this.SuspendLayout();

//

//msg

//

this.msg.ForeColor=System.Drawing.Color.Green;

this.msg.Location=newSystem.Drawing.Point(0,0);

this.msg.Multiline=true;

https://www.doczj.com/doc/889348395.html,="msg";

this.msg.ScrollBars=System.Windows.Forms.ScrollBars.Vertical;

this.msg.Size=newSystem.Drawing.Size(512,264);

this.msg.TabIndex=0;

this.msg.Text="";

//

//label1

//

https://www.doczj.com/doc/889348395.html,bel1.Location=newSystem.Drawing.Point(16,24);

https://www.doczj.com/doc/889348395.html,="label1";

https://www.doczj.com/doc/889348395.html,bel1.Size=newSystem.Drawing.Size(56,16);

https://www.doczj.com/doc/889348395.html,bel1.TabIndex=1;

https://www.doczj.com/doc/889348395.html,bel1.Text="串口号:";

//

//label2

//

https://www.doczj.com/doc/889348395.html,bel2.ForeColor=System.Drawing.Color.FromArgb(((System.Byte)(192)),((S ystem.Byte)(64)),((System.Byte)(0)));

https://www.doczj.com/doc/889348395.html,bel2.Location=newSystem.Drawing.Point(8,280);

https://www.doczj.com/doc/889348395.html,="label2";

https://www.doczj.com/doc/889348395.html,bel2.Size=newSystem.Drawing.Size(80,16);

https://www.doczj.com/doc/889348395.html,bel2.TabIndex=1;

https://www.doczj.com/doc/889348395.html,bel2.Text="设置数据包:";

//

//t_send

//

this.t_send.BorderStyle=System.Windows.Forms.BorderStyle.FixedSingle;

this.t_send.ForeColor=System.Drawing.Color.FromArgb(((System.Byte)(255)),(( System.Byte)(128)),((System.Byte)(0)));

this.t_send.Location=newSystem.Drawing.Point(80,272);

this.t_https://www.doczj.com/doc/889348395.html,="t_send";

this.t_send.Size=newSystem.Drawing.Size(344,21);

this.t_send.TabIndex=2;

this.t_send.Text="";

//

//button1

//

this.button1.Location=newSystem.Drawing.Point(432,272);

https://www.doczj.com/doc/889348395.html,="button1";

this.button1.Size=newSystem.Drawing.Size(40,23);

this.button1.TabIndex=3;

this.button1.Text="发送";

this.button1.Click+=newSystem.EventHandler(this.button1_Click);

//

//groupBox1

//

this.groupBox1.Controls.Add(this.button2);

this.groupBox1.Controls.Add(this.t_port);

this.groupBox1.Controls.Add(https://www.doczj.com/doc/889348395.html,bel1);

this.groupBox1.Controls.Add(https://www.doczj.com/doc/889348395.html,bel3);

this.groupBox1.Controls.Add(this.t_rate);

this.groupBox1.Controls.Add(https://www.doczj.com/doc/889348395.html,bel4);

this.groupBox1.Controls.Add(this.t_bytesize);

this.groupBox1.Controls.Add(https://www.doczj.com/doc/889348395.html,bel5);

this.groupBox1.Controls.Add(this.t_stopbyte);

this.groupBox1.Controls.Add(https://www.doczj.com/doc/889348395.html,bel6);

this.groupBox1.Controls.Add(this.t_parity);

this.groupBox1.ForeColor=System.Drawing.Color.FromArgb(((System.Byte)(192) ),((System.Byte)(64)),((System.Byte)(0)));

this.groupBox1.Location=newSystem.Drawing.Point(8,304);

https://www.doczj.com/doc/889348395.html,="groupBox1";

this.groupBox1.Size=newSystem.Drawing.Size(176,216);

this.groupBox1.TabIndex=4;

this.groupBox1.TabStop=false;

this.groupBox1.Text="参数设置";

//

//button2

//

this.button2.FlatStyle=System.Windows.Forms.FlatStyle.Popup;

this.button2.Location=newSystem.Drawing.Point(80,184);

https://www.doczj.com/doc/889348395.html,="button2";

this.button2.Text="应用设置";

this.button2.Click+=newSystem.EventHandler(this.button2_Click);

//

//t_port

//

this.t_port.BorderStyle=System.Windows.Forms.BorderStyle.FixedSingle; this.t_port.Location=newSystem.Drawing.Point(80,16);

this.t_https://www.doczj.com/doc/889348395.html,="t_port";

this.t_port.Size=newSystem.Drawing.Size(80,21);

this.t_port.TabIndex=2;

this.t_port.Text="1";

//

//label3

//

https://www.doczj.com/doc/889348395.html,bel3.Location=newSystem.Drawing.Point(16,58);

https://www.doczj.com/doc/889348395.html,="label3";

https://www.doczj.com/doc/889348395.html,bel3.Size=newSystem.Drawing.Size(56,16);

https://www.doczj.com/doc/889348395.html,bel3.TabIndex=1;

https://www.doczj.com/doc/889348395.html,bel3.Text="波特率:";

//

//t_rate

//

this.t_rate.BorderStyle=System.Windows.Forms.BorderStyle.FixedSingle; this.t_rate.Location=newSystem.Drawing.Point(80,50);

this.t_https://www.doczj.com/doc/889348395.html,="t_rate";

this.t_rate.Size=newSystem.Drawing.Size(80,21);

this.t_rate.TabIndex=2;

this.t_rate.Text="9600";

//

//label4

//

https://www.doczj.com/doc/889348395.html,bel4.Location=newSystem.Drawing.Point(16,92);

https://www.doczj.com/doc/889348395.html,="label4";

https://www.doczj.com/doc/889348395.html,bel4.Size=newSystem.Drawing.Size(56,16);

https://www.doczj.com/doc/889348395.html,bel4.TabIndex=1;

https://www.doczj.com/doc/889348395.html,bel4.Text="数据位:";

//

//t_bytesize

//

this.t_bytesize.BorderStyle=System.Windows.Forms.BorderStyle.FixedSingle; this.t_bytesize.Location=newSystem.Drawing.Point(80,84);

this.t_https://www.doczj.com/doc/889348395.html,="t_bytesize";

this.t_bytesize.Size=newSystem.Drawing.Size(80,21);

this.t_bytesize.Text="8";

//

//label5

//

https://www.doczj.com/doc/889348395.html,bel5.Location=newSystem.Drawing.Point(16,126);

https://www.doczj.com/doc/889348395.html,="label5";

https://www.doczj.com/doc/889348395.html,bel5.Size=newSystem.Drawing.Size(56,16);

https://www.doczj.com/doc/889348395.html,bel5.TabIndex=1;

https://www.doczj.com/doc/889348395.html,bel5.Text="停止位:";

//

//t_stopbyte

//

this.t_stopbyte.BorderStyle=System.Windows.Forms.BorderStyle.FixedSingle; this.t_stopbyte.Location=newSystem.Drawing.Point(80,118);

this.t_https://www.doczj.com/doc/889348395.html,="t_stopbyte";

this.t_stopbyte.Size=newSystem.Drawing.Size(80,21);

this.t_stopbyte.TabIndex=2;

this.t_stopbyte.Text="1";

//

//label6

//

https://www.doczj.com/doc/889348395.html,bel6.Location=newSystem.Drawing.Point(16,160);

https://www.doczj.com/doc/889348395.html,="label6";

https://www.doczj.com/doc/889348395.html,bel6.Size=newSystem.Drawing.Size(56,16);

https://www.doczj.com/doc/889348395.html,bel6.TabIndex=1;

https://www.doczj.com/doc/889348395.html,bel6.Text="校验位:";

//

//t_parity

//

this.t_parity.BorderStyle=System.Windows.Forms.BorderStyle.FixedSingle; this.t_parity.Enabled=false;

this.t_parity.Location=newSystem.Drawing.Point(80,152);

this.t_https://www.doczj.com/doc/889348395.html,="t_parity";

this.t_parity.Size=newSystem.Drawing.Size(80,21);

this.t_parity.TabIndex=2;

this.t_parity.Text="0";

//

//button3

//

this.button3.Location=newSystem.Drawing.Point(472,272);

https://www.doczj.com/doc/889348395.html,="button3";

this.button3.Size=newSystem.Drawing.Size(40,23);

this.button3.TabIndex=3;

this.button3.Text="清空";

this.button3.Click+=newSystem.EventHandler(this.button3_Click);

//

//button4

//

this.button4.FlatStyle=System.Windows.Forms.FlatStyle.Popup;

this.button4.Location=newSystem.Drawing.Point(432,312);

https://www.doczj.com/doc/889348395.html,="button4";

this.button4.Size=newSystem.Drawing.Size(72,23);

this.button4.TabIndex=6;

this.button4.Text="初始化";

//

//textBox8

//

this.textBox8.BorderStyle=System.Windows.Forms.BorderStyle.FixedSingle; this.textBox8.ForeColor=System.Drawing.Color.FromArgb(((System.Byte)(255)),( (System.Byte)(128)),((System.Byte)(0)));

this.textBox8.Location=newSystem.Drawing.Point(288,312);

https://www.doczj.com/doc/889348395.html,="textBox8";

this.textBox8.Size=newSystem.Drawing.Size(136,21);

this.textBox8.TabIndex=7;

this.textBox8.Text="";

//

//label7

//

https://www.doczj.com/doc/889348395.html,bel7.Location=newSystem.Drawing.Point(200,320);

https://www.doczj.com/doc/889348395.html,="label7";

https://www.doczj.com/doc/889348395.html,bel7.Size=newSystem.Drawing.Size(100,16);

https://www.doczj.com/doc/889348395.html,bel7.TabIndex=8;

https://www.doczj.com/doc/889348395.html,bel7.Text="设置本机地址:";

//

//button5

//

this.button5.FlatStyle=System.Windows.Forms.FlatStyle.Popup;

this.button5.Location=newSystem.Drawing.Point(440,504);

https://www.doczj.com/doc/889348395.html,="button5";

this.button5.Size=newSystem.Drawing.Size(64,23);

this.button5.TabIndex=9;

this.button5.Text="关闭串口";

this.button5.Click+=newSystem.EventHandler(this.button5_Click);

//

//Form1

//

this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);

this.ClientSize=newSystem.Drawing.Size(512,533);

this.Controls.Add(this.button5);

this.Controls.Add(this.textBox8);

this.Controls.Add(https://www.doczj.com/doc/889348395.html,bel7);

this.Controls.Add(this.button4);

this.Controls.Add(this.groupBox1);

this.Controls.Add(this.button1);

this.Controls.Add(this.t_send);

this.Controls.Add(this.msg);

this.Controls.Add(https://www.doczj.com/doc/889348395.html,bel2);

this.Controls.Add(this.button3);

https://www.doczj.com/doc/889348395.html,="Form1";

this.Text="串口通讯(小y设计)";

this.Closing+=https://www.doczj.com/doc/889348395.html,ponentModel.CancelEventHandler(this.Form1_Clos ing);

this.Load+=newSystem.EventHandler(this.Form1_Load);

this.groupBox1.ResumeLayout(false);

this.ResumeLayout(false);

}

#endregion

///

///应用程序的主入口点。

///

[STAThread]

staticvoidMain()

{

Application.Run(newForm1());

}

//程序开启,串口初始化

privatevoidForm1_Load(objectsender,System.EventArgse)

{

mycom1.PortNum=iPort;

mycom1.BaudRate=iRate;

mycom1.ByteSize=bSize;

mycom1.Parity=bParity;

mycom1.StopBits=bStopBits;

mycom1.ReadTimeout=iTimeout;

if(this.OpenCom())

msg.AppendText("串口初始化成功……\r\n");

else

msg.AppendText("串口初始化失败!\r\n");

}

//显示包信息

publicstringdis_package(byte[]reb)

{

stringtemp="";

foreach(bytebinreb)

temp+=b.ToString("X2")+"";

returntemp;

}

//开串口

publicboolOpenCom()

{

try

{

if(mycom1.Opened)

{

mycom1.Close();

mycom1.Open();//打开串口

}

else

{

mycom1.Open();//打开串口

}

returntrue;

}

catch(Exceptione)

{

MessageBox.Show("错误:"+e.Message);

returnfalse;

}

}

//发送按钮

privatevoidbutton1_Click(objectsender,System.EventArgse)

{

if(t_send.Text=="")

{MessageBox.Show("发送数据为空!");return;}

byte[]temp1=mysendb();

intsendnumb=0;

try

{

sendnumb=mycom1.Write(temp1);

msg.AppendText("\r\n发送数据("+sendnumb+"):"+dis_package(temp1)); recb=mycom1.Read(50);

//if(recb.Length!=0)

msg.AppendText("\r\n接收到数据包:"+dis_package(recb));

}

catch

{msg.AppendText("\r\n发送失败!");return;}

//OpenCom();

}

//去掉发送数组中的空格

publicstringdelspace(stringputin)

{

stringputout="";

for(inti=0;i

{

if(putin[i]!='')

putout+=putin[i];

}

returnputout;

}

//提取数据包

publicbyte[]mysendb()

{

stringtemps=delspace(t_send.Text);

byte[]tempb=newbyte[50];

intj=0;

for(inti=0;i

tempb[j]=Convert.ToByte(temps.Substring(i,2),16);

byte[]send=newbyte[j];

Array.Copy(tempb,send,j);

returnsend;

}

//清空按钮

privatevoidbutton3_Click(objectsender,System.EventArgse)

{

t_send.Text=string.Empty;

msg.Text=string.Empty;

}

//参数设置

privatevoidbutton2_Click(objectsender,System.EventArgse)

{

mycom1.PortNum=Convert.ToInt16(t_port.Text);//1,2,3,4

mycom1.BaudRate=Convert.ToInt16(t_rate.Text);//1200,2400,4800,9600 mycom1.ByteSize=Convert.ToByte(t_bytesize.Text,10);//8bits

mycom1.Parity=Convert.ToByte(t_parity.Text,10);//0-4=no,odd,even,mark,spac e

mycom1.StopBits=Convert.ToByte(t_stopbyte.Text,10);//0,1,2=1,1.5,2

//iTimeout=3;

if(this.OpenCom())

msg.AppendText("串口初始化成功……\r\n");

else

msg.AppendText("串口初始化失败!\r\n");

}

//程序关闭,结束串口

privatevoidForm1_Closing(objectsender,https://www.doczj.com/doc/889348395.html,ponentModel.CancelEventArg se)

{

mycom1.Close();

}

privatevoidbutton5_Click(objectsender,System.EventArgse)

{

if(mycom1.Opened)

{

mycom1.Close();

button5.Text="开启串口";

msg.AppendText("\r\n串口被关闭……");

}

else

{

mycom1.Open();

button5.Text="关闭串口";

msg.AppendText("\r\n串口成功开启……");

}

}

}

}

注意:发送数据包的格式是16进制数据如:024566FA中间可以有或者没有空格,但要保证有偶数位

c语言串口通信范例

一个c语言的串口通信程序范例 分类:技术笔记 标签: c语言 串口通信 通信程序 it 最近接触一个项目,用HL-C1C激光位移传感器+易控组态软件完成生产线高度跳变检测,好久没有接触c c#,一些资料,找来做个记录,也许大家用的着 #include #include #include #include #define COM232 0x2f8 #define COMINT 0x0b #define MaxBufLen 500 #define Port8259 0x20 #define EofInt 0x20 static int comportaddr; static char intvectnum; static unsigned char maskb; static unsigned char Buffer[MaxBufLen]; static int CharsInBuf,CircIn,CircOut; static void (interrupt far *OldAsyncInt)();

static void interrupt far AsyncInt(void); void Init_COM(int ComPortAddr, unsigned char IntVectNum, int Baud, unsigned char Data, unsigned char Stop, unsigned char Parity) { unsigned char High,Low; int f; comportaddr=ComPortAddr; intvectnum=IntVectNum; CharsInBuf=0;CircIn=0;CircOut=0; f=(Baud/100); f=1152/f; High=f/256; Low=f-High*256; outp(ComPortAddr+3,0x80); outp(ComPortAddr,Low); outp(ComPortAddr+1,High); Data=(Data-5)|((Stop-1)*4); if(Parity==2) Data=Data|0x18; else if(Parity==1) Data=Data|0x8; outp(ComPortAddr+3,Data); outp(ComPortAddr+4,0x0a);

C语言串口通信助手代码

该程序全部由C写成没有C++ 更没用MFC 完全是自娱自乐给需要的人一个参考 #include "stdafx.h" #include #include "resource.h" #include "MainDlg.h" #include #include #include HANDLE hComm;//用于获取串口打开函数的返回值(句柄或错误值)OVERLAPPED m_ov; COMSTAT comstat; DWORD m_dwCommEvents;

TCHAR cRecs[200],cSends[100]; //接收字符串发送字符串 char j=0,*cCom; //接收用统计数据大小变量端口选择 BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog); HANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand); HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose); } return FALSE; } /*系统初始化函数*/ BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) { HWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1); ComboBox_InsertString(hwndCombo1,-1,TEXT("COM1")); ComboBox_InsertString(hwndCombo1,-1,TEXT("COM2"));

用C#一步步写串口通信分析解析

我们来看具体的实现步骤。 公司要求实现以下几个功能: 1):实现两台计算机之前的串口通信,以16进制形式和字符串两种形式传送和接收。 2):根据需要设置串口通信的必要参数。 3):定时发送数据。 4):保存串口设置。 看着好像挺复杂,其实都是纸老虎,一戳就破,前提是你敢去戳。我尽量讲的详细一些,争取说到每个知识点。 在编写程序前,需要将你要测试的COM口短接,就是收发信息都在本地计算机,短接的方式是将COM口的2、3号针接起来。COM 口各针的具体作用,度娘是这么说的:COM口。记住2、3针连接一定要连接牢固,我就是因为接触不良,导致本身就不通,白白花掉了一大半天时间调试代码。 下面给出主要的操作界面,如下:

顺便,我将所有控件对应的代码名字也附上了,相信对初学者来说,再看下面的代码会轻松很多。控件名字命名的方法是“控件名+作用”的形式,例如“打开串口”的开关按钮,其名字是btnSwitch (btn就是button的简写了)。我认为这种命名控件的方式比较好,建议大家使用,如果你有好的命名方式,希望你能告诉我! 下面我们将各个功能按照从主到次的顺序逐个实现。(我分块给出代码实现,详细代码见链接:《C#串口通信工具》)

一、获取计算机的COM口总个数,将它们列为控件cbSerial的候选项,并将第一个设为cbSerial的默认选项。 这部分是在窗体加载时完成的。请看代码: (很多信息代码的注释里讲的很清楚,我就不赘述了。) [csharp]view plaincopyprint? 1.//检查是否含有串口 2. string[] str = SerialPort.GetPortNames(); 3. if (str == null) 4. { 5. MessageBox.Show("本机没有串口!", "Error"); 6. return; 7. } 8. 9. //添加串口项目 10. foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) 11. {//获取有多少个COM口 12. cbSerial.Items.Add(s); 13. } 14. 15. //串口设置默认选择项

VC++_串口上位机编程实例

VC++串口上位机简单例程(源码及详细步骤) (4.33MB) VC++编写简单串口上位机程序 2010年4月13日10:23:40 串口通信,MCU跟PC通信经常用到的一种通信方式,做界面、写上位机程序的编程语言、编译环境等不少,VB、C#、LABVIEW等等,我会的语言很少,C语言用得比较多,但是还没有找到如何用C语言来写串口通信上位机程序的资料,在图书管理找到了用VC++编写串口上位机的资料,参考书籍,用自己相当蹩脚的C++写出了一个简单的串口上位机程序,分享一下,体验一下单片机和PC通信的乐趣。 编译环境:VC++6.0 操作系统:VMWare虚拟出来的Windows XP 程序实现功能: 1、PC初始化COM1口,使用n81方式,波特率57600与单片机通信。PC的COM口编号可以通过如下方式修改: 当然也可以通过上位机软件编写,通过按钮来选择COM端口号,但是此次仅仅是简单的例程,就没有弄那么复杂了。COM1口可用的话,会提示串口初始化完毕。否则会提示串口已经打开Port already open,表示串口已经打开,被占用了。 2、点击开始转换,串口会向单片机发送0xaa,单片机串口中断接收到0xaa后启动ADC转

换一次,并把转换结果ADCL、ADCH共两个字节的结果发送至PC,PC进行数值转换后在窗口里显示。(见文章末尾图) 3、为防止串口被一只占用,点击关闭串口可以关闭COM1,供其它程序使用,点击后按钮变为打开串口,点击可重新打开COM1。 程序的编写: 1、打开VC++6.0建立基于对话框的MFC应用程序Test,

2、在项目中插入MSComm控件:工程->增加到工程->Components and Controls->双击Registered ActiveX Controls->选择Microsoft Communications Control,version6.0->Insert,按

单片机串口通信C程序及应用实例

一、程序代码 #include//该头文件可到https://www.doczj.com/doc/889348395.html,网站下载#define uint unsigned int #define uchar unsigned char uchar indata[4]; uchar outdata[4]; uchar flag; static uchar temp1,temp2,temp3,temp; static uchar R_counter,T_counter; void system_initial(void); void initial_comm(void); void delay(uchar x); void uart_send(void); void read_Instatus(void); serial_contral(void); void main() { system_initial(); initial_comm(); while(1) { if(flag==1) { ES = 0; serial_contral(); ES = 1; flag = 0; } else read_Instatus(); } } void uart_send(void) { for(T_counter=0;T_counter<4;T_counter++) { SBUF = outdata[T_counter]; while(TI == 0);

TI = 0; } T_counter = 0; } uart_receive(void) interrupt 4 { if(RI) { RI = 0; indata[R_counter] = SBUF; R_counter++; if(R_counter>=4) { R_counter = 0; flag = 1; } } } void system_initial(void) { P1M1 = 0x00; P1M0 = 0xff; P1 = 0xff; //初始化为全部关闭 temp3 = 0x3f;//初始化temp3的值与六路输出的初始值保持一致 temp = 0xf0; R_counter = 0; T_counter = 0; } void initial_comm(void) { SCON = 0x50; //设定串行口工作方式:mode 1 ; 8-bit UART,enable ucvr TMOD = 0x21; //TIMER 1;mode 2 ;8-Bit Reload PCON = 0x80; //波特率不加倍SMOD = 1 TH1 = 0xfa; //baud: 9600;fosc = 11.0596 IE = 0x90; // enable serial interrupt TR1 = 1; // timer 1 RI = 0; TI = 0; ES = 1; EA = 1; }

VC与c51串口通讯程序

跟着步骤学习 1.建立项目:打开VC++6.0,建立一个基于对话框的MFC应用程序SCommTest 2.在项目中插入MSComm控件选择Project菜单下Add To Project子菜单中的 Components and Controls…选项,在弹出的对话框中双击Registered ActiveX Controls项(稍等一会,这个过程较慢),则所有注册过的ActiveX控件出现在列表框中。选择Microsoft Communications Control, version 6.0,,单击Insert按钮将它插入到我们的Project中来,接受缺省的选项。(如果你在控件列表中看不到Microsoft Communications Control, version 6.0,那可能是你在安装VC6时没有把ActiveX一项选上,重新安装VC6,选上ActiveX就可以了), 这时在ClassView视窗中就可以看到CMSComm类了,(注意:此类在ClassWizard中看不到,重构clw 文件也一样),并且在控件工具栏Controls中出现了电话图标(如图1所示),现在要做的是用鼠标 将此图标拖到对话框中,程序运行后,这个图标是看不到的。 3.利用ClassWizard定义CMSComm类控制对象打开ClassWizard ->Member Viariables选项卡,选择CSCommTestDlg类,为IDC_MSCOMM1 添加控制变量:m_ctrlComm,这时你可以看一看,在对话框头文件中自动 加入了//{{AFX_INCLUDES() #include "mscomm.h" //}}AFX_INCLUDES (这时运行程序,如果有错,那就再从头开始)。 4.在对话框中添加控件向主对话框中添加两个编辑框,一个用于接收显 示数据ID为IDC_EDIT_RXDATA,另一个用于输入发送数据,ID为 IDC_EDIT_TXDATA,再添加一个按钮,功能是按一次就把发送编辑框中的内 容发送一次,将其ID设为IDC_BUTTON_MANUALSEND。别忘记了将接收编辑 框的Properties->Styles中把Miltiline和Vertical Scroll属性选上,发送编辑框若你想输入多行文字,也可选上Miltiline。 再打开ClassWizard->Member Viariables选项卡,选择CSCommTestDlg类,为IDC_EDIT_RXDATA 添加CString变量m_strRXData,为IDC_EDIT_TXDATA添加CString变量m_strTXData。说明: m_strRXData和m_strTXData分别用来放入接收和发送的字符数据。 5.添加串口事件消息处理函数OnComm()打开ClassWizard->Message Maps,选择类CSCommTestDlg,选择IDC_MSCOMM1,双击消息OnComm,将弹出的对话框中将函数名改为OnComm,(好记而已)OK。 这个函数是用来处理串口消息事件的,如每当串口接收到数据,就会产生一个串口接收数据缓冲区中有字符的消息事件,我们刚才添加的函数就会执行,我们在OnComm()函数加入相应的处理代码就能实现自已想要的功能了。请你在函数中加入如下代码: void CSCommTestDlg::OnComm() { // TODO: Add your control notification handler code here VARIANT variant_inp; COleSafeArray safearray_inp; LONG len,k; BYTE rxdata[2048]; //设置BYTE数组 An 8-bit integerthat is not signed. CString strtemp; if(m_ctrlComm.GetCommEvent()==2) //事件值为2表示接收缓冲区内有字符 { ////////以下你可以根据自己的通信协议加入处理代码 variant_inp=m_ctrlComm.GetInput(); //读缓冲区 safearray_inp=variant_inp; //VARIANT型变量转换为ColeSafeArray型变量 len=safearray_inp.GetOneDimSize(); //得到有效数据长度 for(k=0;k

c语言串口通信范例

c语言串口通信范例 This manuscript was revised by the office on December 22, 2012

一个c语言的串口通信程序范例 标签:分类: 最近接触一个项目,用HL-C1C激光位移传感器+易控组态软件完成生产线高度跳变检测,好久没有接触c c#,一些资料,找来做个记录,也许大家用的着 #include <> #include <> #include <> #include <> #define COM232 0x2f8 #define COMINT 0x0b #define MaxBufLen 500 #define Port8259 0x20 #define EofInt 0x20

static int comportaddr; static char intvectnum; static unsigned char maskb; static unsigned char Buffer[MaxBufLen]; static int CharsInBuf,CircIn,CircOut; static void (interrupt far *OldAsyncInt)(); static void interrupt far AsyncInt(void); void Init_COM(int ComPortAddr, unsigned char IntVectNum, int Baud, unsigned char Data, unsigned char Stop, unsigned char Parity) { unsigned char High,Low; int f; comportaddr=ComPortAddr; intvectnum=IntVectNum; CharsInBuf=0;CircIn=0;CircOut=0; f=(Baud/100);

UART串口通信设计实例

2.5 UART串口通信设计实例(1) 接下来用刚才采用的方法设计一个典型实例。在一般的嵌入式开发和FPGA设计中,串口UART是使用非常频繁的一种调试手段。下面我们将使用Verilog RTL编程设计一个串口收发模块。这个实例虽然简单,但是在后续的调试开发中,串口使用的次数比较多,这里阐明它的设计方案,不仅仅是为了讲解RTL编程,而且为了后续使用兼容ARM9内核实现嵌入式开发。 串口在一般的台式机上都会有。随着笔记本电脑的使用,一般会采用USB转串口的方案虚拟一个串口供笔记本使用。图2-7为UART串口的结构图。串口具有9个引脚,但是真正连接入FPGA开发板的一般只有两个引脚。这两个引脚是:发送引脚TxD和接收引脚RxD。由于是串行发送数据,因此如果开发板发送数据的话,则要通过TxD线1 bit接着1 bit 发送。在接收时,同样通过RxD引脚1 bit接着1 bit接收。 再看看串口发送/接收的数据格式(见图2-8)。在TxD或RxD这样的单线上,是从一个周期的低电平开始,以一个周期的高电平结束的。它中间包含8个周期的数据位和一个周期针对8位数据的奇偶校验位。每次传送一字节数据,它包含的8位是由低位开始传送,最后一位传送的是第7位。

这个设计有两个目的:一是从串口中接收数据,发送到输出端口。接收的时候是串行的,也就是一个接一个的;但是发送到输出端口时,我们希望是8位放在一起,成为并行状态(见图2-10)。我们知道,串口中出现信号,是没有先兆的。如果出现了串行数据,则如何通知到输出端口呢?我们引入“接收有效”端口。“接收有效”端口在一般情况下都是低电平,一旦有数据到来时,它就变成高电平。下一个模块在得知“接收有效”信号为高电平时,它就明白:新到了一个字节的数据,放在“接收字节”端口里面。

C语言串口通信-源代码

#include #include #include #include #define COM232 0x2f8 #define COMINT 0x0b #define MaxBufLen 500 #define Port8259 0x20 #define EofInt 0x20 static int comportaddr; static char intvectnum; static unsigned char maskb; static unsigned char Buffer[MaxBufLen]; static int CharsInBuf,CircIn,CircOut; static void (interrupt far *OldAsyncInt)(); static void interrupt far AsyncInt(void); void Init_COM(int ComPortAddr, unsigned char IntVectNum, int Baud, unsigned char Data, unsigned char Stop, unsigned char Parity) { unsigned char High,Low; int f; comportaddr=ComPortAddr; intvectnum=IntVectNum; CharsInBuf=0;CircIn=0;CircOut=0; f=(Baud/100); f=1152/f; High=f/256; Low=f-High*256; outp(ComPortAddr+3,0x80); outp(ComPortAddr,Low); outp(ComPortAddr+1,High); Data=(Data-5)|((Stop-1)*4); if(Parity==2) Data=Data|0x18; else if(Parity==1) Data=Data|0x8; outp(ComPortAddr+3,Data);

WIN_API串口通信详细讲解带范例程序说明

WIN32 API串口通讯实例教程 第一节实现串口通讯的函数及串口编程简介 API函数不仅提供了打开和读写通讯端口的操作方法,还提供了名目繁多的函数以支持对串行通讯的各种操作。常用函数及作用下: 函数名作用 CreateFile 打开串口 GetCommState 检测串口设置 SetCommState 设置串口 BuilderCommDCB 用字符串中的值来填充设备控制块 GetCommTimeouts 检测通信超时设置 SetCommTimeouts 设置通信超时参数 SetCommMask 设定被监控事件 WaitCommEvent 等待被监控事件发生 WaitForMultipleObjects 等待多个被监测对象的结果 WriteFile 发送数据 ReadFile 接收数据 GetOverlappedResult 返回最后重叠(异步)操作结果 PurgeComm 清空串口缓冲区,退出所有相关操作 ClearCommError 更新串口状态结构体,并清除所有串口硬件错误 CloseHandle 关闭串行口 用Windows API 编写串口程序本身是有巨大优点的,因为控制能力会更强,效率也会更高。 API编写串口,过程一般是这样的: 1、创建串口句柄,用CreateFile; 2、对串口的参数进行设置,其中比较重要的是波特率(BaudRate),数据宽度(BytesBits),奇偶校验(Parity),停止位(StopBits),当然,重要的还有端口号(Port); 3、然后对串口进行相应的读写操作,这时候用到ReadFile和WriteFile函数; 4、读写结束后,要关闭串口句柄,用CloseFile。 下面依次讲述各个步骤的过程。

串口通信

一. 实验目的及实验环境 <1>实验环境 Java eclipse下 <2>实验目的 了解串行通信的背景知识后,通过三线制制作一条串口通信线(PC-PC),并编程实现两台PC间通过RS-232C通信。要求两台PC机能进行实时的字符通信,并了解工业自动化控制中的基本通信方式。 二.实验内容 1、检查PC是否具有串行通信接口,并按其针脚类准备一条串口通信线缆。 2、串口包的安装,下载javacomm20-win32.zip并解压,将win32com.dll复制到\bin目录下;将comm.jar复制到\lib;把https://www.doczj.com/doc/889348395.html,m.properties 也同样拷贝到\lib目录下,再将上面提到的文件放到JRE相应的目录下就可以了。 三、方案设计 1、将实验所需RS-232缆线准备好,并将JAVA串口包复制到相应地目录下。 2、查找有关串口通信的书籍以及在网上查找相应地串口通信代码。 3、用JAVA编程软件JCreator编写代码。 四.测试数据及运行结果 图一主界面

图二发送消息 图三接收消息 五.总结 1、实验过程中遇到的问题及解决办法; 串口包的安装配置比较难完成,最后在网上看各种博客和论坛,才将问题解决。还有一些代码问题,最后找同学调试好了。 2、对设计及调试过程的心得体会。 通过本次串口实验,我对串口通信的知识了解的更透彻,这是在刚开始对串口通信知识不了解的情况下就编程而造成许多错误之后才得到的结果。在网上查找资料的时候也接触到了不少其他的编程语言例如VB,delphi,C#等,这也让我对这些从没有学过的语言有所了解,我想这些知识对以后的实验工作都有帮助。我也进一步发现了自己动手能力和自学能力都得到很多的进步,同时也对串口的发送与接收信息有了进一步的了解。 六.附录:源代码

VB串口通信程序代码

vb中怎样用mscomm控件实现串口通信 本问分两部分均来自https://www.doczj.com/doc/889348395.html, 第一部分jessezappy(晶晶) ================================================================================== If MSComm1.PortOpen Then MSComm1.PortOpen = False https://www.doczj.com/doc/889348395.html,mPort = 1 '假定是用COM1口 ' 设定传输速率等,可依照您的需求更改 MSComm1.Settings = "9600,N,8,1" MSComm1.PortOpen = True '---------初始化Modem------------- MSComm1.Output = "ATZ" MSComm1.Output = "AT&F" MSComm1.Output = "ATE0" MSComm1.Output = "ATM1" MSComm1.Output = "ATQ0" MSComm1.Output = "ATV0" '--------------------------拨号------------- MSComm1.Output ="ATDT163" '拨163 '---------------------------接通后 MSComm1.Output ="SDFJDKSJLKFA" '发送字符串 '--------------------- Private Sub MSComm1_OnComm() '用串口事件捕捉数据.. If MSComm1.InBufferCount Then ' 通讯埠中假如有资料的话, 则读取进来 InStringB = InStringB & MSComm1.Input ' 如果资料中有Chr(13) 和Chr(10) 的话, 则显示出来 If InStr(InStringB, vbCrLf) Then instring = instring & InStringB AddText Text3, InStringB, False InStringB = "" End If End If END SUB

用SerialPort类设计串口通讯程序

使用SerialPort类设计串口通讯程 一.概述 输送带控制模块的核心技术是与PLC的串口通讯,在Visual Studio 6.0中编写串口通讯程序,一般都使用Microsoft Communication Control(简称MSComm)的通讯控件,只要通过对此控件的属性和事件进行相应编程操作,就可以轻松地实现串口通讯。但在https://www.doczj.com/doc/889348395.html,技术广泛应用的今天,Visual https://www.doczj.com/doc/889348395.html,没有将此控件加入控件库,所以人们采用了许多方法在Visual https://www.doczj.com/doc/889348395.html,来编写串口通讯程序:第一种方法是通过采用Visual Studio 6.0中原来的MSComm控件这是最简单的,最方便的方法,但需要注册;第二种方法是采用微软在.NET推出了一个串口控件,基于.NET的P/Invoke调用方法实现;第三种方法是自己用API写串口通信,虽然难度高,但可以方便实现自己想要的各种功能。 现在微软推出了最新版本的Visual Studio 2005开发工具,可以不再采用第三方控件的方法来设计串口通讯程序。NET Framework 2.0类库包含了SerialPort类,方便地实现了所需要串口通讯的多种功能,为了使MSComm编程方法快速转换到以SerialPort类为核心的串口通讯的设计方法,这里着重讨论了Visual Studio 6.0的MSComm控件和SerialPort类设计方法的异同点。 二.SerialPort常用属性、方法和事件 1.命名空间 System.IO.Ports命名空间包含了控制串口重要的SerialPort类,该类提供了同步I/O 和事件驱动的I/O、对管脚和中断状态的访问以及对串行驱动程序属性的访问,所以在程序代码起始位置需加入Using System.IO.Ports。 2.串口的通讯参数 串口通讯最常用的参数就是通讯端口号及通讯格式(波特率、数据位、停止位和校验位),在MSComm 中相关的属性是CommPort和Settings。SerialPort类与MSComm有一些区别: 通讯端口号 [PortName]属性获取或设置通信端口,包括但不限于所有可用的COM 端口,请注意该属性返回类型为String,不是https://www.doczj.com/doc/889348395.html,mPort的short类型。通常情况下,PortName正常返回的值为COM1、COM2……,SerialPort类最大支持的端口数突破了CommPort控件中CommPort 属性不能超过16的限止,大大方便了用户串口设备的配置。 通讯格式 SerialPort类对分别用[BaudRate]、[Parity] 、[DataBits]、[StopBits]属性设置通讯格式中的波特率、校验位、数据位和停止位,其中[Parity]和[StopBits]分别是枚举类型Parity、StopBits,Parity 类型中枚举了Odd(奇)、Even(偶)、Mark、None、Space,Parity枚举了None、One、OnePointFive、Two。 SerialPort类提供了七个重载的构造函数,既可以对已经实例化的SerialPort对象设置上述相关属性的值,也可以使用指定的端口名称、波特率和奇偶校验位数据位和停止位直接初始化SerialPort 类的新实例。

用C编写的RS232串口通信程序

void main() { delayms(100); init(); //初始化系统 delayms(100); init_wdt(); //初始化看门狗 while(1) { while(!RI_0) //是否收到数据 { clr_wdt(); } RI_0=0; //清除接收中断标志 buffer=S0BUF; if(buffer==0x5a) //检测祯头0 start0=1; if(buffer==0x54) //检测祯头1 start1=1; if(buffer==0x5a) //检测祯尾0 end0=1; if(buffer==0xfe) //检测祯尾1 end1=1; if((start0==1)&(start1==1)) { buff[i]=buffer; //从祯头1开始存储数据 i++; } if((end0==1)&(end1==1)) //是否已经接收祯尾 { count=i; //数据长度为count个 i=1; if((buff[2]==0x03)&(count==107)) //是否422指令 { buff[0]=0x5a; //重填祯头0 buff[count-4]=0; //校验和清零 for(k=2;k<(count-4);k++) //计算校验和 { buff[count-4]+=buff[k]; } for(k=0;k

S0BUF=buff[k]; while(!TI_0); //等待发送完成 TI_0=0; //清除发送中断标志 } reset(); } else if((buff[2]==0x05)&(count==7)) //是否AD测试指令 { sendad(); reset(); } else if((buff[2]==0x18)&(count==7)) //是否发送时序信号指令 { sendpaulse(); reset(); } else //如果接收错误,则恢复各标志位为初始状态以便下次接收 { reset(); } } } } void reset() { start0=0; //祯头祯尾标志位清零 start1=0; end0=0; end1=0; for(k=0;k

Labview串口通信开发实例(值得拥有)

串口通信的基本概念 串口通信的基本概念 1,什么是串口? 2,什么是RS-232? 3,什么是RS-422? 4,什么是RS-485? 5,什么是握手? 1,什么是串口? 串口是计算机上一种非常通用设备通信的协议(不要与通用串行总线Universal Serial Bus或者USB混淆)。大多数计算机包含两个基于RS232的串口。串口同时也是仪器仪表设备通用的通信协议;很多GPIB兼容的设备也带有RS-232口。同时,串口通信协议也可以用于获取远程采集设备的数据。 串口通信的概念非常简单,串口按位(bit)发送和接收字节。尽管比按字节(byte)的并行通信慢,但是串口可以在使用一根线发送数据的同时用另一根线接收数据。它很简单并且能够实现远距离通信。比如IEEE488定义并行通行状态时,规定设备线总常不得超过20米,并且任意两个设备间的长度不得超过2米; 而对于串口而言,长度可达1200米。

典型地,串口用于ASCII码字符的传输。通信使用3根线完成:(1)地线,(2)发送,(3)接收。由于串口通信是异步的,端口能够在一根线上发送数据同时在另一根线上接收数据。其他线用于握手,但是不是必须的。串口通信最重要的参数是波特率、数据位、停止位和奇偶校验。对于两个进行通行的端口,这些参 数必须匹配: a,波特率:这是一个衡量通信速度的参数。它表示每秒钟传送的bit的个数。例如300波特表示每秒钟发送300个bit。当我们提到时钟周期时,我们就是指波特率例如如果协议需要4800波特率,那么时钟是4800Hz。这意味着串口通信在数据线上的采样率为4800Hz。通常电话线的波特率为14400,28800和36600。波特率可以远远大于这些值,但是波特率和距离成反比。高波特率常常用于放置的很近的仪器间的通信,典型的例子就是GPIB 设备的通信。 b,数据位:这是衡量通信中实际数据位的参数。当计算机发送一个信息包,实际的数据不会是8位的,标准的值是5、7和8位。如何设置取决于你想传送的信息。比如,标准的ASCII码是0~127(7位)。扩展的ASCII码是0~255(8位)。如果数据使用简单的文本(标准 ASCII码),那么每个数据包使用7位数据。每个包是指一个字节,包括开始/停止位,数据位和奇偶校验位。由于实际数据位取决于通信协议的选取,术语“包”指任何通信 的情况。 c,停止位:用于表示单个包的最后一位。典型的值为1,1.5和

C#中串口通信编程

本文将介绍如何在.NET平台下使用C#创建串口通信程序,.NET 2.0提供了串口通信的功能,其命名 空间是System.IO.Ports。这个新的框架不但可以访问计算机上的串口,还可以和串口设备进行通信。 我们将使用标准的RS 232 C 在PC间通信。它工作在全双工模式下,而且我们不打算使用任何的握手或流控制器,而是使用无modem连接。 命名空间 System.IO.Ports命名空间中最重用的是SerialPort 类。 创建SerialPort 对象 通过创建SerialPort 对象,我们可以在程序中控制串口通信的全过程。 我们将要用到的SerialPort 类的方法: ReadLine():从输入缓冲区读一新行的值,如果没有,会返回NULL WriteLine(string):写入输出缓冲 Open():打开一个新的串口连接 Close():关闭 Code: //create a Serial Port object SerialPort sp = new SerialPort (); 默认情况下,DataBits 值是8,StopBits 是1,通信端口是COM1。这些都可以在下面的属性中重新设置: BaudRate:串口的波特率 StopBits:每个字节的停止位数量 ReadTimeout:当读操作没有完成时的停止时间。单位,毫秒 还有不少其它公共属性,自己查阅MSDN。

串口的硬件知识 在数据传输的时候,每个字节的数据通过单个的电缆线传输。包包括开始位,数据,结束为。一旦 开始位传出,后面就会传数据,可能是5,6,7或8位,就看你的设定了。发送和接收必须设定同样 的波特率和数据位数。 无猫模式 没有Modem模式的电缆只是简单地交叉传送和接收线。同样DTR & DSR, 和 RTS & CTS也需要交叉。RS232针图 这里,我们三条线。互连2和3(一段的2pin连接3pin),连接两端的5pin。 [示例程序] 主程序

RS232串口通信基本知识与实例

1,RS232串口通信基本知识 (1)目前较为常用的串口是9针串口(DB9。通信距离较近时(<12m),可以用电缆线直接连接标准RS232端口;若距离较远,需附加调制解调器(MOD EM)。 (2)RS232C串口通信接线方法(三线制) 接收数据针脚(或线)与发送数据针脚(或线)相连,彼些交叉,信号地对应相接 (3)DB9接口三线引脚定义 2 ---- RXD 接收数据 3 ---- TXD 发送数据 5 ---- GND 信号地 (4)串行通信方式 1)单工:信息只能单向传送 2)半双工:信息可双向传送但不能同时进行 3)全双工:信息可同时进行双向传送 (5)RS232逻辑电平 逻辑0电平规定为+5 ~ +15V之间;逻辑1是电平为-5 ~ -15V之间,因此在与单片机进行通信时需要进行电平转换 (6)RS232串行通信接口电路设计 (7)51单片机串行通信接口软件设计 1)两个重要指标:可靠性和速度,可靠性是第一位。 2)与串口通信相关的几个寄存器和控制位 TMOD:可以用它来设置定时器工作方式(如果在MCU中使用的是定时器来产生波特率,就需要对这个寄存器进行设置,通常设为0x20,即设置定时器1为8位自动重装定时器,即工作方式1) TH1和TL1:定时器1初始值(可通过波特率计算软件获得) TR1:开启定时器1 SCON:串口控制寄存器,通常设为0x50,即10位异步传输,由定时器1

产生波特率,无奇偶校验位,允许接收 PCON:这个寄存器主要用到它的最高位SMON,当最高位设为1时,原波特率加倍 ES:串口中断使能位 EA:全局中断使能位 3)波特率计算方法(使用一个名为“51波特率初值计算.exe”的小软件)第1步:选择定时器工作方式(方式2) 第2步:输入晶振值(11.0592) 第3步:选择波特率(9600) 第4步:设置SMOD值(0) 第5步:点击确定 第6步:将软件上显示值赋给TH1和TL1 4)串口初始化程序 void Initial_RS232(unsigned char rate) { //默认晶振值为11.0592MHz unsigned char Reload1; switch(rate) //根据拨码器设置波特率 { case 0: Reload1 = 0xE8; //2400bps break; case 1: Reload1 = 0xF4; //4800bps break; case 2: Reload1 = 0xFA; //9600bps break; case 3: Reload1 = 0xFD; //19200bps break; default: Reload1 = 0x00; break; } PCON = PCON|0x80; //SMOD = 1 ;波特率加倍 TMOD = 0x20; //0011,00010设置定时器1为8位自动重装计数器 SCON = 0x50; //0101,0000 8位可变波特率,无奇偶校验位 TH1 = Reload1; //设置定时器1自动重装数 TL1 = Reload1; TR1 = 1; //开定时器1 ES = 1; //允许串口中断 EA = 1; //开总中断 }

delphi7串口通信(spcomm控件)实例

Delphi7串口通信(spcomm控件)实例 最近在用delphi7做串口通信,网上找了很多例程,复制粘贴运行就没有能通过的,再次鄙视一下列位先行者,你们帮人倒是帮到底啊,没一个是拿过来能用的,太坑了,在N天的努力下(鄙人比较笨)终于通过串口接收到数据,希望给后来人予以帮助,程序如下: 功能简介 功能比较简单,只是从串口接收单片机发送的数据,给memo1 unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes,

Graphics, Controls, Forms,

Dialogs, SPComm, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; Comm1: TComm; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Comm1ReceiveData(Sender: TObject; Buffer: Pointer;BufferLength: Word); procedure Comm1ModemStateChange(Sender: TObject; ModemEvent: Cardinal); private { Private declarations } public { Public declarations } end; var

相关主题
文本预览
相关文档 最新文档