C语言串口通信助手代码
C#串口助手
串口助手实现功能实现ASC码与HEX转换ASC、HEX收发测试正常运行效果图源码using System;using System.Text;using System.Windows.Forms; using System.IO.Ports;using System.Threading; using System.IO;//NOTE:设置串口通信的编码格式,默认ASCIInamespace myUSART{public partial class Form1 : Form{SerialPort sp = new SerialPort();//窗体初始化public Form1(){InitializeComponent();}// 检测是否有可用串口,若有添加到下拉菜单,没有提示失败private void CheckPort(){cbxPortName.Items.Clear(); ///清除数据bool haveCOM = false; ///默认串口资源标志无串口资源string[] sn = SerialPort.GetPortNames(); ///获取当前计算机的串行端口名称到字符串数组if (sn == null) ///获取失败,提示错误(看代码提示信息){haveCOM = false;}else ///获取成功,逐个判断串口资源是否可用{foreach (string s in sn) ///字符串s获取串行名称端口数组sn的端口名称{bool Useful = false; ///默认端口资源不可用try{SerialPort sp = new SerialPort(s); ///获取字符串s的端口名称创建端口对象sp.Open();sp.Close();Useful = true;}catch{Useful = false;}if (Useful) ///若端口名称可用,添加到端口数组集合并设串口资源标志有串口资源{cbxPortName.Items.Add(s);haveCOM = true;}}}if (haveCOM) ///有串口资源默认显示最后一个端口名称{cbxPortName.SelectedIndex = 0; ///默认显示最后一个端口名称}else ///没有串口资源提示错误消息{MessageBox.Show("Opration SerialPort failed! It's not useful!" "Error");}}//初始化串口设置private void SetSerialPort(){try{sp.PortName = cbxPortName.Text.Trim();//端口名sp.BaudRate =Convert.ToInt32(cbxBaudRate.Text.Trim());//波特率if (cbxStopBits.Text.Trim() == "1")//停止位{sp.StopBits = StopBits.One;}else if (cbxStopBits.Text.Trim() == "1.5"){sp.StopBits = StopBits.OnePointFive;}else if (cbxStopBits.Text.Trim() == "2"){sp.StopBits = StopBits.Two;}else{sp.StopBits = StopBits.None;}sp.DataBits =Convert.ToInt16(cbxDataBits.Text.ToString().Trim());//数据位if (cbxParity.Text.Trim() == "奇校验")//奇偶校验位{sp.Parity = Parity.Odd;}else if (cbxParity.Text.Trim() == "偶校验"){sp.Parity = Parity.Even;}else{sp.Parity = Parity.None;}sp.Encoding = Encoding.UTF8;//设置串口通信的编码格式,默认ASCII}catch{throw;}}//窗体加载设置private void Form1_Load(obxxxxject sender EventArgs e) {//设置窗口大小this.MaximizeBox = false;//隐藏最大化按钮this.MaximumSize = this.Size;//固定窗口尺寸最大为当前尺寸this.MinimumSize = this.Size;//固定窗口尺寸最小为当前尺寸tbxSendData.Focus();//默认将光标放在发送文本框上ckbHexShow.Select();//默认选择ASCII字符显示ckbHexSend.Select();//默认选择ASCII字符显示CheckPort();//检测可用串口//初始化串口设置cbxBaudRate.SelectedIndex = 0;cbxStopBits.SelectedIndex = 0;cbxDataBits.SelectedIndex = 0;cbxParity.SelectedIndex = 0;}//打开串口设置private void rbtnOpenCOM_Click(obxxxxject sender EventArgs e) {if (rbtnOpenCOM.Text == "打开串口"){SetSerialPort();//设置串口函数if (!sp.IsOpen){try{sp.Open(); //打开串口//禁用设置控件cbxPortName.Enabled = false;cbxBaudRate.Enabled = false;cbxParity.Enabled = false;cbxStopBits.Enabled = false;cbxDataBits.Enabled = false;rbtnOpenCOM.Text = "关闭串口";sp.DataReceived += new SerialDataReceivedEventHandler(COMReceived);//定义串口接收事件DataReceived事件委托}catch (Exception ex){MessageBox.Show("串口"/*+cbxPort.Text*/+ "打开失败失败原因:" + ex.Message "错误提示");}}}else //关闭串口{if (sp.IsOpen) //判断串口是否打开{try{sp.Close(); //关闭串口//启用设置控件cbxPortName.Enabled = true;cbxBaudRate.Enabled = true;cbxParity.Enabled = true;cbxStopBits.Enabled = true;cbxDataBits.Enabled = true;rbtnOpenCOM.Text = "打开串口";rbtnOpenCOM.Checked = false;}catch (Exception ex){MessageBox.Show("串口"/*+ cbxPort.Text*/ + "关闭失败错误提示:" + ex.Message "错误提示");}}else{cbxPortName.Enabled = true;cbxBaudRate.Enabled = true;cbxParity.Enabled = true;cbxStopBits.Enabled = true;cbxDataBits.Enabled = true;rbtnOpenCOM.Text = "打开串口";MessageBox.Show("串口未打开,无法关闭!" "错误提示");}}}//16进制字符串转换成ASCII字符串private string HexToASCII(string str){try{string[] mystr = str.Trim().Split(' '); //去掉字符串首尾的空白后以空格为界线来分割成字符串数组byte[] t = new byte[mystr.Length]; //定义一个和字符串数组等长的字节数组for (int i = 0; i < t.Length; i++) //将字符串数组的元素转换为字节数组并赋值给字节数组{t[i] = Convert.ToByte(mystr[i] 16);}return Encoding.UTF8.GetString(t); //以UTF8编码方式转换字节数组为字符串}catch (Exception ex){ckbHexSend.Select();MessageBox.Show(ex.Message "温馨提示!");return str;}}//字符串转换成16进制字符private string ASCIIToHex(string str){try{byte[] a = Encoding.UTF8.GetBytes(str.Trim());string mystr = "";for (int i = 0; i < a.Length; i++){mystr += a[i].ToString("X2") + " ";}return mystr;}catch (Exception ex){ckbHexSend.Select();MessageBox.Show("转换失败!" + ex.Message "错误提示");return str;}}//选中HEX显示就将字符串数据转换为HEX数据,否则相反private void ckbHexShow_CheckedChanged(obxxxxject sender EventArgs e){if (ckbHexShow.Checked){tbxReceivedData.Text =ASCIIToHex(tbxReceivedData.Text.ToString());}else{tbxReceivedData.Text =HexToASCII(tbxReceivedData.Text);}}//选中HEX发送就将字符串数据转换为HEX数据,否则相反private void ckbHexSend_CheckedChanged(obxxxxject sender EventArgs e){if (ckbHexSend.Checked){tbxSendData.Text =ASCIIToHex(tbxSendData.Text.ToString());}else{tbxSendData.Text = HexToASCII(tbxSendData.Text);}}int Sendlen = 0; //用于发送接收计数private void Send_Click(obxxxxject sender EventArgs e){try{string mystr = tbxSendData.Text.Trim();if (ckbHexSend.Checked){mystr = mystr.Replace(" " "");if ((mystr.Length % 2) != 0)mystr += " ";byte[] a = new byte[mystr.Length / 2];for (int i = 0; i < a.Length; i++){a[i] = Convert.ToByte(mystr.Substring(i * 2 2).Replace(" " "") 16);}sp.Write(a 0 a.Length);Sendlen = Sendlen + a.Length;lbSendCount.Text = "S:" + Sendlen;}else{sp.Write(mystr);Sendlen = Sendlen + mystr.Length;lbSendCount.Text = "S:" + Sendlen;}}catch (Exception ex){MessageBox.Show(ex.Message "温馨提示");}}int Receivelen = 0; //用于接收计数//接收串口数据事件private void COMReceived(obxxxxject senderSerialDataReceivedEventArgs e){Thread.Sleep(100);this.Invoke((EventHandler)(delegate //异步委托一个线程{try{byte[] a = new byte[sp.BytesToRead]; //读出缓冲区串口通讯的字节sp.Read(a 0 a.Length); //写入spif (ckbHexShow.Checked){for (int i = 0; i < a.Length; i++){tbxReceivedData.Text += (a[i].ToString("X2")+" ");}if (ckbWordWrap.Checked){tbxReceivedData.Text += "\r\n";}}else{tbxReceivedData.Text +=Encoding.UTF8.GetString(a);if (ckbWordWrap.Checked){tbxReceivedData.Text += "\r\n";}}Receivelen = Receivelen + a.Length;lbGetCount.Text = "R:" + Receivelen;}catch{throw;}}));}//清空接收private void button2_Click(obxxxxject sender EventArgs e){tbxReceivedData.Clear();}//清空发送private void button4_Click(obxxxxject sender EventArgs e){tbxSendData.Clear();}private void btSaveFiles_Click(obxxxxject sender EventArgs e) {char[] charData;byte[] byData;string s;try{FileStream aFile = new FileStream("Temp.txt" FileMode.Create);if (cbxPortName.Text == ""){s = "No";}else{s = cbxPortName.Text + "+" + cbxBaudRate.Text;}charData = s.ToCharArray();byData = new byte[charData.Length];Encoder e1 = Encoding.UTF8.GetEncoder();e1.GetBytes(charData 0 charData.Length byData 0 true);aFile.Seek(0 SeekOrigin.Begin);aFile.Write(byData 0 charData.Length);aFile.Close();}catch (Exception ex){MessageBox.Show(ex.Message "友情提示");}}private void BtCntClear_Click(obxxxxject sender EventArgs e) {lbSendCount.Text = "S:" + 0;lbGetCount.Text = "R:" + 0;Sendlen = 0;Receivelen = 0;}}}。
C语言串口通信助手代码
该程序全部由C写成没有C++ 更没用MFC完全是自娱自乐给需要的人一个参考#include "stdafx.h"#include <windowsx.h>#include "resource.h"#include "MainDlg.h"#include <windows.h>#include <stdio.h>#include <stdlib.h>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"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM3"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM4"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM5"));ComboBox_SetCurSel(hwndCombo1,0);void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime);SetTimer(hwnd,1,1000,TimerProc);return TRUE;}/*监视串口错误时使用的函数*/boolProcessErrorMessage(char* ErrorText){char *Temp = new char[200];LPVOID lpMsgBuf;FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language(LPTSTR) &lpMsgBuf,NULL);sprintf(Temp, "WARNING: %s Failed with the following error:\n%s\nPort: %d\n", (char*)ErrorText, lpMsgBuf, "com2"); MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP); LocalFree(lpMsgBuf);delete[] Temp;return true;}boolopenport(char *portname)//打开串口{hComm = CreateFile(portname, //串口号“com1”“com2” 调用方法:bool open; open=openport("com2");GENERIC_READ | GENERIC_WRITE, //允许读写0, //通讯设备必须以独占方式打开0, //无安全属性OPEN_EXISTING, //通讯设备已存在FILE_FLAG_OVERLAPPED, //异步I/O0); //通讯设备不能用模板打开if (hComm == INVALID_HANDLE_VALUE) //如果被占用或是没有打开时返回的是这个错误代码CloseHandle(hComm);return FALSE;}elsereturn true;}boolsetupdcb(intrate_arg)//设置port的属性{DCB dcb;int rate= rate_arg;memset(&dcb,0,sizeof(dcb));if(!GetCommState(hComm,&dcb))//获取当前DCB配置return FALSE;// set DCB to configure the serial portdcb.DCBlength = sizeof(dcb);dcb.BaudRate = rate;dcb.Parity = NOPARITY; //奇偶校验值0~4分别对应无校验、奇校验、偶校验、校验置位、校验清零dcb.fParity = 0; //为1的话激活奇偶校验检查dcb.StopBits = ONESTOPBIT;//停止位个数,0~2分别对应1位、1.5位、2位停止位dcb.ByteSize = 8; //数据位数dcb.fOutxCtsFlow = 0;dcb.fOutxDsrFlow = 0;dcb.fDtrControl = DTR_CONTROL_DISABLE; dcb.fDsrSensitivity = 0;dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fOutX = 0;dcb.fInX = 0;dcb.fErrorChar = 0;dcb.fBinary = 1;dcb.fNull = 0;dcb.fAbortOnError = 0;dcb.wReserved = 0;dcb.XonLim = 2;dcb.XoffLim = 4;dcb.XonChar = 0x13;dcb.XoffChar = 0x19;dcb.EvtChar = 0;// set DCBif(!SetCommState(hComm,&dcb))return false;elsereturn true;}/*串口读取相关时间设置*/boolsetuptimeout(DWORDReadInterval,DWORDReadTotalMultiplier,DWORDReadTotalconstant,DW ORDWriteTotalMultiplier,DWORDWriteTotalconstant){COMMTIMEOUTS timeouts;timeouts.ReadIntervalTimeout=ReadInterval; //读取两个字节间隔最大值mS如超过立即返回不再读取timeouts.ReadTotalTimeoutConstant=ReadTotalconstant; //如果同下面一个都为0 则无论是否读到数据都返回// 可以毫秒为单位指定一个乘数,该乘数用来计算读操作的总限时时间timeouts.ReadTotalTimeoutMultiplier=ReadTotalMultiplier; // 以毫秒为单位指定一个常数,用于计算读操作的总限时时间0表示不限时timeouts.WriteTotalTimeoutConstant=WriteTotalconstant;// 写操作延时同上timeouts.WriteTotalTimeoutMultiplier=WriteTotalMultiplier;if(!SetCommTimeouts(hComm, &timeouts))return false;elsereturn true;}intClearn() //清除buff中的内容并返回buff中现有数据量的大小并读取错误原因{DWORD dwError = 0;DWORD BytesRead = 0;ClearCommError(hComm, &dwError, &comstat);return comstat.cbInQue; //返回buff中数据量}/*串口数据接收读取函数*/void ReceiveChar(){BOOL bRead = TRUE;BOOL bResult = TRUE;DWORD dwError = 0;DWORD BytesRead = 0;char i=0,n;char RXBuff;j=0;while (i-n){n=i;Sleep(10);bResult = ClearCommError(hComm, &dwError, &comstat); i=(char)comstat.cbInQue;for (;i>0;i--){if (bRead)bResult = ReadFile(hComm, // Handle to COMM port &RXBuff, // RX Buffer Pointer1, // Read one byte&BytesRead, // Stores number of bytes read&m_ov); // pointer to the m_ov structure// printf("%c",RXBuff);cRecs[j++]=(char)RXBuff;if (!bResult){switch (dwError = GetLastError()){case ERROR_IO_PENDING:{bRead = FALSE;break;}default: break;}elsebRead = TRUE; // close if (bRead)if (!bRead){bRead = TRUE;bResult = GetOverlappedResult(hComm, // Handle to COMM port&m_ov, // Overlapped structure&BytesRead, // Stores number of bytes readTRUE); // Wait flag}}}boolWriteChar(char* m_szWriteBuffer,DWORDm_nToSend) //写字符的函数{BOOL bWrite = TRUE;BOOL bResult = TRUE;DWORD BytesSent = 0;HANDLE m_hWriteEvent;ResetEvent(m_hWriteEvent);if (bWrite){m_ov.Offset = 0;m_ov.OffsetHigh = 0;// Clear bufferbResult = WriteFile(hComm, // Handle to COMM Portm_szWriteBuffer, // Pointer to message buffer in calling finction m_nToSend, // Length of message to send&BytesSent, // Where to store the number of bytes sent&m_ov ); // Overlapped structureif (!bResult){DWORD dwError = GetLastError();switch (dwError){case ERROR_IO_PENDING:{// continue to GetOverlappedResults()BytesSent = 0;bWrite = FALSE;break;}default:// all other error codesbreak;}}} // end if(bWrite)if (!bWrite){bWrite = TRUE;bResult = GetOverlappedResult(hComm, // Handle to COMM port &m_ov, // Overlapped structure&BytesSent, // Stores number of bytes sentTRUE); // Wait flag// deal with the error codeif (!bResult){printf("GetOverlappedResults() in WriteFile()");}} // end if (!bWrite)// Verify that the data size send equals what we tried to send if (BytesSent != m_nToSend){printf("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)m_szWriteBuffer));}return true;}/*window时间函数回调*/void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime){SYSTEMTIME time; //定义机构体变量timeGetLocalTime(&time); //取系统时间以指针方式TCHAR strTime[256]; //程序只有一个作用wsprintf(strTime,"%04d-%02d-%02d %02d:%02d:%02d",time.wYear, //就是读取系统时间time.wMonth,time.wDay,time.wHour,time.wMinute,time.wSecond);//然后写进strTimeSetDlgItemText(hwnd,IDC_TIME,strTime); //这个字符串}void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify){switch(id){case IDC_SEND:{GetDlgItemText (hwnd,IDC_EDIT2,cSends,sizeof(cSends)); unsigned n=sizeof(cSends); //n是通知串口将发送字节的长度char send[100];wsprintf (send,"%s",cSends);WriteChar(send,n-1);SetCommMask(hComm, EV_RXCHAR); //监视串口是否接收有数据ReceiveChar(); //读取串口sbuff中数据cRecs[j]='\0'; //将cRecs转为字符串SetDlgItemText(hwnd,IDC_EDIT1,cRecs);} break;/*case IDC_RECEIVE: //暂时未用采用直接显示的方式{}break;*/case IDC_CHECK:{intctr;HWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);ctr = ComboBox_GetCurSel(hwndCombo1);switch (ctr){case 0:cCom="com1";break;case 1:cCom="com2";break;case 2:cCom="com3";break;case 3:cCom="com4";break;case 4:cCom="com5";break;default: cCom="com1";break;}if (openport(cCom)){ SetDlgItemText(hwnd,IDC_EDIT3,"OK !");MessageBox(hwnd,"串口打开成功!","",0); }elseSetDlgItemText(hwnd,IDC_EDIT3,"FAIL");if(setupdcb(9600)&&setuptimeout(1024,0,0,20,1000)) //初始化串口属性波特率9600SetDlgItemText(hwnd,IDC_EDIT4,"串口属性设置成功");elseSetDlgItemText(hwnd,IDC_EDIT4,"串口初始化失败!"); PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR |PURGE_RXABORT | PURGE_TXABORT);}default:break;}}void Main_OnClose(HWND hwnd) {EndDialog(hwnd, 0);}。
C语言串口通信-源代码
C语言串口通信-源代码#include<tdio.h>#include<do.h>#include<conio.h>#include<tring.h>#defineCOM2320某2f8#defineCOMINT0某0b#defineMa某BufLen500#definePort82590某20#defineEofInt0某20taticcharintvectnum;taticunignedcharmakb;taticunignedcharBuffer[Ma某BufLen];taticintCharInBuf,CircIn,CircOut;taticvoid(interruptfar某OldAyncInt)();taticvoidinterruptfarAyncInt(void);unignedcharData,unignedcharStop,unignedcharParity){ unignedcharHigh,Low;intf;intvectnum=IntVectNum;CharInBuf=0;CircIn=0;CircOut=0;diable();OldAyncInt=getvect(IntVectNum);etvect(IntVectNum,Ay ncInt);enable();makb=inp(Port8259+1);if(IntVectNum==0某0c)outp(Port8259+1,makb&0某ef);eleoutp(Port8259+1,makb&0某f7);}taticvoidinterruptfarAyncInt(void){diable();if(CharInBuf<Ma某BufLen)if(CircIn<Ma某BufLen-1)CircIn++;eleCircIn=0;if(CircIn==CircOut)CircOut++;eleCharInBuf++;enable();outp(Port8259,EofInt);}voidRetore(void)etvect(intvectnum,OldAyncInt);outp(Port8259+1,makb);}intGetCharInBuf(unignedchar某Char) {intFlag;Flag=-1;if(CharInBuf>0){(某Char)=Buffer[CircOut];if(CircOut<Ma某BufLen-1)CircOut++; eleCircOut=0;CharInBuf--;Flag=0;}returnFlag;}intSendChar(unignedcharChar)return0;}main(){inti,c;unignedcharInChar;Init_COM(COM232,COMINT,1200,8,1,0); while(1){if(kbhit()){if((InChar=getch())==27)break; elewhile(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)printf("%c",InChar);}Retore();}接收程序:#include<do.h>#include<ftream.h>#include<conio.h>#include<tdio.h>#include<tdlib.h>#include<math.h>#defineR某D0//接收voidInt(){unignedcharkey,key2;if(peek(0某40,port某2)==0){e某it(1);}ele{};Getportaddr(port);//得到串口地址SerInit(SER_BAUD_9600,SER_PARITY_EVEN|SER_BITS_8|SER_STOP_1) ;//初始化串口,设置波特率等SerOpen();do{if(kbhit()){key2=getch();if(key2==27){break;}};key=getb();if(key!=0某ff){printf("%某\t",key);FILE某fp;fp=fopen("C:\\Receivedata.dat","ab");//可选择接收数据的存放文件路径和文件名if(fp==NULL)printf("Fileopenerror!");//fputc(key,fp);fwrite(&key,izeof(unignedchar),1,fp);fcloe(fp);}}while(key2!=27);SerCloe();//printf("%dcharhabeenreceived\n",incount); //printf("%dcharhabeenended\n",outcount);//printf("\num=%d\n",um);}{printf("PleaeinputthereceiveCOMnum:(1~4)\n"); Cloe_Serial(intport_bae){outp(port_bae+SER_MCR,0);outp(port_bae+SER_IER,0);outp(PIC_IMR,old_int_mak);if(port_bae==COM_1){_do_etvect(INT_SER_PORT_0,Old_Ir);}ele{_do_etvect(INT_SER_PORT_1,Old_Ir);}}/某-------------发送应用----------------某/ voidmain(intargc,char某argv[]){charch,pre;intdone=0;FILE某fp;argc=2;if(argc<2){printf("\nUage:diplayfilename.wav!!!");//e某it(1);}if((fp=fopen(argv[1],"r+b"))==NULL){printf("cannotopenthefile\n");//e某it(0);}feek(fp,0,SEEK_SET);Open_Serial(COM_1,SER_BAUD_9600,SER_PARITY_EVEN|SER_STOP_1);printf("preanykeytobeginending");getch();//Serial_Write('');//该语句可用于发送单个字符while(!done&&ch!=EOF)//发送文件开始{ch=fgetc(fp);SER_BITS_8|//if(ch==EOF)Serial_Write(27);Serial_Write(ch);delay(30);if( kbhit()){pre=getch();if(pre==27){Serial_Write(27);done=1;}}}Cloe _Serial(COM_1);fcloe(fp);}下面介绍最重要的MFC:CWnd:窗口,它是大多数“看得见的东西”的父类(Window里几乎所有看得见的东西都是一个窗口,大窗口里有许多小窗口),比如视图CView、框架窗口CFrameWnd、工具条CToolBar、对话框CDialog、按钮CButton,etc;一个例外是菜单(CMenu)不是从窗口派生的。
c语言串口通信范例
c语言串口通信范例标准化管理处编码[BBX968T-XBB8968-NNJ668-MM9N]一个c语言的串口通信程序范例标签:分类:最近接触一个项目,用HL-C1C激光位移传感器+易控组态软件完成生产线高度跳变检测,好久没有接触c c#,一些资料,找来做个记录,也许大家用的着#include <>#include <>#include <>#include <>#define COM232 0x2f8#define COMINT 0x0b#define MaxBufLen 500#define Port8259 0x20#define EofInt 0x20static 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);?outp(ComPortAddr+1,0x01);?disable();OldAsyncInt=getvect( IntVectNum );setvect( IntVectNum, AsyncInt );enable();?maskb=inp(Port8259+1);if(IntVectNum==0x0c)outp(Port8259+1,maskb&0xef); else outp(Port8259+1,maskb&0xf7);?}static void interrupt far AsyncInt(void){disable();if(CharsInBuf<MaxBufLen)Buffer[CircIn]=inp(comportaddr);if(CircIn<MaxBufLen-1) CircIn++;else CircIn=0;if(CircIn==CircOut) CircOut++;else CharsInBuf++;enable();outp(Port8259,EofInt);}void Restore(void){setvect(intvectnum,OldAsyncInt);outp(Port8259+1,maskb);?}int GetCharInBuf(unsigned char *Char) {int Flag;Flag=-1;if(CharsInBuf>0){(*Char)=Buffer[CircOut];if(CircOut<MaxBufLen-1)CircOut++;else CircOut=0;CharsInBuf--;Flag=0;}return Flag;}int SendChar(unsigned char Char){if((inp(comportaddr+5)&0x20)==0) return -1; outp(comportaddr,Char);return 0;}main(){int i,c;unsigned char InChar;Init_COM(COM232,COMINT,1200,8,1,0); while(1){if(kbhit()){if((InChar=getch())==27)break;else while(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)?printf("%c",InChar);}Restore();}接收程序:#include <>#include <>#include <>#include <>#include <>#include <>#define RXD 0 .);void putb(unsigned char ch).) {unsigned char ch;ch=inportb(portaddr+RXD); putb(ch);incount++; n");exit(1);}else{printf("The used port is :COM%d\n",ComNum); };Getportaddr(port); .#else#define __CPPARGS#endif#define SER_RBF 0#define SER_THR 0#define SER_IER 1#define SER_IIR 2#define SER_LCR 3#define SER_MCR 4#define SER_LSR 5#define SER_MSR 6#define SER_DLL 0#define SER_DLH 1#define SER_BAUD_1200 96#define SER_BAUD_2400 48#define SER_BAUD_9600 12#define SER_BAUD_19200 6#define SER_GP02 8#define COM_1 0x3F8#define COM_2 0x2F8 /*/ base port address of port 1*/ #define COM_3 0x3E8#define COM_4 0x2E8#define SER_STOP_1 0 /*/ 1 stop bit per character*/ #define SER_STOP_2 4 /*/ 2 stop bits per character*/ #define SER_BITS_5 0 /*/ send 5 bit characters*/#define SER_BITS_6 1 /*/ send 6 bit characters*/#define SER_BITS_7 2 /*/ send 7 bit characters*/#define SER_BITS_8 3 /*/ send 8 bit characters*/#define SER_PARITY_NONE 0 /*/ no parity*/#define SER_PARITY_ODD 8 /*/ odd parity*/#define SER_PARITY_EVEN 24 /*/ even parity*/#define SER_DIV_LATCH_ON 128 /*/ used to turn reg 0,1 into divisor latch*/ #define PIC_IMR 0x21 /*/ pic's interrupt mask reg.*/#define PIC_ICR 0x20 /*/ pic's interupt control reg.*/#define INT_SER_PORT_0 0x0C /*/ port 0 interrupt com 1 & 3*/#define INT_SER_PORT_1 0x0B /*/ port 0 interrupt com 2 & 4*/#define SERIAL_BUFF_SIZE 128 /*/ current size of circulating receivebuffer*/void interrupt far (*Old_Isr)(__CPPARGS); /*/ holds old com port interrupt handler*/char ser_buffer[SERIAL_BUFF_SIZE]; /*/ the receive buffer*/int ser_end = -1,ser_start=-1; /*/ indexes into receive buffer*/int ser_ch, char_ready=0; /*/ current character and ready flag*/int old_int_mask; /*/ the old interrupt mask on the PIC*/int open_port; /*/ the currently open port*/int serial_lock = 0; /*/ serial ISR semaphore so the buffer*//*/ isn't altered will it is being written*/ /*/ to by the ISR*//*-------------写串口-----------------*/ void interrupt far Serial_Isr(__CPPARGS){serial_lock = 1;ser_ch = inp(open_port + SER_RBF);if (++ser_end > SERIAL_BUFF_SIZE-1)ser_end = 0;ser_buffer[ser_end] = ser_ch;++char_ready;outp(PIC_ICR,0x20);serial_lock = 0;}int Ready_Serial(){return(char_ready);}/*--------------读串口--------------*/ int Serial_Read(){int ch;while(serial_lock){}if (ser_end != ser_start){if (++ser_start > SERIAL_BUFF_SIZE-1) ser_start = 0;ch = ser_buffer[ser_start];printf("%x",ch);if (char_ready > 0)--char_ready;return(ch);}elsereturn(0);}/*--------------写串口-----------------*/Serial_Write(char ch){while(!(inp(open_port + SER_LSR) & 0x20)){}asm clioutp(open_port + SER_THR, ch);asm sti}/*-----------初始化串口---------------*/Open_Serial(int port_base, int baud, int configuration) {open_port = port_base;disable();outp(port_base + SER_LCR, SER_DIV_LATCH_ON);outp(port_base + SER_DLL, baud);outp(port_base + SER_DLH, 0);outp(port_base + SER_LCR, configuration);outp(port_base + SER_MCR, SER_GP02);outp(port_base + SER_IER, 1);if (port_base == COM_1 || port_base==COM_3){Old_Isr = _dos_getvect(INT_SER_PORT_0);_dos_setvect(INT_SER_PORT_0, Serial_Isr);printf("\nOpening Communications Channel Com Port #1/3...\n"); }else{Old_Isr = _dos_getvect(INT_SER_PORT_1);_dos_setvect(INT_SER_PORT_1, Serial_Isr);printf("\nOpening Communications Channel Com Port #2/4...\n");}old_int_mask = inp(PIC_IMR);outp(PIC_IMR, (port_base==COM_1) (old_int_mask & 0xEF) : (old_int_mask & 0xF7 ));enable();}/*-------------关闭串口--------------*/Close_Serial(int port_base){outp(port_base + SER_MCR, 0);outp(port_base + SER_IER, 0);outp(PIC_IMR, old_int_mask );if (port_base == COM_1){_dos_setvect(INT_SER_PORT_0, Old_Isr);printf("\nClosing Communications Channel Com Port #1.\n"); }else{_dos_setvect(INT_SER_PORT_1, Old_Isr);printf("\nClosing Communications Channel Com Port #2.\n"); }}/*-------------发送应用----------------*/void main(int argc,char *argv[]){char ch,press;int done=0;FILE *fp;argc=2;//argv[1]="c:\\";if(argc<2){printf("\nUsage:display !!!");// exit(1);}if((fp=fopen(argv[1],"r+b"))==NULL){printf("cannot open the file\n");// exit(0);}fseek(fp, 0, SEEK_SET);Open_Serial(COM_1,SER_BAUD_9600,SER_PARITY_EVEN| SER_BITS_8 | SER_STOP_1); printf("com:1;bps:9600;parity:even;bits:8;stop bit:1");printf("press any key to begin sending");getch();//Serial_Write(''); //该语句可用于发送单个字符while(!done&&ch != EOF) //发送文件开始 {ch = fgetc(fp);//if(ch==EOF) Serial_Write(27);Serial_Write(ch);delay(30);if (kbhit()){press=getch();if (press==27){Serial_Write(27);done=1;}}}Close_Serial(COM_1);fclose(fp);}下面介绍最重要的MFC:CWnd:窗口,它是大多数“看得见的东西”的父类(Windows里几乎所有看得见的东西都是一个窗口,大窗口里有许多小窗口),比如视图CView、框架窗口CFrameWnd、工具条CToolBar、对话框CDialog、按钮CButton,etc;一个例外是菜单(CMenu)不是从窗口派生的。
c语言怎么写串口通信编程 -回复
c语言怎么写串口通信编程 -回复在C语言中进行串口通信编程,你需要了解串口的基本原理以及相关的函数和库。
串口通信是一种通过串行数据传输进行通信的方式,常用于嵌入式系统中与外部设备进行数据交互。
本文将以步骤的形式来介绍如何在C语言中进行串口通信编程。
步骤一:了解串口的基本原理在开始串口通信编程之前,你需要了解串口的基本原理。
串口是通过发送和接收数据位的序列来进行通信的。
串口通信需要考虑的一些参数包括波特率(即数据传输速率)、数据位数、校验位和停止位等。
波特率指的是每秒钟传输的位数,可以是常用的9600、19200、38400等。
步骤二:选择合适的串口库在C语言中,你可以选择使用合适的串口库来简化串口通信的编程工作。
常见的串口库包括Windows系统中的WinAPI、Linux系统中的termios库等。
选择库的时候,需根据你所使用的操作系统和开发环境进行选择。
步骤三:打开串口在开始使用串口进行通信之前,需要先打开串口。
使用串口库的函数,可以根据需要选择打开特定的串口,一般通过指定串口名称或者端口号来进行打开。
打开串口的函数可能返回一个文件描述符或者句柄,用于后续的读写操作。
步骤四:配置串口参数打开串口之后,需要进行串口参数的配置。
这包括波特率、数据位数、校验位和停止位等参数的设置。
一般通过调用相应的函数,将需要设置的参数传递给串口库,以完成参数的配置。
步骤五:读取串口数据配置完串口参数后,你可以开始读取串口数据。
通过调用读取函数,你可以从串口接收缓冲区中获取数据,并进一步进行处理。
读取函数可能会阻塞程序执行,直到有数据可读取为止。
步骤六:发送串口数据与读取串口数据相对应的是发送串口数据。
通过调用相应的发送函数,你可以将你要发送的数据写入串口发送缓冲区,等待发送。
发送函数可能会阻塞程序执行,直到数据成功发送。
步骤七:关闭串口在程序结束时,需要关闭已经打开的串口。
通过调用相应的函数,可以完成串口的关闭。
C语言实现串口通信
C语言实现串口通信在使用系统调用函数进行串口通信之前,需要打开串口设备并设置相关参数。
打开串口设备可以使用open(函数,设置串口参数可以使用termios结构体和tcsetattr(函数。
以下是一个简单的串口通信接收数据的示例代码:```c#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <unistd.h>#include <termios.h>int mainint fd; // 串口设备文件描述符char buff[255]; // 存储接收到的数据int len; // 接收到的数据长度//打开串口设备fd = open("/dev/ttyS0", O_RDONLY);if (fd < 0)perror("Failed to open serial port");return -1;}//设置串口参数struct termios options;tcgetattr(fd, &options);cfsetspeed(&options, B1200); // 设置波特率为1200 tcsetattr(fd, TCSANOW, &options);//接收数据while (1)len = read(fd, buff, sizeof(buff)); // 从串口读取数据if (len > 0)buff[len] = '\0'; // 将接收到的数据转为字符串printf("Received data: %s\n", buff);}}//关闭串口设备close(fd);return 0;```这段代码首先通过open(函数打开串口设备文件"/dev/ttyS0",然后使用tcgetattr(函数获取当前设置的串口参数,接着使用cfsetspeed(函数设置波特率为1200,最后使用tcsetattr(函数将设置好的串口参数写回。
c#上位机串口通信助手源代码详解
c#上位机串口通信助手源代码实例详解
一、功能
1软件打开时,自动检测有效COM端口
2软件打开时,自动复原到上次关闭时的状态
3不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开
4
5
6
7
8
扰
9
10
二、
三、
1
用
端口号:
数据位:
校验位:
发送(byte):tbSendCount接收(byte):tbReceivedCount
清空计数按钮:btnClearCount按16进制显示:cb16Display
接收区清空内容按钮:btnClearReceived保存数据按钮:btnSaveFile
接收数据框:tbReceivedData发送数据框:tbSendData
自动发送:cbAutomaticSend间隔时间:tbSpaceTime
按16进制发送:cb16Send发送区清空内容按钮:btnClearSend
2创建一个方法类
按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:
tbSendData.Text=tbSendDataStr;
}
}
//发送文本框键盘按键检测
privatevoidtbSendData_KeyPress(objectsender,KeyPressEventArgse) {
if(cb16Send.Checked)
{
//正则匹配
stringpattern="[0-9a-fA-F]|\b";//\b:退格键
if(m.Success)。
C语言串口通信-源代码
C语言串口通信-源代码#include#include#include#include#define COM232 0x2f8#define COMINT 0x0b#define MaxBufLen 500#define Port8259 0x20#define EofInt 0x20static 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);outp(ComPortAddr+1,0x01);disable();OldAsyncInt=getvect( IntVectNum );setvect( IntVectNum, AsyncInt );enable();maskb=inp(Port8259+1);if(IntVectNum==0x0c)outp(Port8259+1,maskb&0xef); else outp(Port8259+1,maskb&0xf7);}static void interrupt far AsyncInt(void){disable();if(CharsInBuf<maxbuflen)< p="">Buffer[CircIn]=inp(comportaddr);if(CircIn<="" p="">else CircIn=0;if(CircIn==CircOut) CircOut++;else CharsInBuf++;enable();outp(Port8259,EofInt);}void Restore(void){setvect(intvectnum,OldAsyncInt);outp(Port8259+1,maskb);}int GetCharInBuf(unsigned char *Char){int Flag;Flag=-1;if(CharsInBuf>0){(*Char)=Buffer[CircOut];if(CircOut<maxbuflen-1)circout++;< p="">else CircOut=0;CharsInBuf--;Flag=0;}return Flag;}int SendChar(unsigned char Char){if((inp(comportaddr+5)&0x20)==0) return -1; outp(comportaddr,Char);return 0;}main(){int i,c;unsigned char InChar;Init_COM(COM232,COMINT,1200,8,1,0);while(1){if(kbhit()){if((InChar=getch())==27)break;else while(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)printf("%c",InChar);}Restore();}接收程序:#include#include#include#include#include#include#define RXD 0 //接收#define TXD 0 //发送#define LSB 0 //波特率调节低8位#define MSB 1 //波特率调节高8位#define IER 1 // 中断起用寄存器#define IIR 2 //中断标识寄存器#define LCR 3 //线路控制寄存器#define MCR 4 //调制解调器控制寄存器#define LSR 5 //线路状态寄存器#define MSR 6 //调制解调器状态寄存器#define IERV 1#define OUT2 0x08#define ERTS 2#define EDTR 1#define EMPTY 0X20#define READY 0X30#define ICREG 0X20#define IMASKREG 0X21#define EOI 0X20#define WAITCOUNT 5000#define BUFFLEN 2048 //用于存储字符的数组的界#define ALTE 0X12#define ALTQ 0X10#define SER_BAUD_1200 96#define SER_BAUD_2400 48#define SER_BAUD_9600 0x0C#define SER_BAUD_19200 6#define SER_STOP_1 0 /*/ 1 stop bit per character*/#define SER_STOP_2 4 /*/ 2 stop bits per character*/#define SER_BITS_5 0 /*/ send 5 bit characters*/#define SER_BITS_6 1 /*/ send 6 bit characters*/#define SER_BITS_7 2 /*/ send 7 bit characters*/#define SER_BITS_8 3 /*/ send 8 bit characters*/#define SER_PARITY_NONE 0 /*/ no parity*/#define SER_PARITY_ODD 8 /*/ odd parity*/#define SER_PARITY_EVEN 24 /*/ even parity*/int port;int ComNum;unsigned portaddr;unsigned portf;unsigned int baudtable[]={0x180,0xc0,0x60,0x30,0x18,0x0c,0x06};unsigned char paritytable[]={0x08,0x18,0x00,0x28,0x38};unsigned char buffer[BUFFLEN];//recv bufint buffin=0;int buffout=0;int incount=0;int outcount=0;void interrupt(*vect_com)(...);void putb(unsigned char ch)//write a char to the recvbuf 将中断得到的数据写到缓冲区{int temp;temp=buffin;if(++buffin==BUFFLEN)buffin=0;if(buffin!=buffout){buffer[buffin]=ch;// printf("bufferin[%d]=%c",buffer[buffin]);// getch();}elsebuffin=temp;};unsigned char getb()//read a char from the recvbuf{if(buffout!=buffin){if(++buffout==BUFFLEN)buffout=0;//printf("bufferout[%d]=%c",buffout,buffer[buffout]);return(buffer[buffout]);}elsereturn(0xff);};/*unsigned char sender( unsigned char ch) {outportb(portaddr2+TXD,ch);printf("\nsender outportdata=%c\n",ch); outcount++;return(1);};*/void interrupt receiver(...){unsigned char ch;ch=inportb(portaddr+RXD);putb(ch);incount++; //记录接收了多少个数据。
51单片机的串口通信程序(C语言)
#include <reg52.h>#include<intrins.h>#include <stdio.h>#include <math.h>#define uchar unsigned char#define uint unsigned intsbit Key1 = P2^3;sbit Key2 = P2^2;sbit Key3 = P2^1;sbit Key4 = P2^0;sbit BELL = P3^6;sbit CONNECT = P3^7;unsigned int Key1_flag = 0;unsigned int Key2_flag = 0;unsigned int Key3_flag = 0;unsigned int Key4_flag = 0;unsigned char b;unsigned char code Num[21]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00, 0x10,0x89};unsigned char code Disdigit[4] = {0x7F,0xBF,0xDF,0xEF};unsigned char Disbuf[4];void delayms(uint t){uint i;while(t--){/* 对于11.0592M时钟,约延时1ms */for (i=0;i<125;i++){}}}//-----------------------------------------------------void SendData(uchar Dat){uchar i=0;SBUF = Dat;while (1){if(TI){TI=0;break;}}}void ScanKey(){if(Key1 == 0){delayms(100); if(Key1 == 0){Key1_flag = 1; Key2_flag = 0; Key3_flag = 0;Key4_flag = 0;Key1 = 1;}else;}if(Key2 == 0){delayms(100);if(Key2 == 0){Key2_flag = 1; Key1_flag = 0; Key3_flag = 0;Key4_flag = 0;Key2 = 1;}else;}if(Key3 == 0){delayms(50);if(Key3 == 0){Key3_flag = 1; Key1_flag = 0; Key2_flag = 0;Key4_flag = 0;Key3 = 1;}else;}if(Key4 == 0){delayms(50);if(Key4 == 0){Key4_flag = 1;Key1_flag = 0;Key2_flag = 0;Key3_flag = 0;Key4 = 1;}else;}else;}void KeyProc(){if(Key1_flag){TR1 = 1;SendData(0x55);Key1_flag = 0; }else if(Key2_flag){TR1 = 1;SendData(0x11); Key2_flag = 0;}else if(Key3_flag) {P1=0xff;BELL = 0;CONNECT = 1;Key3_flag = 0;}else if(Key4_flag){CONNECT = 0;BELL = 1;Key4_flag = 0;}else;}void Initdisplay(void){Disbuf[0] = 1;Disbuf[1] = 2;Disbuf[2] = 3;Disbuf[3] = 4;}void Display() //显示{unsigned int i = 0;unsigned int temp,count;temp = Disdigit[count]; P2 =temp;temp = Disbuf[count];temp = Num[temp];P0 =temp;count++;if (count==4)count=0;}void time0() interrupt 1 using 2 {Display();TH0 = (65535 - 2000)/256;TL0 = (65535 - 2000)%256;}void main(){Initdisplay();TMOD = 0x21;TH0 = (65535 - 2000)/256;TL0 = (65535 - 2000)%256;TR0 = 1;ET0 = 1;TH1 = 0xFD; //11.0592MTL1 = 0xFD;PCON&=0x80;TR1 = 1;ET1 = 1;SCON = 0x40; //串口方式REN = 1;PT1 = 0;PT0 = 1;EA = 1;while(1){ScanKey();KeyProc();if(RI){Disbuf[0] = 0;Disbuf[1] = 20;Disbuf[2] = SBUF>>4;Disbuf[3] = SBUF&0x0f;RI = 0;}else;}}51单片机串口通信C语言程序2**************************************************************; 平凡单片机工作室;ckss.asm;功能:反复向主机送AA和55两个数;主机使用一个串口调试软件设置19200,n,8,1***************************************************************/#include "reg51.h"#define uchar unsigned char#define uint unsigned int//延时程序//////////////////由Delay参数确定延迟时间*/void mDelay(unsigned int Delay){ unsigned int i;for(;Delay>0;Delay--){ for(i=0;i<124;i++){;}}}//////////////////// 主程序////////////////////void main(){ uchar OutDat; //定义输出变量TMOD=0x20; //TMOD=0TH1=0xf3; //12MHZ ,BPS:4800,N,8,1TL1=0xf3;PCON=0x80; //方式一TR1=1; //?????????????????????????????SCON=0x40; //串口通信控制寄存器模式一OutDat=0xaa; //向串口发送固定数据值for(;;) //循环程序{SBUF=OutDat;//发送数据for(;;){ if(TI) //发送中断位当发送停止位时置1,表示发送完成break;}mDelay(500);TI=0; //清零中断位OutDat=~OutDat; //显示内容按位取反}}。
串口调试助手VC源程序及编程详细过程
串口调试助手VC源程序及编程详细过程作者:龚建伟可以任意转载,注明作者和说明来自◆龚建伟技术主页◆目次:1.建立项目2.在项目中插入MSComm控件3.利用ClassWizard定义CMSComm类控制变量4.在对话框中添加控件5.添加串口事件消息处理函数OnComm()6.打开和设置串口参数7.发送数据如果你还没有下载源程序,又对本文有兴趣,请立即下载在众多网友的支持下,串口调试助手从2001年5月21日发布至今,短短一个月,在全国各地累计下载量近5000人次,在近200多个电子邮件中,20多人提供了使用测试意见,更有50多位朋友提出要串口调试助手的源代码,为了答谢谢朋友们的支持,公开推出我最初用VC控件MSComm编写串口通信程序的源代码,并写出详细的编程过程,姑且叫串口调试助手源程序V1.0或VC串口通讯源程序吧,我相信,如果你用VC编程,那么有了这个代码,就可以轻而易举地完成串口编程任务了。
(也许本文过于详细,高手就不用看)开始吧: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所示),现在要做的是用鼠标将此图标拖到对话框中,程序运行后,这个图标是看不到的。
C语言串口通信-源代码
#include <stdio.h>#include <dos.h>#include <conio.h>#include <string.h>#define COM232 0x2f8#define COMINT 0x0b#define MaxBufLen 500#define Port8259 0x20#define EofInt 0x20static 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);outp(ComPortAddr+1,0x01);disable();OldAsyncInt=getvect( IntVectNum );setvect( IntVectNum, AsyncInt );enable();maskb=inp(Port8259+1);if(IntVectNum==0x0c)outp(Port8259+1,maskb&0xef); else outp(Port8259+1,maskb&0xf7);}static void interrupt far AsyncInt(void){disable();if(CharsInBuf<MaxBufLen)Buffer[CircIn]=inp(comportaddr);if(CircIn<MaxBufLen-1) CircIn++;else CircIn=0;if(CircIn==CircOut) CircOut++;else CharsInBuf++;enable();outp(Port8259,EofInt);}void Restore(void){setvect(intvectnum,OldAsyncInt);outp(Port8259+1,maskb);}int GetCharInBuf(unsigned char *Char){int Flag;Flag=-1;if(CharsInBuf>0){(*Char)=Buffer[CircOut];if(CircOut<MaxBufLen-1)CircOut++;else CircOut=0;CharsInBuf--;Flag=0;}return Flag;}int SendChar(unsigned char Char){if((inp(comportaddr+5)&0x20)==0) return -1; outp(comportaddr,Char);return 0;}main(){int i,c;unsigned char InChar;Init_COM(COM232,COMINT,1200,8,1,0);while(1){if(kbhit()){if((InChar=getch())==27)break;else while(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)printf("%c",InChar);}Restore();}接收程序:#include <dos.h>#include <fstream.h>#include <conio.h>#include <stdio.h>#include <stdlib.h>#include <math.h>#define RXD 0 //接收#define TXD 0 //发送#define LSB 0 //波特率调节低8位#define MSB 1 //波特率调节高8位#define IER 1 // 中断起用寄存器#define IIR 2 //中断标识寄存器#define LCR 3 //线路控制寄存器#define MCR 4 //调制解调器控制寄存器#define LSR 5 //线路状态寄存器#define MSR 6 //调制解调器状态寄存器#define IERV 1#define OUT2 0x08#define ERTS 2#define EDTR 1#define EMPTY 0X20#define READY 0X30#define ICREG 0X20#define IMASKREG 0X21#define EOI 0X20#define WAITCOUNT 5000#define BUFFLEN 2048 //用于存储字符的数组的界#define ALTE 0X12#define ALTQ 0X10#define SER_BAUD_1200 96#define SER_BAUD_2400 48#define SER_BAUD_9600 0x0C#define SER_BAUD_19200 6#define SER_STOP_1 0 /*/ 1 stop bit per character*/#define SER_STOP_2 4 /*/ 2 stop bits per character*/#define SER_BITS_5 0 /*/ send 5 bit characters*/#define SER_BITS_6 1 /*/ send 6 bit characters*/#define SER_BITS_7 2 /*/ send 7 bit characters*/#define SER_BITS_8 3 /*/ send 8 bit characters*/#define SER_PARITY_NONE 0 /*/ no parity*/#define SER_PARITY_ODD 8 /*/ odd parity*/#define SER_PARITY_EVEN 24 /*/ even parity*/int port;int ComNum;unsigned portaddr;unsigned portf;unsigned int baudtable[]={0x180,0xc0,0x60,0x30,0x18,0x0c,0x06};unsigned char paritytable[]={0x08,0x18,0x00,0x28,0x38};unsigned char buffer[BUFFLEN];//recv bufint buffin=0;int buffout=0;int incount=0;int outcount=0;void interrupt(*vect_com)(...);void putb(unsigned char ch)//write a char to the recvbuf 将中断得到的数据写到缓冲区{int temp;temp=buffin;if(++buffin==BUFFLEN)buffin=0;if(buffin!=buffout){buffer[buffin]=ch;// printf("bufferin[%d]=%c",buffer[buffin]);// getch();}elsebuffin=temp;};unsigned char getb()//read a char from the recvbuf{if(buffout!=buffin){if(++buffout==BUFFLEN)buffout=0;//printf("bufferout[%d]=%c",buffout,buffer[buffout]);return(buffer[buffout]);}elsereturn(0xff);};/*unsigned char sender( unsigned char ch){outportb(portaddr2+TXD,ch);printf("\nsender outportdata=%c\n",ch);outcount++;return(1);};*/void interrupt receiver(...){unsigned char ch;ch=inportb(portaddr+RXD);putb(ch);incount++; //记录接收了多少个数据。
模拟串口的三种方法及C语言
模拟串口的三种方法及C语言模拟串口是软件中模拟实现串口通信的一种方法,它是在电脑上通过软件模拟两个串口之间的传输,用来测试、调试串口相关的应用程序。
本文将介绍三种常见的模拟串口的方法,并提供C语言代码示例。
1.使用虚拟串口软件虚拟串口软件是一种用于模拟串口通信的应用程序。
它创建了虚拟的串口设备,使其在电脑上模拟出真实的串口通信环境。
通过虚拟串口软件,可以实现串口的模拟收发数据,可以连接到串口测试工具、串口调试工具或者自己编写的串口通信程序上。
以下是一个使用虚拟串口软件模拟串口通信的C语言代码示例:```c#include <stdio.h>#include <windows.h>int mai//打开虚拟串口//检测串口是否成功打开printf("Error in opening serial port\n");return 1;}//进行串口通信操作,如发送、接收数据//关闭串口return 0;```在这个示例中,我们使用了Windows操作系统的函数`CreateFile`来打开一个虚拟串口,这里的串口名称是"COM1"。
然后可以调用相关函数进行串口通信操作,最后用`CloseHandle`函数关闭串口。
2.使用串口驱动模拟在一些情况下,可以通过修改电脑的串口驱动程序来模拟串口通信。
这种方法需要更深入的了解操作系统的底层机制,并进行驱动程序的开发和修改。
通过修改串口驱动程序,可以模拟出一个虚拟的串口设备,通过这个设备进行串口通信。
以下是一个简单的C语言代码示例,用于修改串口驱动程序来模拟串口通信:```c#include <stdio.h>#include <fcntl.h>#include <unistd.h>int maiint fd;//打开串口设备fd = open("/dev/ttyS0", O_RDWR);//检测串口是否成功打开if (fd < 0)printf("Error in opening serial port\n");return 1;}//进行串口通信操作,如发送、接收数据//关闭串口设备close(fd);return 0;```在这个示例中,我们使用了Linux操作系统的函数`open`来打开一个串口设备,这里的设备名称是"/dev/ttyS0"。
VC实现串口通信项目源码
VC实现串口通信项目源码以下是一个简单的串口通信项目的VC实现源码,包括了串口初始化、发送数据、接收数据等基本功能。
```#include <Windows.h>#include <stdio.h>#define BUFFER_SIZE 1024HANDLE hSerial;//初始化串口参数BOOL InitSerialPort//打开串口hSerial = CreateFile("\\\\.\\COM1", GENERIC_READ ,GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);if (hSerial == INVALID_HANDLE_VALUE)printf("Failed to open serial port\n");return FALSE;}//配置串口参数DCB dcbSerialParams = { 0 };dcbSerialParams.DCBlength = sizeof(dcbSerialParams); printf("Failed to get serial port state\n"); CloseHandle(hSerial);return FALSE;}dcbSerialParams.BaudRate = CBR_9600; // 波特率为9600 dcbSerialParams.ByteSize = 8; // 8位数据位dcbSerialParams.Parity = NOPARITY; // 无奇偶校验dcbSerialParams.StopBits = ONESTOPBIT;// 1位停止位printf("Failed to set serial port state\n"); CloseHandle(hSerial);return FALSE;}//设置超时操作CloseHandle(hSerial);return FALSE;}return TRUE;//发送数据BOOL SendData(const char* data)DWORD bytesWritten;if (!WriteFile(hSerial, data, strlen(data), &bytesWritten, NULL))printf("Failed to send data\n");CloseHandle(hSerial);return FALSE;}return TRUE;//接收数据BOOL ReceiveData(char* buffer, DWORD size)DWORD bytesRead;if (!ReadFile(hSerial, buffer, size, &bytesRead, NULL))printf("Failed to receive data\n");CloseHandle(hSerial);return FALSE;}return TRUE;if (!InitSerialPort()return 1;}char sendBuffer[BUFFER_SIZE];char receiveBuffer[BUFFER_SIZE];//发送数据printf("Enter data to send: ");gets_s(sendBuffer, BUFFER_SIZE);if (!SendData(sendBuffer))return 1;}//接收数据printf("Receiving data...\n");if (!ReceiveData(receiveBuffer, BUFFER_SIZE)) return 1;}printf("Received data: %s\n", receiveBuffer); CloseHandle(hSerial);```这个项目使用了Windows的串口通信API函数来实现串口的初始化、发送数据和接收数据操作。
c语言怎么写串口通信编程
c语言怎么写串口通信编程串口通信是一种广泛应用于嵌入式系统和电子设备之间的通信方式。
无论是嵌入式开发还是电子设备控制,串口通信都是常见的需求。
在C语言中,实现串口通信需要通过操作串口的硬件寄存器和使用相应的通信协议来实现数据的发送和接收。
本文将一步一步介绍如何使用C语言编写串口通信程序。
第一步:打开串口要开始串口通信,首先需要打开串口。
在C语言中,可以使用文件操作函数来打开串口设备。
通常,串口设备被命名为/dev/ttyS0,/dev/ttyS1等,具体名称取决于系统。
下面是一个打开串口设备的示例代码:cinclude <stdio.h>include <fcntl.h>include <termios.h>int open_serial_port(const char *port) {int fd = open(port, O_RDWR O_NOCTTYO_NDELAY);if (fd == -1) {perror("open_serial_port");return -1;}设置串口属性struct termios options;tcgetattr(fd, &options);cfmakeraw(&options);cfsetspeed(&options, B9600);tcsetattr(fd, TCSANOW, &options);return fd;}int main() {const char *port = "/dev/ttyS0";int fd = open_serial_port(port);if (fd == -1) {打开串口失败,处理错误return -1;}串口已打开,可以进行数据的读写操作return 0;}在上面的代码中,open_serial_port函数用于打开指定的串口设备并进行一些必要的设置。
C51单片机串口通讯通用模块代码(可用于操作系统串口通讯)
C51单片机串口通讯通用模块代码(可用于操作系统串口通讯)#include#include "UART1.h"#include "commdriver.h"//当前适用于C51//可以根据具体CPU型号,修改宏定义和串口初始化代码就可以#define CPU_XTAL 22118400 //CPU频率#define FUNCTION_NULL 0 //没有定义函数#define COM_TI TI //发送中断寄存器#define COM_TI0() {TI = 0;} //发送中断寄存器清零#define COM_TI1() {TI = 1;} //发送中断寄存器置一( 强行置一触发发送中断)#define COM_TI_SBUF(dat) {SBUF = dat;} //发送数据到硬件缓冲区#define COM_TI_End() {return;} //发送结束处理函数#define COM_RI RI //接收中断寄存器#define COM_RI0() {RI = 0;} //接收中断寄存器清零#define COM_RI1() {RI = 1;} //接收中断寄存器置一#define COM_RI_SBUF(dat) {dat = SBUF;} //提取接收硬件缓冲区数据#define COM_TI_FLAG COM_TI //发送中断标志寄存器(非中断发送方式使用)#define COM_TI_FLAG0() COM_TI0() //发送中断标志寄存器清零(非中断发送方式使用)void (*COM1RevEvent)(unsigned char dat); //数据接收事件#define LenTxBuf 30 //发送缓冲区长度#define LenRxBuf 1 //接收缓冲区长度volatile unsigned char TxBuf1[LenTxBuf],RxBuf1[LenRxBuf]; //收发缓冲区实体volatile unsigned char *inTxBuf1,*outTxBuf1,*inRxBuf1,*outRxBuf1; //收发缓冲区读写指针volatile unsigned char TIflag1=1;//Note:It must be 1. //发送缓冲区为空标志//*********************#define _TxBuf TxBuf1#define _RxBuf RxBuf1#define _inTxBuf inTxBuf1#define _outTxBuf outTxBuf1#define _inRxBuf inRxBuf1#define _outRxBuf outRxBuf1#define _TIflag TIflag1/*************函数声明****************/#define _COMRevEvent COM1RevEvent //串口接收事件#define _USART_IRQ void USART1_IRQHandler(void) interrupt 4 //串口中断服务程序#define _COM_Buffer_Init void COM1_Buffer_Init(void) //串口缓冲区初始化#define _COM_Open void COM1_Open(unsigned int baudrate,void (*revevent)(unsigned char dat)) // 串口初始化#define _COM_Close void COM1_Close(void) //关闭串口#define _COM_GetOneByte unsigned charCOM1_GetOneByte(unsigned char *ch) //获取一个字节#define _COM_GetPChar unsigned char COM1_GetPChar(unsigned char *ch,unsigned char len) //获取指定长度字节数组#define _COM_RxByte unsigned char COM1_RxByte(void) //获取接收字节个数//********缓冲区中断方式发送(安全性高)#define _COM_SendOneByte unsigned char COM1_SendOneByte(unsigned char one_byte) // 发送一个字节#define _COM_SendPChar void COM1_SendPChar(unsigned char *P,unsigned char Len) //发送定长字节数组#define _COM_SendString void COM1_SendString(unsigned char *P) //发送字符串//********非缓冲区中断方式发送#define _COM_PrintOneByte void COM1_PrintOneByte(unsigned char c) // 发送一个字节#define _COM_PrintPChar void COM1_PrintPChar(unsigned char *buf,unsigned int len) //发送定长字节数组#define _COM_PrintString void COM1_PrintString(unsigned char *P) //发送字符串//*************内部引用模型函数(外部不关心,移植时修改后面函数名,要与上面对应的外部声明的函数名一致)*******************#define COM_GetOneByte_(ptr) COM1_GetOneByte(ptr) //与上面获取一个字节的函数对应#define COM_SendOneByte_(dat) COM1_SendOneByte(dat) //与上面发送一个字节的函数对应#define COM_PrintOneByte_(dat) COM1_PrintOneByte(dat) //与上面发送一个字节的函数对应//*********************函数模型定义区(不需要修改)*****************/****************************函数模型:void USART_IRQHandler(void)函数功能:串口中断服务程序入口参数:无返回值:无修改者:修改时间:修改内容简要:***************************/_USART_IRQ //串口1中断{volatile unsigned char *t;if(COM_RI){COM_RI0(); //清接收标记if(_COMRevEvent != FUNCTION_NULL) //自定义接收事件{COM_RI_SBUF(*_inRxBuf);_COMRevEvent(*_inRxBuf);}else{t = _inRxBuf;t++;if(t == (_RxBuf + LenRxBuf)) t = _RxBuf;if(t != _outRxBuf) //RxBuf No Full{COM_RI_SBUF(*_inRxBuf);_inRxBuf = t;}}}if(COM_TI){COM_TI0();if(_inTxBuf == _outTxBuf) {_TIflag = 1;COM_TI_End();};//TxBuf1 EmptyCOM_TI_SBUF(*_outTxBuf); _outTxBuf++;if(_outTxBuf == (_TxBuf+LenTxBuf)) _outTxBuf = _TxBuf;}}/****************************函数模型:void COM1_Buffer_Init(void)函数功能:串口1缓冲区初始化入口参数:无返回值:无修改者:修改时间:修改内容简要:***************************/_COM_Buffer_Init{_inTxBuf = _TxBuf;_outTxBuf = _TxBuf;_inRxBuf = _RxBuf;_outRxBuf = _RxBuf;}/****************************函数模型:void COM_Open(unsigned int baudrate,void (*revevent)(unsigned char dat))函数功能:系统串口初始化入口参数: unsigned int baudrate:串口波特率返回值:无修改者:修改时间:修改内容简要:***************************/_COM_Open{//定时器1做波特率发生器TI = 0; /* clear transmit interrupt */TR1 = 0; /* stop timer 1 */ET1 = 0; /* disable timer 1 interrupt */PCON |= 0x80; /* 0x80=SMOD: set serial baudrate doubler */ TMOD &= ~0xF0; /* clear timer 1 mode bits */TMOD |= 0x20; /* put timer 1 into MODE 2 */TH1 = (unsigned char) (256 - (CPU_XTAL / (16L * 12L * baudrate)));TR1 = 1; /* start timer 1 *///设置串口1模式SM0 = 0; SM1 = 1; /* serial port MODE 1 */SM2 = 0;REN = 1; /* enable serial receiver */RI = 0; /* clear receiver interrupt */TI = 0; /* clear transmit interrupt */ES = 1; /* enable serial interrupts */PS = 1; /* set serial interrupts to low priority */_COMRevEvent = revevent;}/****************************函数模型:void COM1_Close(void)函数功能:关闭系统串口入口参数:无返回值:无修改者:修改时间:修改内容简要:***************************/_COM_Close{}/****************************函数模型:unsigned char COM1_GetOneByte(unsigned char *ch)函数功能:获取一个字节入口参数:unsigned char *ch:接收字节指针返回值: unsigned char *ch:接收字节指针unsigned char :获取状态;0:成功,1:失败(缓冲区为空)修改者:修改时间:修改内容简要:***************************/_COM_GetOneByte{if(_inRxBuf == _outRxBuf) {return 0;}; //RxBuf Empty*ch = *_outRxBuf; _outRxBuf++;if(_outRxBuf==_RxBuf+LenRxBuf) _outRxBuf = _RxBuf;return 1;}/****************************函数模型:unsigned char COM_GetPChar(unsigned char *ch,unsigned char len)函数功能:获取指定长度字节数组入口参数: unsigned char *ch:接收字节数组指针unsigned char len:接收字节个数返回值: unsigned char *ch:接收字节数组指针unsigned char:实际接收字节个数修改者:修改时间:修改内容简要:***************************/_COM_GetPChar{unsigned char i = 0;do{len--;if(!COM_GetOneByte_(ch)) break;i++;ch++;}while(len);return i;}/****************************函数模型:unsigned char COM_RxByte(void)函数功能:获取接收缓冲区有效字节个数入口参数:无返回值: unsigned char:接收缓冲区有效字节个数修改者:修改时间:修改内容简要:***************************/_COM_RxByte{if(_inRxBuf>=_outRxBuf) return (_inRxBuf-_outRxBuf);else return LenRxBuf-(_outRxBuf-_inRxBuf);}/****************************函数模型:unsigned char COM_SendOneByte(unsigned char one_byte)函数功能:发送一个字节入口参数: unsigned char one_byte:发送的字节返回值:unsigned char:发送状态,0:成功,1:失败(缓冲区满)修改者:修改时间:修改内容简要:***************************/_COM_SendOneByte{volatile unsigned char *t;if(_TIflag){_TIflag = 0;COM_TI1();}t = _inTxBuf;t++;if(t == _TxBuf + LenTxBuf) t = _TxBuf;if(t == _outTxBuf) {return 1;};//TxBuf Full*_inTxBuf = one_byte;_inTxBuf = t;return 0;}/****************************函数模型:void COM_SendPChar(unsigned char *P,unsigned char Len)函数功能:发送定长字节数组入口参数: unsigned char *P:字节数组指针unsigned char Len:发送长度返回值:无修改者:修改时间:修改内容简要:***************************/_COM_SendPChar{while(Len){//while(COM1_SendOneByte(*P)); //发送失败,继续发送,知道发送成功COM_SendOneByte_(*P);P++;Len--;}}/****************************函数模型:void COM_SendString(unsigned char *P)函数功能:发送字符串入口参数: unsigned char *P:字符串指针返回值:无修改者:修改时间:修改内容简要:***************************/_COM_SendString{while(*P){COM_SendOneByte_(*P);P++;}}//**************** 非缓冲区中断方式发送/****************************函数模型:void COM_PrintOneByte(unsigned char c)函数功能:发送一个字节入口参数: unsigned char one_byte:发送的字节返回值:无修改者:修改时间:修改内容简要:***************************/_COM_PrintOneByte{COM_TI_FLAG0();COM_TI_SBUF(c); //发送数据while(!COM_TI_FLAG) ; //等待发送结束}/****************************函数模型:void COM_PrintPChar(unsigned char *buf,unsigned int len)函数功能:发送定长字节数组入口参数: unsigned char *P:字节数组指针unsigned char Len:发送长度返回值:无修改者:修改时间:修改内容简要:***************************/_COM_PrintPChar{while(len){COM_PrintOneByte_(*buf);buf ++;len--;}}/****************************函数模型:void COM_PrintString(unsigned char *P) 函数功能:发送字符串入口参数: unsigned char *P:字符串指针返回值:无修改者:修改时间:修改内容简要:***************************/_COM_PrintString{while(*P){COM_PrintOneByte_(*P);P++;}}。
经典串口调试助手源程序及串口通信设置
经典串口调试助手源程序及串口通信设置串口调试助手是一种用于串口通信调试的工具,它可以通过串口与外部设备进行数据的读写和处理,常用于单片机、嵌入式系统、电子设备等领域的开发调试中。
经典串口调试助手源程序经典串口调试助手是一款经典的串口调试工具,其源程序使用C语言编写,提供了丰富的功能和易于使用的界面,被广泛应用于各种领域的开发调试中。
该工具可以在Windows操作系统中运行,并支持多种串口通信协议,包括RS232、RS485、RS422等。
以下是经典串口调试助手部分源程序的示例:```c// 打开串口HANDLE OpenSerialPort(const char* portName){ HANDLE hCom; hCom = CreateFile(portName, // 串口名称GENERIC_READ | GENERIC_WRITE, // 读写访问0,// 无共享NULL,// 安全描述符OPEN_EXISTING,// 打开方式FILE_ATTRIBUTE_NORMAL, // 文件属性NULL); // 文件模板if (hCom ==INVALID_HANDLE_VALUE) // 判断是否打开成功{ return NULL; } return hCom;}// 发送数据int SendData(HANDLE hCom, const char* data, int len){ DWORD writeSize; if (!WriteFile(hCom, data, len, &writeSize, NULL)) // 写入数据{ return -1; } return writeSize;}// 接收数据int ReceiveData(HANDLE hCom, char* data, int len){ DWORD readSize; if (!ReadFile(hCom, data, len,&readSize, NULL)) // 读取数据{ return -1; } return readSize;}// 关闭串口int CloseSerialPort(HANDLE hCom){ if(!CloseHandle(hCom)) // 关闭句柄{ return-1; } return 0;}```上述函数实现了打开串口、发送数据、接收数据和关闭串口等基本功能,可以作为串口通信的底层驱动实现。
Comassistant串口助手详解和源代码分析
到目前为止还不能在接收编辑框中看到数据,因为我们还没有打开串口,但运行程序不应该有任何错误, 不然,你肯定哪儿没看仔细,因为我是打开 VC6 对照着做一步写一行的,运行试试。没错吧?那么做下一 步: 6.打开串口和设置串口参数 码: // TODO: Add extra initialization here if(m_ctrlComm.GetPortOpen()) m_ctrlComm.SetPortOpen(FALSE); m_ctrlComm.SetCommPort(1); //选择 com1 if( !m_ctrlComm.GetPortOpen()) m_ctrlComm.SetPortOpen(TRUE);//打开串口 else AfxMessageBox("cannot open serial port"); m_ctrlComm.SetSettings("9600,n,8,1"); //波特率 9600,无校验,8 个数据位,1 个停止位 m_ctrlComm.SetInputModel(1); //1:表示以二进制方式检取数据 m_ctrlComm.SetRThreshold(1); //参数 1 表示每当串口接收缓冲区中有多于或等于 1 个字符时将引发一个接收数据的 OnComm 事件 m_ctrlComm.SetInputLen(0); //设置当前接收区数据长度为 0 m_ctrlComm.GetInput();//先预读缓冲区以清除残留数据 现在你可以试试程序了,将串口线接好后(不会接?去看看我写的串口接线基本方法),打开串口调试助 手,并将串口设在 com2,选上自动发送,也可以等会手动发送。再执行你编写的程序,接收框里应该有数 据显示了。 7.发送数据 先为发送按钮添加一个单击消息即 BN_CLICKED 处理函数,打开 ClassWizard->Message 你可以在你需要的时候打开串口, 例如在程序中做一个开始按钮, 在该按钮
qt串口通信c语言代码
qt串口通信c语言代码
引言概述:
QT串口通信是一种基于C语言的编程技术,它可以实现计算机与外部设备之间的数据交互。
本文将从五个大点出发,详细阐述QT串口通信的C语言代码实现。
正文内容:
1. 串口通信的基本原理
1.1 串口通信的定义和作用
1.2 串口通信的工作原理
1.3 串口通信的数据传输方式
2. QT串口通信的C语言代码实现
2.1 QT串口通信的环境搭建
2.2 QT串口通信的代码编写
2.3 QT串口通信的数据收发处理
3. QT串口通信的常见问题与解决方法
3.1 串口通信的波特率设置问题
3.2 数据传输的校验与校验位设置问题
3.3 数据的发送与接收缓冲区处理问题
4. QT串口通信的扩展功能
4.1 串口通信的多线程处理
4.2 串口通信的数据转换与解析
4.3 串口通信的错误处理与异常情况处理
5. QT串口通信的应用实例
5.1 串口通信在嵌入式系统中的应用
5.2 串口通信在数据采集与监控系统中的应用
5.3 串口通信在机器人控制系统中的应用
总结:
通过本文的阐述,我们了解了QT串口通信的C语言代码实现。
首先,我们介绍了串口通信的基本原理,包括定义和作用、工作原理以及数据传输方式。
然后,我们详细讲解了QT串口通信的C语言代码实现,包括环境搭建、代码编写和数据收发处理。
接着,我们列举了一些常见问题,并提供了解决方法。
此外,我们还介绍了QT串口通信的扩展功能和应用实例,展示了其在不同领域的应用前景。
通过学习和实践,我们可以更好地掌握QT串口通信的C语言代码编写技巧,为实际应用提供有力支持。
VC串口通信API程序代码
用API来实现串口通信其实不是很难,关于串口操作的函数在MSDN中都可以找到,大致的过程是:1.用CreateFile()函数创建串口2.用SetupComm()函数分配串口的输入和输出缓冲区的大小,当然也可以不设置,系统会默认的分配1024和512字节作为输入和输出缓冲区的大小3.用BuildCommDCB或者SetCommState函数来设置串口通信的相关参数,如波特率、奇偶校验、数据位、停止位以及线路检测等。
4.用WriteFile()函数向串口发送数据5.Windows到WM_COMMNOTIFY消息的时候,用ReadFile()函数从串口读取数据我这里有一个示例程序,功能不是很强,但是学习串口API编程还是可以的:unit Unit1;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls;constWM_COMMNOTIFY = WM_USER + 100; // 通讯消息typeTForm1 = class(TForm)StatusBar1: TStatusBar;Memo1: TMemo;Memo2: TMemo;Label1: TLabel;Label2: TLabel;GroupBox1: TGroupBox;Label3: TLabel;Label4: TLabel;Label5: TLabel;Label6: TLabel;ComboBox4: TComboBox;ComboBox3: TComboBox;ComboBox2: TComboBox;ComboBox1: TComboBox;Label7: TLabel;ComboBox5: TComboBox;btnOpenCom: TButton;btnSendData: TButton;btnReceiveData: TButton;btnCloseCom: TButton;procedure btnOpenComClick(Sender: TObject);procedure FormCreate(Sender: TObject);procedure btnCloseComClick(Sender: TObject);procedure btnSendDataClick(Sender: TObject);procedure btnReceiveDataClick(Sender: TObject);private{ Private declarations }procedure WMCOMMNOTIFY(var Message :TMessage);message WM_COMMNOTIFY;public{ Public declarations }end;varForm1: TForm1;implementation{$R *.dfm}varCommHandle:THandle;PostEvent:THandle;ReadOs : Toverlapped;Connected:Boolean;Receive :Boolean;ReceiveData : Dword;procedure AddToMemo(Str:PChar;Len:Dword); // 接收的数据送入显示区Memo2 begin//设置接收后的字符串为NULL终止str[Len]:=#0;Form1.Memo2.Text:=Form1.Memo2.Text+StrPas(str);end;procedure CommWatch(Ptr:Pointer);stdcall; // 通讯监视线程vardwEvtMask,dwTranser : Dword;PostMsgFlag: Boolean;overlapped : Toverlapped;beginReceive :=True;FillChar(overlapped,SizeOf(overlapped),0);overlapped.hEvent :=CreateEvent(nil,True,False,nil); // 创建重叠读事件对象if overlapped.hEvent=null thenbeginMessageBox(0,'overlapped.Event Create Error !','Notice',MB_OK);Exit;end;//进入串口监视状态,直到全局变量Receive置为False停止while(Receive) dobegindwEvtMask:=0;// 等待串口事件发生if not WaitCommEvent(CommHandle,dwEvtMask,@overlapped) thenbeginif ERROR_IO_PENDING=GetLastError thenGetOverLappedResult(CommHandle,overlapped,dwTranser,True)end;//串口读事件发布消息if ((dwEvtMask and EV_RXCHAR)=EV_RXCHAR) thenbegin// 等待允许传递WM_COMMNOTIFY通讯消息WaitForSingleObject(Postevent,INFINITE);// 处理WM_COMMNOTIFY消息时不再发送WM_COMMNOTIFY消息ResetEvent(PostEvent);// 传递WM_COMMNOTIFY通讯消息,告知主线程调用读串口的过程PostMsgFlag:=PostMessage(Form1.Handle,WM_COMMNOTIFY,CommHandle,0);if (not PostMsgFlag) thenbeginMessageBox(0,'PostMessage Error !','Notice',MB_OK);Exit;end;end;end;CloseHandle(overlapped.hEvent); // 关闭重叠读事件对象end;procedure TForm1.WMCOMMNOTIFY(var Message :TMessage); // 消息处理函数varCommState : ComStat;dwNumberOfBytesRead : Dword;ErrorFlag : Dword;InputBuffer : Array [0..1024] of Char;beginif not ClearCommError(CommHandle,ErrorFlag,@CommState) thenbeginMessageBox(0,'ClearCommError !','Notice',MB_OK);PurgeComm(CommHandle,Purge_Rxabort or Purge_Rxclear);Exit;end;if CommState.cbInQue>0 thenbeginfillchar(InputBuffer,CommState.cbInQue,#0);// 接收通讯数据if (not ReadFile( CommHandle,InputBuffer,CommState.cbInQue,dwNumberOfBytesRead,@ReadOs )) thenbeginErrorFlag := GetLastError();if (ErrorFlag <> 0) and (ErrorFlag <> ERROR_IO_PENDING) thenbeginMessageBox(0,'ReadFile Error!','Notice',MB_OK);Receive :=False;CloseHandle(ReadOs.hEvent);CloseHandle(PostEvent);CloseHandle(CommHandle);Exit;endelse beginWaitForSingleObject(CommHandle,INFINITE); // 等待操作完成GetOverlappedResult(CommHandle,ReadOs,dwNumberOfBytesRead,False);end;end;if dwNumberOfBytesRead>0 thenbeginReadOs.Offset :=ReadOs.Offset+dwNumberOfBytesRead;ReceiveData := ReadOs.Offset;// 处理接收的数据AddToMemo(InputBuffer,dwNumberOfBytesRead);end;end;// 允许发送下一个WM_COMMNOTIFY消息SetEvent(PostEvent);end;procedure TForm1.btnOpenComClick(Sender: TObject);varCommTimeOut : TCOMMTIMEOUTS;DCB : TDCB;beginStatusBar1.SimpleText := '连接中...';//发送消息的句柄PostEvent:=CreateEvent(nil,True,True,nil);if PostEvent=null thenbeginMessageBox(0,'CreateEvent Error!','Notice',MB_OK);StatusBar1.SimpleText := '串口打开失败';Exit;end;//Overlapped Read建立句柄ReadOs.hEvent :=CreateEvent(nil,true,False,nil);if ReadOs.hEvent=null thenbeginMessageBox(0,'CreateEvent Error!','Notice',MB_OK);CloseHandle(PostEvent);StatusBar1.SimpleText := '串口打开失败';Exit;end;//建立串口句柄CommHandle := CreateFile(PChar(ComboBox1.Text),GENERIC_WRITE or GENERIC_READ,0,nil,OPEN_EXISTING,FILE_FLAG_OVERLAPPED or FILE_ATTRIBUTE_NORMAL,0);if CommHandle = INVALID_HANDLE_VALUE thenbeginCloseHandle(PostEvent);CloseHandle(ReadOs.hEvent);MessageBox(0,'串口打开失败!','Notice',MB_OK);StatusBar1.SimpleText := '串口打开失败';Exit;end;StatusBar1.SimpleText := '已同端口'+ ComboBox1.Text + ' 连接!';//设置超时CommTimeOut.ReadIntervalTimeout := MAXDWORD;CommTimeOut.ReadTotalTimeoutMultiplier := 0;CommTimeOut.ReadTotalTimeoutConstant := 0;SetCommTimeouts(CommHandle, CommTimeOut);//设置读写缓存SetupComm(CommHandle,4096,1024);//对串口进行指定配置GetCommState(CommHandle,DCB);DCB.BaudRate := StrToInt(ComboBox2.Text);DCB.ByteSize := StrToInt(ComboBox3.Text);DCB.Parity := ComboBox4.ItemIndex;;DCB.StopBits := ComboBox5.ItemIndex;Connected := SetCommState(CommHandle, DCB);//关系串口的读事件if (not SetCommMask(CommHandle,EV_RXCHAR)) thenbeginMessageBox(0,'SetCommMask Error !','Notice',MB_OK);Exit;end;if (Connected) thenbeginbtnOpenCom.Enabled :=False;endelse beginCloseHandle(CommHandle);StatusBar1.SimpleText := '设置串口失败';end;end;procedure TForm1.FormCreate(Sender: TObject);beginConnected:=False;ComboBox1.ItemIndex:=0;ComboBox2.ItemIndex:=0;ComboBox3.ItemIndex:=4;ComboBox4.ItemIndex:=0;ComboBox5.ItemIndex:=0;end;procedure TForm1.btnCloseComClick(Sender: TObject);beginif not Connected thenbeginStatusBar1.SimpleText := '未打开串口';Exit;end;Receive :=False;//取消事件监视,此时监视线程中的WaitCommEvent将返回SetCommMask(CommHandle,0);//等待监视线程结束WaitForSingleObject(PostEvent,INFINITE);//关闭事件句柄CloseHandle(PostEvent);//停止发送和接收数据,并清除发送和接收缓冲区PurgeComm(CommHandle,PURGE_TXABORT or PURGE_RXABORT or PURGE_TXCLEAR or PURGE_RXCLEAR);//关闭其他的句柄CloseHandle(ReadOs.hEvent);CloseHandle(CommHandle);btnOpenCom.Enabled :=True;Connected:=False;StatusBar1.SimpleText := '串口已经关闭';end;procedure TForm1.btnSendDataClick(Sender: TObject);varStr:String;i:Integer;writeoverlapped:TOverlapped;ByteToWrite,BytesWritten,AllBytesWritten:DWORD;ErrorCode,ErrorFlag:DWORD;CommStat:COMSTAT;beginif not Connected thenbeginStatusBar1.SimpleText := '未打开串口';Exit;end;if (Memo1.GetTextLen=0) thenbeginStatusBar1.SimpleText := '缓冲区为空';Exit;end;AllBytesWritten:=0;for i:=0 to memo1.Lines.Count-1 dobeginStr:=memo1.Lines[i];ByteToWrite:=length(Str);if ByteToWrite=0 then continue;tryStatusBar1.SimpleText := '正在发送数据';//初始化一步读写结构FillChar(writeoverlapped,Sizeof(writeoverlapped),0);//避免贡献资源冲突writeoverlapped.hEvent:=CreateEvent(nil,True,False,nil);//发送数据if not WriteFile(Commhandle,Str[1],ByteToWrite,BytesWritten,@writeoverlapped) then beginErrorCode:=GetLastError;if ErrorCode<>0 thenbeginif ErrorCode=ERROR_IO_PENDING thenbeginStatusBar1.SimpleText := '端口忙,正在等待...';while not GetOverlappedResult(Commhandle,writeoverlapped,BytesWritten,True) dobeginErrorCode:=GetLastError;if ErrorCode=ERROR_IO_PENDING thencontinueelse beginClearCommError(Commhandle,ErrorFlag,@CommStat);showmessage('发送数据出错');CloseHandle(WriteOverlapped.hEvent);CloseHandle(Commhandle);btnOpenCom.Enabled :=True;Exit;end;end;AllBytesWritten:=AllBytesWritten+BytesWritten;endelse beginClearCommError(Commhandle,ErrorFlag,@CommStat);showmessage('发送数据出错');CloseHandle(WriteOverlapped.hEvent);Receive :=False;CloseHandle(Commhandle);CloseHandle(PostEvent);btnOpenCom.Enabled :=True;Exit;end;end;end;finallyCloseHandle(writeoverlapped.hEvent);end;end;StatusBar1.SimpleText:='已经发送了Byte个数:'+IntToStr(ALLBytesWritten); end;procedure TForm1.btnReceiveDataClick(Sender: TObject);varcom_thread: Thandle;ThreadID:DWORD;beginif not connected thenbeginStatusBar1.SimpleText := '未打开串口';Exit;end;ReceiveData :=0;Memo2.Clear;FillChar(ReadOs,SizeOf(ReadOs),0);ReadOs.Offset := 0;ReadOs.OffsetHigh := 0;// 建立通信监视线程Com_Thread:=CreateThread(nil,0,@CommWatch,nil,0,ThreadID);if (Com_Thread=0) thenMessageBox(Handle,'No CreateThread!',nil,mb_OK);//设置DTR信号线EscapeCommFunction(Commhandle,SETDTR);StatusBar1.SimpleText := '正在接收数据...';end;end.。
c上位机串口通信助手源代码详解
c# 上位机串口通信助手源代码实例详解功能1软件打开时,自动检测有效COM 端口2软件打开时,自动复原到上次关闭时的状态3不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开4可统计接收字节和发送字节的个数5接收数据可按16 进制数据和非16 进制数据进行整体转换6可将接收到数据进行保存7可设置自动发送,发送时间可进行实时更改8可按字符串、16 进制字节、文件方式进行发送,字符串和16 进制字节可分别进行存储,内容互不干扰9按16进制发送时,可自动校验格式,不会输错10可清空发送或接收区域的数据使用工具Visual Studio2015程序详解1 界面创建用winform 创建如图1所示界面,控件名字分别为:2创建一个方法类按Ctrl+shift+A 快捷键创建一个类,名字叫 Methods ,代码为:端口号:cbxCOMPort 波特率:cbxBaudRate 数据位:cbxDataBits 校验位:Iabel5发送(byte ) : tbSendCount 清空计数按钮:bt nClearCou nt 接收区清空内容按钮:bt nClearReceived接收数据框:tbReceivedData自动发送:cbAutomaticSe nd按16进制发送:cb16Send停止位:cbxStopBits打开串口按钮:bt nOpe nCom 接收(byte ): tbReceivedCount 按16进制显示:cb16Display 保存数据按钮:bt nSaveFile发送数据框:tbSe ndData间隔时间:tbSpaceTime发送区清空内容按钮:bt nClearSe nd发送按钮:btn Se nd图1using System; usi ngusi ngusi ngif=());else();oStri ng();} catch ( Exception ex){return ;}}闭);( "串口无效或已被占用!","错误提示");return ;}DisplayPortState( PortState .打开);}public Form1(){In itializeComp onen t();}oStri ng()); else=3;"cbxStopBits" ].ToStri ng());else =0;一)#en dregi on#region列岀奇偶校验位无“);#regio nCOM 口重新加载清除当前串口号中的所有串口名称if ( "cbxCOMPort") && "cbxCOMPort"].ToString())) ="cbxCOMPort"].ToStri ng());else =0; #en dregi on#regi on初始化计数器="0" ;「 true ; "0"; true ;#en dregi on#en dregi on #regio n 列岀停止位if ( "cbxStopBits"))#regi on初始化当前时间"cbxDataBits" ].ToStri ng());奇校验"); 偶校验");#en dregi on#en dregi on#regi on初始化按16进制显示状态if ( "cb16Display" ) && ht[ "cb16Display" ].ToString()== = true ; else | = false ;#en dregi on#regi on初始化按16进制发送状态if ( "cb16Send") && ht[ "cb16Send"].ToString() == "True" = true ;else = false ;#en dregi on #region初始化发送区文本|_if ("tbSendData16" ) && ( "tbSendDataStr")){tbSendData16 = ht[ "tbSendData16" ].ToString(); tbSendDataStr = ht["tbSendDataStr" ].ToString();if=ht["tbSendData16" ].ToString();|else=ht["tbSendDataStr" ].ToString(); }#en dregi on(); }开);}catch ( Exception ){闭);catch ( Exception )#regi on初始化串口状态} {elseif (!isSetProperty)开);"1000";"True"){"关闭串口时发生错误",“错误提示");(}}}oStri ng();}}}|* *" ;if ()=={stri ng fName =;using ( FileStream fs = (fName,) {(),0,;}}}}}需要源代码或有疑问的C#爱好者们,欢迎加入C#技术交流群(),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ComboBox_InsertString(hwndCombo1,-1,TEXT("COM3")); ComboBox_InsertString(hwndCombo1,-1,TEXT("COM4")); ComboBox_InsertString(hwndCombo1,-1,TEXT("COM5")); ComboBox_SetCurSel(hwndCombo1,0); void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime); SetTimer(hwnd,1,1000,TimerProc); return TRUE; } /*监视串口错误时使用的函数*/ bool ProcessErrorMessage(char* ErrorText) { char *Temp = new char[200]; LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf,
0, NULL ); sprintf(Temp, "WARNING: %s Failed with the following error: \n%s\nPort: %d\n", (char*)ErrorText, lpMsgBuf, "com2"); MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP); LocalFree(lpMsgBuf); delete[] Temp; return true;
原因 { DWORD dwError = 0; DWORD BytesRead = 0; ClearCommError(hComm, &dwError, &comstat); return comstat.cbInQue; //返回 buff 中数据量 } /*串口数据接收 读取函数*/ void ReceiveChar() { BOOL bRead = TRUE; BOOL bResult = TRUE; DWORD dwError = 0; DWORD BytesRead = 0; char i=0,n; char RXBuff; j=0; while (i-n) { n=i; Sleep(10); bResult = ClearCommError(hComm, &dwError, &comstat); i=(char)comstat.cbInQue;
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"));
} bool WriteChar(char* m_szWriteBuffer,DWORD m_nToSend) //写字符的 函数 { BOOL bWrite = TRUE; BOOL bResult = TRUE; DWORD BytesSent = 0; HANDLE m_hWriteEvent; ResetEvent(m_hWriteEvent); if (bWrite)
{ m_ov.Offset = 0; m_ov.OffsetHigh = 0;// Clear buffer bResult = WriteFile(hComm, // Handle to COMM Port m_szWriteBuffer, // Pointer to message buffer in calling finction m_nToSend, // Length of message to send &BytesSent, // Where to store the number of bytes sent &m_ov ); // Overlapped structure if (!bResult) { DWORD dwError = GetLastError(); switch (dwError) { case ERROR_IO_PENDING: { // continue to GetOverlappedResults() BytesSent = 0; bWrite = FALSE; break; } default: // all other error codes
该程序全部由 C 写成 没有 C++ 更没用 MFC 完全是自娱自乐 给需要的人一个参考 #include "stdafx.h" #include <windowsx.h> #include "resource.h" #include "MainDlg.h" #include <windows.h> #include <stdio.h> #include <stdlib.h> HANDLE hComm;//用于获取串口打开函数的返回值(句柄或错误值) OVERLAPPED m_ov; COMSTAT comstat; DWORD m_dwCommEvents;
switch(uMsg) { HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog); HANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand)ain_OnClose); }
} /*串口读取相关时间设置*/ bool setuptimeout(DWORD ReadInterval,DWORD ReadTotalMultiplier,DWORD ReadTotalconstant,DWORD WriteTotalMultiplier,DWORD WriteTotalconstant) { COMMTIMEOUTS timeouts; timeouts.ReadIntervalTimeout=ReadInterval; //读取两个字节间隔最大值 mS 如超过立即返回不再读取 timeouts.ReadTotalTimeoutConstant=ReadTotalconstant; //如果同下面一 个都为 0 则无论是否读到数据都返回 // 可以毫秒为单位指定一个乘数,该乘数用来计算读操作的总限时时间 timeouts.ReadTotalTimeoutMultiplier=ReadTotalMultiplier; // 以毫秒为单 位指定一个常数,用于计算读操作的总限时时间 0 表示不限时 timeouts.WriteTotalTimeoutConstant=WriteTotalconstant;// 写操作延时 同上 timeouts.WriteTotalTimeoutMultiplier=WriteTotalMultiplier; if(!SetCommTimeouts(hComm, &timeouts)) return false; else return true; } int Clearn() //清除 buff 中的内容并返回 buff 中现有数据量的大小并读取错误
{ CloseHandle(hComm); return FALSE; } else return true; } bool setupdcb(int rate_arg)//设置 port 的属性
{ DCB dcb; int rate= rate_arg; memset(&dcb,0,sizeof(dcb)); if(!GetCommState(hComm,&dcb))//获取当前 DCB 配置 return FALSE; // set DCB to configure the serial port dcb.DCBlength = sizeof(dcb); dcb.BaudRate = rate; dcb.Parity = NOPARITY; //奇偶校验值 0~4 分别对应无校验、奇校验、偶校 验、校验置位、校验清零 dcb.fParity = 0; //为 1 的话激活奇偶校验检查 dcb.StopBits = ONESTOPBIT;//停止位个数,0~2 分别对应 1 位、1.5 位、2 位停止位 dcb.ByteSize = 8; //数据位数
dcb.fOutxCtsFlow = 0; dcb.fOutxDsrFlow = 0; dcb.fDtrControl = DTR_CONTROL_DISABLE; dcb.fDsrSensitivity = 0; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fOutX = 0; dcb.fInX = 0; dcb.fErrorChar = 0; dcb.fBinary = 1; dcb.fNull = 0; dcb.fAbortOnError = 0; dcb.wReserved = 0; dcb.XonLim = 2; dcb.XoffLim = 4; dcb.XonChar = 0x13; dcb.XoffChar = 0x19; dcb.EvtChar = 0; // set DCB if(!SetCommState(hComm,&dcb)) return false; else return true;