C语言串口通信-源代码

合集下载

串口精灵源代码

串口精灵源代码
senddata.SetSize(len/2);
for(int i=0;i<len;)
{
char lstr,hstr=str[i];
if(hstr==' ')
{
i++;
continue;
}
i++;
if(i>=len)
break;
lstr=str[i];
//功能:若是在0-F之间的字符,则转换为相应的十六进制字符,否则返回-1
char CSCommTestDlg::ConvertHexChar(char ch)
{
if((ch>='0')&&(ch<='9'))
return ch-0x30;
else if((ch>='A')&&(ch<='F'))
{
// 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.
写出详细的编程过程,姑且叫串口调试助手源程序V1.0或VC串口通讯源程序吧,
我相信,如果你用VC编程,那么有了这个代码,就可以轻而易举地完成串口编
程任务了。(也许本文过于详细,高手就不用看)
开始吧:

C语言串口通信-源代码

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语言实现串口通信

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(函数将设置好的串口参数写回。

LabWindowscvi之RS-232串口通信编程源代码

LabWindowscvi之RS-232串口通信编程源代码

LabWindows/cvi之RS-232串口通信编程源代码/* LabWindows/CVI User Interface Resource (UIR) Include File *//* Copyright (c) National Instruments 2006. All Rights Reserved. *//* *//* W ARNING: Do not add to, delete from, or otherwise modify the contents *//* of this include file. *//**************************************************************************/#include <userint.h>#ifdef __cplusplusextern "C" {#endif/* Panels and Controls: */#define PANEL 1#define PANEL_OKBUTTON_2 2 /* callback function: receivefile */#define PANEL_OKBUTTON 3 /* callback function: receivefilename */#define PANEL_STRING_2 4#define PANEL_QUITBUTTON 5 /* callback function: QuitCallback */#define PANEL_STRING 6#define PANEL_DECORATION_2 7#define PANEL_COMMANDBUTTON 8 /* callback function: filesel */#define PANEL_DECORATION 9#define PANEL_TEXTMSG 10#define PANEL_TEXTMSG_2 11/* Menu Bars, Menus, and Menu Items: *//* (no menu bars in the resource file) *//* Callback Prototypes: */int CVICALLBACK filesel(int panel, int control, int event, void *callbackData, int eventData1, int eventData2);int CVICALLBACK QuitCallback(int panel, int control, int event, void*callbackData, int eventData1, int eventData2);int CVICALLBACK receivefile(int panel, int control, int event, void *cal lbackData, int eventData1, int eventData2);int CVICALLBACK receivefilename(int panel, int control, int event, void*callbackData, int eventData1, int eventData2);#ifdef __cplusplus}#endif#include <ansi_c.h>#include <utility.h>#include <rs232.h>#include <cvirte.h>#include <userint.h>#include "232.h"static int byteswritten;static char filename[MAX_FILENAME_LEN];static char pathname[MAX_PATHNAME_LEN];static int panelHandle;int main (int argc, char *argv[]){if (InitCVIRTE (0, argv, 0) == 0)return -1; /* out of memory */if ((panelHandle = LoadPanel (0, "232.uir", PANEL)) < 0)return -1;//打开并配置串口Com1OpenComConfig (1, "", 57600, 1, 8, 1, 32767, 32767);//设置通信超时时间SetComTime (1, 5.0);//禁止串口软件握手SetXMode (1, 0);//禁止硬件握手SetCTSMode (1, LWRS_HW HANDSHAKE_OFF); DisplayPanel (panelHandle);RunUserInterface ();DiscardPanel (panelHandle);return 0;}int CVICALLBACK sendfilename (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){int comstatus;int outputqueuelen;switch (event){case EVENT_COMMIT:strcat (filename, "\r");//向Com1写入文件名字符串byteswritten = ComWrt (1, filename, strlen(filename));break;}return 0;}int CVICALLBACK QuitCallback (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){switch (event){case EVENT_COMMIT://关闭串口Com1CloseCom (1);QuitUserInterface (0);break;}return 0;}int CVICALLBACK filesel (int panel, int control, int event,void *callbackData, int eventData1, int eventData2){int selstatus;switch (event){case EVENT_COMMIT:filename[0] = '\0';selstatus = FileSelectPopup ("", "*.*", "*.*", "打开文件", VAL_LOAD_BUTTON, 0, 0, 1, 1, pathname);if (selstatus >= 0){SetCtrlVal (panelHandle, PANEL_STRING, pathname);//获得文件名SplitPath (pathname, NULL, NULL, filename);}break;}return 0;}int CVICALLBACK sendfile (int panel, int control, int event,void *callbackData, int eventData1, int eventData2){int outputqueuelen;switch (event){case EVENT_COMMIT://设置串口Com1调制解调器参数XModemConfig (1, 10.0, 10, 5.0, 1024);//设置从串口Com1发送文件数据XModemSend (1, pathname);//获得串口Com1输出队列的字符串数目outputqueuelen = GetOutQLen (1);if (outputqueuelen == 0){MessagePopup ("文件传输", "文件传输完毕!");}break;}return 0;}接收程序#include "toolbox.h"#include <ansi_c.h>#include <rs232.h>#include <cvirte.h>#include <userint.h>#include "232.h"static int bytesread;static char filename[MAX_PATHNAME_LEN];static char pathname[MAX_PATHNAME_LEN];static int panelHandle;int main (int argc, char *argv[]){if (InitCVIRTE (0, argv, 0) == 0)return -1; /* out of memory */if ((panelHandle = LoadPanel (0, "232.uir", PANEL)) < 0) return -1;//打开并配置串口Com2OpenComConfig (2, "", 57600, 1, 8, 1, 32767, 32767);//设置通信超时时间SetComTime (2, 5.0);//禁止串口软件握手SetXMode (2, 0);//禁止硬件握手SetCTSMode (2, LWRS_HW HANDSHAKE_OFF);DisplayPanel (panelHandle);RunUserInterface ();DiscardPanel (panelHandle);return 0;}int CVICALLBACK receivefilename (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){switch (event){case EVENT_COMMIT:filename[0] = '\0';SetCtrlVal (panelHandle, PANEL_STRING, "");//读取字符串直到回车符出现bytesread = ComRdTerm (2, filename, 260, 13);//当出现回车符后,在其后加上结束符filename[bytesread]= '\0';SetCtrlVal (panelHandle, PANEL_STRING, filename);break;}return 0;}int CVICALLBACK QuitCallback (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){switch (event){case EVENT_COMMIT://关闭串口Com2CloseCom (2);QuitUserInterface (0);break;}return 0;}int CVICALLBACK filesel (int panel, int control, int event,void *callbackData, int eventData1, int eventData2){int selstatus;switch (event){case EVENT_COMMIT:selstatus = DirSelectPopup ("", "保存文件", 1, 1, pathname); if (selstatus){strcat (pathname, "\\");strcat (pathname, filename);SetCtrlVal (panelHandle, PANEL_STRING_2, pathname);}break;}return 0;}int CVICALLBACK receivefile (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){int result;int filesize;int inputqueuelen;FILE *stream;switch (event){case EVENT_COMMIT:GetCtrlVal (panelHandle, PANEL_STRING_2, pathname);//判断文件是否存在result = FileExists (pathname, &filesize);if (!result){stream = fopen (pathname, "wb+");fclose (stream);}//设置串口Com2调制解调器参数XModemConfig (2, 10.0, 10, 5.0, 1024);//设置从串口Com2接收文件数据XModemReceive (2, pathname);//获得串口Com2输入队列的字符串数目inputqueuelen = GetInQLen (2);if (inputqueuelen == 0){MessagePopup ("文件保存", "文件保存完毕!"); }break;}return 0;}。

三菱PLC编程口通信C语言源代码三菱plc

三菱PLC编程口通信C语言源代码三菱plc

三菱PLC编程口通信C语言源代码 - 三菱plcfxnew.h#define DELAY_TIMES 30000L#define TRUE 1#define FALSE 0#define TRUE 1#define FALSE 0#define FORCE_ON 0x37#define FORCE_OFF 0x38void init_plc(void);int check_plc(void);int _read_data_register(unsigned int uAddress,unsigned int number);int _read_mdata_register(unsigned int uAddress,unsigned int number);int _write_data_register(unsigned int uAddress,unsigned int number);int _force_m_contact(unsigned int uAddress,unsigned char ucOn_off);int read_data_register(unsigned int uAddress,unsigned intnumber);int read_mdata_register(unsigned int uAddress,unsigned int number);int write_data_register(unsigned int uAddress,unsigned int number);int force_m_contact(unsigned int uAddress,unsigned char ucOn_off);int _read_m_register(unsigned int uAddress,unsigned int number);int read_m_register(unsigned int uAddress,unsigned int number);int TESTING=0;unsigned int uRead_value[25];unsigned int uWrite_value[25];unsigned int COMM_PORT=1;unsigned int STATS_PORT=0x2fd;unsigned int DATA_PORT=0x2f8;void init_plc(void){ _AX=0xfa;_DX=COMM_PORT;geninterrupt(0x14);while((inportb(STATS_PORT)1)!=0)inportb(DATA_PORT);}int check_plc(void){ long lTmp;if(TESTING==1)return TRUE;init_plc();for(lTmp=0L;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)0x20)!=0) break;}if(lTmp=DELAY_TIMES)return(FALSE);outportb(DATA_PORT,5);disable();for(lTmp=0L;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)1)!=0) break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}if((lTmp=inportb(DATA_PORT))==6){ enable();return(TRUE);}else{ enable();return(FALSE);}}int read_data_register(unsigned int uAddress,unsigned int number){int i;for(i=0;i3;i++)if(_read_data_register(uAddress,number)==TRUE)return TRUE;return FALSE;}int _read_data_register(unsigned int uAddress,unsigned int number){ unsigned char uSend[]={2,0x30,0x30,0x30,0x30,0x30,0x30,0x32,3,0x30,0x30}; unsigned char uReceive[104];unsigned int uTmp;unsigned int uSum;unsigned int num;long lTmp;int i,j;if(TESTING==1){ for(i=0;inumber;i++)uRead_value[i]=0;return TRUE;}init_plc();num=number*2;if((num/16)=10)uSend[6]=(unsigned char)(num/16+0x41-10);elseuSend[6]=(unsigned char)(num/16+0x30);if((num%16)=10)uSend[7]=(unsigned char)((num%16)+0x41-10); elseuSend[7]=(unsigned char)((num%16)+0x30);uAddress=uAddress*2+0x1000;uTmp=uAddress 0x000f;uSend[5]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);uTmp=(uAddress4) 0x000f;uSend[4]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress8) 0x000f;uSend[3]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress12)0x000f;uSend[2]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uSum=0;for(i=1;i9;i++)uSum=uSum+(unsigned char)uSend[i];uTmp=uSum0x000f;uSend[10]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uSum4)0x000f;uSend[9]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);for(i=0;i11;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++){ if((inportb(STATS_PORT)0x20)!=0)break;}if(lTmp=DELAY_TIMES){return(FALSE);}outportb(DATA_PORT,uSend[i]); }disable();for(lTmp=0;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)1)!=0) break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}uReceive[0]=inportb(DATA_PORT);if(uReceive[0]!=2){enable();return(FALSE);}for(i=1;inumber*4+4;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++){ if((inportb(STATS_PORT)1)!=0)break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}uReceive[i]=inportb(DATA_PORT);}enable();uSum=0;for(i=1;inumber*4+2;i++)uSum=uSum+(unsigned int)uReceive[i];uTmp=uSum0xf;uTmp=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);if((unsigned char)uTmp!=uReceive[number*4+3])return(FALSE); uTmp=(uSum4)0xf;uTmp=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);if((unsigned char)uTmp!=uReceive[number*4+2])return(FALSE); for(j=0;jnumber;j++){for(i=j*4+1;ij*4+5;i++)uReceive[i]=(uReceive[i]0x39)?uReceive[i]-0x41+0xa:uReceive [i]-0x30;uRead_value[j]=(((((uReceive[j*4+3]4)+uReceive[j*4+4])4)+uR eceive[j*4+1])4)+uReceive[j*4+2];}return TRUE;}int read_mdata_register(unsigned int uAddress,unsigned int number){int i;for(i=0;i3;i++)if(_read_mdata_register(uAddress,number)==TRUE)return TRUE;return FALSE;}int _read_mdata_register(unsigned int uAddress,unsigned int number){ unsigned char uSend[]={2,0x30,0x30,0x30,0x30,0x30,0x30,0x32,3,0x30,0x30};unsigned char uReceive[104];unsigned int uTmp;unsigned int uSum;unsigned int num;long lTmp;int i,j;if(TESTING==1){ for(i=0;inumber;i++)uRead_value[i]=0; return TRUE;}init_plc();num=number*2;if((num/16)=10)uSend[6]=(unsigned char)(num/16+0x41-10); elseuSend[6]=(unsigned char)(num/16+0x30);if((num%16)=10)uSend[7]=(unsigned char)((num%16)+0x41-10); elseuSend[7]=(unsigned char)((num%16)+0x30);/*uAddress=uAddress*2+0x1000;*/uTmp=uAddress 0x000f;uSend[5]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress4) 0x000f;uSend[4]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress8) 0x000f;uSend[3]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress12)0x000f;uSend[2]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uSum=0;for(i=1;i9;i++)uSum=uSum+(unsigned char)uSend[i];uTmp=uSum0x000f;uSend[10]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uSum4)0x000f;uSend[9]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); for(i=0;i11;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++){ if((inportb(STATS_PORT)0x20)!=0)break;}if(lTmp=DELAY_TIMES){return(FALSE);}outportb(DATA_PORT,uSend[i]); }disable();for(lTmp=0;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)1)!=0) break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}uReceive[0]=inportb(DATA_PORT);if(uReceive[0]!=2){enable();return(FALSE);}for(i=1;inumber*4+4;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++){ if((inportb(STATS_PORT)1)!=0)break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}uReceive[i]=inportb(DATA_PORT);}enable();uSum=0;for(i=1;inumber*4+2;i++)uSum=uSum+(unsigned int)uReceive[i];uTmp=uSum0xf;uTmp=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);if((unsigned char)uTmp!=uReceive[number*4+3])return(FALSE); uTmp=(uSum4)0xf;uTmp=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);if((unsigned char)uTmp!=uReceive[number*4+2])return(FALSE); for(j=0;jnumber;j++){for(i=j*4+1;ij*4+5;i++)uReceive[i]=(uReceive[i]0x39)?uReceive[i]-0x41+0xa:uReceive [i]-0x30;uRead_value[j]=(((((uReceive[j*4+3]4)+uReceive[j*4+4])4)+uR eceive[j*4+1])4)+uReceive[j*4+2];}return TRUE;}int write_data_register(unsigned int uAddress,unsigned int number){int i;for(i=0;i3;i++)if(_write_data_register(uAddress,number)==TRUE)return TRUE;return FALSE;}int _write_data_register(unsigned int uAddress,unsigned int number){ unsigned char uSend[111];unsigned int uTmp,uSum,num;long lTmp;int i;if(TESTING==1)return TRUE;init_plc();uSend[0]=2;uSend[1]=0x31;uSend[number*4+8]=3;num=(number*2)/16;if(num=10)uSend[6]=num+0x41-10;else uSend[6]=num+0x30;num=(number*2)%16;if(num=10)uSend[7]=num+0x41-10;else uSend[7]=num+0x30;uAddress=0x1000+2*uAddress;uTmp=uAddress0x000f;uSend[5]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress4)0x000f;uSend[4]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress8)0x000f;uSend[3]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress12)0x000f;uSend[2]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);for(i=0;inumber;i++){uTmp=uWrite_value[i]0x000f;uSend[i*4+9]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);uTmp=(uWrite_value[i]4)0x000f;uSend[i*4+8]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);uTmp=(uWrite_value[i]8)0x000f;uSend[i*4+11]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uWrite_value[i]12)0x000f;uSend[i*4+10]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);}uSum=0;for(i=1;i9+number*4;i++)uSum+=uSend[i];uTmp=uSum0x000f;uSend[number*4+10]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uSum4)0x000f;uSend[number*4+9]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); for(i=0;i11+number*4;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++){ if((inportb(STATS_PORT)0x20)!=0)break;}if(lTmp=DELAY_TIMES){/*enable();*/return(FALSE);}outportb(DATA_PORT,uSend[i]);}disable();for(lTmp=0L;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)1)!=0) break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}if(inportb(DATA_PORT)!=6){enable();return(FALSE);}else{enable();return(TRUE);}}int force_m_contact(unsigned uAddress,unsigned char ucOn_off) {int i;for(i=0;i3;i++)if(_force_m_contact(uAddress,ucOn_off)==TRUE)return TRUE;return FALSE;}int _force_m_contact(unsigned uAddress,unsigned char ucOn_off) { unsigned uSend[]={2,0x37,0x30,0x30,0x30,0x30,3,0x30,0x30}; unsigned uTmp,uSum,i;long lTmp;if(TESTING==1)return TRUE;init_plc();uAddress=uAddress+0x800;uSend[1]=ucOn_off;uTmp=uAddress0x000f;uSend[3]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress4)0x000f;uSend[2]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress8)0x000f;uSend[5]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress12)0x000f;uSend[4]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uSum=0;for(i=1;i7;i++)uSum+=uSend[i];uTmp=uSum0x000f;uSend[8]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uSum4)0x000f;uSend[7]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); for(i=0;i9;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++){ if((inportb(STATS_PORT)0x20)!=0)break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}outportb(DATA_PORT,uSend[i]);}disable();for(lTmp=0L;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)1)!=0) break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}if(inportb(DATA_PORT)!=6){enable();return(FALSE);}else{ enable();return(TRUE);}}int read_m_register(unsigned int uAddress,unsigned int number) {int i;for(i=0;i3;i++)if(_read_m_register(uAddress,number)==TRUE)return TRUE;return FALSE;}int _read_m_register(unsigned int uAddress,unsigned int number){ unsigned char uSend[]={2,0x30,0x30,0x30,0x30,0x30,0x30,0x32,3,0x30,0x30}; unsigned char uReceive[54];unsigned int uTmp;unsigned int uSum;unsigned int num;long lTmp;int i,j;if(TESTING==1){ for(i=0;inumber;i++)uRead_value[i]=0;return TRUE;}init_plc();num=number;if((num/16)=10)uSend[6]=(unsigned char)(num/16+0x41-10);elseuSend[6]=(unsigned char)(num/16+0x30);if((num%16)=10)uSend[7]=(unsigned char)((num%16)+0x41-10); elseuSend[7]=(unsigned char)((num%16)+0x30);uAddress=uAddress/8+0x100;uTmp=uAddress 0x000f;uSend[5]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress4) 0x000f;uSend[4]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress8) 0x000f;uSend[3]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uAddress12)0x000f;uSend[2]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);uSum=0;for(i=1;i9;i++)uSum=uSum+(unsigned char)uSend[i];uTmp=uSum0x000f;uSend[10]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa); uTmp=(uSum4)0x000f;uSend[9]=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);for(i=0;i11;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++){ if((inportb(STATS_PORT)0x20)!=0)break;}if(lTmp=DELAY_TIMES){/*enable();*/return(FALSE);}outportb(DATA_PORT,uSend[i]);}disable();for(lTmp=0;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)1)!=0) break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}uReceive[0]=inportb(DATA_PORT);if(uReceive[0]!=2){enable();return(FALSE);}for(i=1;inumber*2+4;i++){ for(lTmp=0L;lTmpDELAY_TIMES;lTmp++) { if((inportb(STATS_PORT)1)!=0) break;}if(lTmp=DELAY_TIMES){enable();return(FALSE);}uReceive[i]=inportb(DATA_PORT);}enable();uSum=0;for(i=1;inumber*2+2;i++)uSum=uSum+(unsigned int)uReceive[i];uTmp=uSum0xf;uTmp=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);if((unsigned char)uTmp!=uReceive[number*2+3])return(FALSE); uTmp=(uSum4)0xf;uTmp=(uTmp10)?(uTmp+0x30):(uTmp+0x41-0xa);if((unsigned char)uTmp!=uReceive[number*2+2])return(FALSE); for(j=0;jnumber;j++){for(i=j*2+1;ij*2+3;i++)uReceive[i]=(uReceive[i]0x39)?uReceive[i]-0x41+0xa:uReceive [i]-0x30;uRead_value[j]=((uReceive[j*2+1])4)+uReceive[j*2+2];}return TRUE; }。

[电子工程] 单片机C语言之串口通信协议(代码分享)

[电子工程]  单片机C语言之串口通信协议(代码分享)

现实生活中,我们总是要与人打交道,互通有无。

单片机也一样,需要跟各种设备交互。

例如汽车的显示仪表需要知道汽车的转速及电动机的运行参数,那么显示仪表就需要从汽车的底层控制器取得数据。

而这个数据的获得过程就是一个通信过程。

类似的例子还有控制器通常是单片机或者PLC与变频器的通信。

通信的双方需要遵守一套既定的规则也称为协议,这就好比我们人之间的对话,需要在双方都遵守一套语言语法规则才有可能达成对话。

通信协议又分为硬件层协议和软件层协议。

硬件层协议主要规范了物理上的连线,传输电平信号及传输的秩序等硬件性质的内容。

常用的硬件协议有串口,IIC,SPI,RS485,CAN和USB。

软件层协议则更侧重上层应用的规范,比如modbus协议。

好了,那这里我们就着重介绍51单片机的串口通信协议,以下简称串口。

串口的6个特征如下。

(1)、物理上的连线至少3根,分别是Tx数据发送线,Rx数据接收线,GND共用地线。

(2)、0与1的约定。

RS232电平,约定﹣5V至﹣25V之间的电压信号为1,﹢5V至﹢25V之间的电压信号为0 。

TTL电平,约定5V的电压信号为1,0V电压信号为0 。

CMOS电平,约定3.3V的电压信号为1,0V电压信号为0 。

其中,CMOS电平一般用于ARM芯片中。

(3)、发送秩序。

低位先发。

(4)、波特率。

收发双方共同约定的一个数据位(0或1)在数据传输线上维持的时间。

也可理解为每秒可以传输的位数。

常用的波特率有300bit/s, 600bit/s, 2400bit/s, 4800bit/s, 9600bit/s。

(5)、通信的起始信号。

发送方在没有发送数据时,应该将Tx置1 。

当需发送时,先将Tx置0,并且保持1位的时间。

接受方不断地侦测Rx,如果发现Rx常时间变高后,突然被拉低(置为0),则视为发送方将要发送数据,迅速启动自己的定时器,从而保证了收发双方定时器同步定时。

(6)、停止信号。

发送方发送完最后一个有效位时,必须再将Tx保持1位的时间,即为停止位。

串口通信源代码

串口通信源代码
// txtest.cpp : 定义控制台应用程序的入口点。
//
#include "tdafx.h"
#include <iostream>
// #include <cv.h>
// #include <highgui.h>
/*#include <cstring>*/
#include<windows.h>
//myDCB.fBinary = TRUE;
//myDCB.fParity = FALSE;
myDCB.ByteSize = 8;
myDCB.Parity = NOPARITY;
myDCB.StopBits = ONESTOPBIT;
SetCommState(hCom, &myDCB);
TimeOuts.WriteTotalTimeoutConstant=2000;
SetCommTimeouts(hCom,&TimeOuts); //设置超时
DCB myDCB;
GetCommState(hCom, &myDCB);
myDCB.BaudRate = 9600;
ReceiveData(hCom, rdata);
cout << (BYTE)(rdata[0]) <<"%%%%%%%"<< (BYTE)(rdata[1]) << endl;
cout << "收到数据!" << endl;
if(i>=250 ) break;

C语言串口通信-源代码

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语言做串口通讯程序了,但是基于DOS环境的程序还是有它的优势的。

DOS系统的单任务环境是系统运行更加稳定、可靠;在一些追求很高的可靠性的系统中还是有一定的价值的。

本文通过C语言控制PLC实现简单的物料传送为例子。

二、硬件介绍:1、CPM1A采用RS232串口通讯与上位机连接,在PLC的DM区中可以设定串口参数,本文采用默认值:串口通信格式:1位---起始位、9600---波特率、7位---数据位、2位---停止位、偶校验2、C语言中用于串口读写的函数:bioscom,在bios.h头文件中。

Bioscom用法:bioscom(int cmd,char byte,int port)Cmd的值:0 设置通信参数为btye值1 发送一个字符到串口2 从串口接收一个字符3 返回串口端口的状态byte的值:0x02 7数据位0x03 8位数据位0x00 1个停止位0x04 2个停止位0x00 无奇偶校验0x08奇校验0x18偶校验0x80 1200波特率0xA0 2400波特率0xC0 4800波特率0xE0 9600波特率注意:在对串口初始化时,上述参数值相或附给byte。

Port的值:0 端口11 端口2三、完整源代码:#include /* 此头函数请不要删除*/#include#include#define F1 0x3B /*启动*/#define F2 0x3C /*停止*/#define F3 0x3D /*混料*/#define F4 0x3E /*出料*/#define F5 0x3F /*退出*/#define PORT 0 /*定义端口号*/#define SETTINGS (0x02|0x04|0x18|0xE0) /*设定参数*//* 定义发送字符函数send */void sendPort(int port,char cc){union{char ch[2];int status;}port_status;/*发送一个字符*/port_status.status=bioscom(1,cc,port);printf("%c",cc); /*判断发送是否正确*/if(port_status.ch[1]&128){printf("Send data error detected in serial port"); printf("\r");}}/* Check-Status 检查端口*/int check_status(int port){int status;status=bioscom(3,0,port);if(status & 0x100)return 0;else return 1;}/*发送命令函数*/void SendOder(char od[]){int i=0;for(i=0;i<=16;i++)sendPort(PORT,od[i]);}/*应用程序主体*/main(){int key=1,i,m=1;int check=1;char a[20]="@00WR0000000144*"; /*启动00*/ char b[20]="@00WR0000000441*"; /*混料02*/ char c[20]="@00WR000000084D*"; /*出料03*/ char d[20]="@00WR0000000247*"; /*停止01*/ a[16]='\r';b[16]='\r';c[16]='\r';d[16]='\r';printf("启动:F1 \t混料:F2 \t出料:F3");printf(" \t停止:F4 \t退出:F5\n");bioscom(0,SETTINGS,PORT); /*初始化串口*/ while(check!=0) /*检查端口状态*/{m+=1;check=check_status(PORT);if(m>=1000)break;}while (1){while (bioskey(1)==0);key=bioskey(0);key=key&0xFF?0:key>>8;if(key==F1) /*启动命令*/{for(i=0;i<=16;i++){sendPort(PORT,a[i]);m=1;while(check!=0){m+=1;check=check_status(PORT); /*检查端口状态*/ if(m>=3000)break;}}}else if(key==F4) /*停止命令*/{for(i=0;i<=16;i++){sendPort(PORT,d[i]);m=1;while(check!=0){m+=1;check=check_status(PORT);if(m>=3000)break;}}}else if(key==F2) /*混料命令*/{for(i=0;i<=16;i++){sendPort(PORT,b[i]);m=1;while(check!=0){m+=1;check=check_status(PORT);if(m>=3000)break;}}}else if(key==F3) /*出料命令*/{for(i=0;i<=16;i++){sendPort(PORT,c[i]);m=1;while(check!=0){m+=1;check=check_status(PORT);if(m>=3000)break;}}}else if(key==F5)exit(1); /*退出命令*/}getch(); /* 此语句请不要删除*/}四、结束语RS232串口通讯在小型的控制系统同中还是应用广泛的,本文采用C语言控制,主要是给用户提供一个新的控制方式做选择。

MODBUS通讯+C语言源代码

MODBUS通讯+C语言源代码

/******************************************************************** *************//*函数名称: strmcpy()*输入参数:共个参数;*输出参数:共个参数;*返回值:*需储存的参数:共个参数;*功能介绍:(1)字符数组拷贝;*修改日志:*[2006-3-6 17:07] Ver. 1.00开始编写;完成;/* *//******************************************************************** *************/void strmcpy(unsigned char dest[], unsigned char src[], int count){int i;for(i = 0; i < count; i ++){dest[i] = src[i];}dest[i] = '\0';}/******************************************************************** *********//******************************************************************** *************//*函数名称: bitmcpy()*输入参数:共个参数;*输出参数:共个参数;*返回值:*需储存的参数:共个参数;*功能介绍:(1)开关量数组拷贝;*修改日志:*[2006-3-7 14:59] Ver. 1.00开始编写;完成;/* *//******************************************************************** *************/void bitmcpy(int dest[], int src[], int count){int i;for(i = 0; i < count; i ++){dest[i] = src[i];}}/******************************************************************** *********//******************************************************************** *************//*函数名称: strmcmp()*输入参数:共个参数;*输出参数:共个参数;*返回值:*需储存的参数:共个参数;*功能介绍:(1)字符数组比较;相同则返回0,不相同则返回1;*修改日志:*[2006-3-6 17:41] Ver. 1.00开始编写;完成;/* *//******************************************************************** *************/int strmcmp(unsigned char str1[], unsigned char str2[], int count){int i;for(i = 0; i < count; i ++){if(str1[i] != str2[i]){return 1;}}return 0;}/******************************************************************** *********//******************************************************************** *************//*函数名称: Datamcmp()*输入参数:共个参数;*输出参数:共个参数;*返回值:*需储存的参数:共个参数;*功能介绍:(1)浮点数组比较;相同则返回0,不相同则返回1;*修改日志:*[2006-3-6 18:05] Ver. 1.00开始编写;完成;*[2006-3-9 13:52]加了一层括号,以前是错误的if(!((data1[i] - data2[i] < 0.0001) && (data1[i] - data2[i] > -0.0001)))/* *//******************************************************************** *************/int Datamcmp(float data1[], float data2[], int count){int i;for(i = 0; i < count; i ++){if(!((data1[i] - data2[i] < 0.0001) && (data1[i] - data2[i] > -0.0001))){return 1;}}return 0;}/******************************************************************** *********//******************************************************************** *************//*函数名称: Bitmcmp()*输入参数:共个参数;*输出参数:共个参数;*返回值:*需储存的参数:共个参数;*功能介绍:(1)开关量数组比较;相同则返回0,不相同则返回1;*修改日志:*[2006-3-6 18:10] Ver. 1.00开始编写;完成;/* *//******************************************************************** *************/int Bitmcmp(int data1[], int data2[], int count){int i;for(i = 0; i < count; i ++){if(data1[i] != data2[i]){return 1;}}return 0;}/******************************************************************** *********//******************************************************************** *************//*函数名称: GetCRC16()*输入参数:共个参数;*输出参数:共个参数;*返回值:*需储存的参数:共个参数;*功能介绍:(1)CRC16校验;返回校验码;*修改日志:*[2005-11-28 16:40] Ver. 1.00开始编写;完成;/* *//******************************************************************** *************/unsigned short GetCRC16(unsigned char *puchMsg, unsigned short usDataLen) {/* CRC 高位字节值表*/unsigned char auchCRCHi[256] = {0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,0x80, 0x41, 0x00, 0xC1, 0x81, 0x40};unsigned char auchCRCLo[256] = {0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,0x43, 0x83, 0x41, 0x81, 0x80, 0x40};unsigned char uchCRCHi = 0xFF ; /* 高CRC字节初始化*/unsigned char uchCRCLo = 0xFF ; /* 低CRC 字节初始化*/unsigned uIndex = 0; /* CRC循环中的索引*/while (usDataLen--) /* 传输消息缓冲区*/{uIndex = uchCRCHi ^ *puchMsg++ ; /* 计算CRC */uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex] ;uchCRCLo = auchCRCLo[uIndex] ;}return (unsigned short)((unsigned short)uchCRCHi << 8 | uchCRCLo) ;}/******************************************************************** *********//******************************************************************** *************//*函数名称: SendRtuCmdToModBus()*输入参数:共个参数;*输出参数:共个参数;*返回值:无*需储存的参数:共个参数;*功能介绍:(1)发送ModBus RTU 指令到Modbus Slave,加上CRC16校验码;*修改日志:*[2005-11-28 16:40] Ver. 1.00开始编写;完成;*[2006-3-1 9:02]返回类型改为void;/* *//******************************************************************** *************/void SendRtuCmdToModBus(int ModPort, unsigned char cmd[], unsigned short len) {unsigned short CRC16;CRC16=GetCRC16(cmd,len);ToComBufn(ModPort,cmd,len);ToCom(ModPort, (unsigned char)(CRC16 >> 8 & 0x00FF)); /* send CRC16 high */ToCom(ModPort, (unsigned char)(CRC16 & 0x00FF)); /* send CRC16 low */}/******************************************************************** *********//******************************************************************** *************//*函数名称: ReadModBusRtuSlave()*输入参数:共8 个参数;*输出参数:共5 个参数;*返回值:成功与否1:成功,2:失败;*需储存的参数:共0 个参数;*功能介绍:(1)读取ModBusRtuSlave,并解码输出反馈字符串相关容;ReadModBusRtuSlave(COMPORT1, ModAddr, ModFunction, ModByteNum, ModData, &ModDataLen, ModTimeout=10, waitTime=30)*修改日志:*[2005-11-28 16:40] Ver. 1.00开始编写;完成;*[2006-3-1 9:23]增加了int counter = 0;unsigned char ModBusMessage[MOD_STR_MAX_LEN];*[2006-3-1 13:46]增加了strmcpy(ModData, ModBusMessage + 3, ModBusIdx - 5);/* *//******************************************************************** *************/int ReadModBusRtuSlave(int ModPort, unsigned char *ModAddr, unsigned char *ModFunction, unsigned char *ModByteNum,unsigned char ModData[], unsigned char *ModDataLen, unsigned ModTimeout, unsigned waitTime){unsigned char data;unsigned long t;int i;unsigned short CRC16;int ModBusIdx = 0;int counter = 0;unsigned char ModBusMessage[MOD_STR_MAX_LEN] = {'\0'};while((!(IsCom(ModPort)) && (counter < waitTime))){DelayMs(1);counter ++;}StopWatchStart(MODBUS_STOP_WATCH);do{while(IsCom(ModPort) && (ModBusIdx < MOD_STR_MAX_LEN - 1)){data = ReadCom(ModPort);ModBusMessage[ModBusIdx ++]=data;StopWatchStart(MODBUS_STOP_WATCH);/* Print("[%02X]",data); */}StopWatchReadValue(MODBUS_STOP_WATCH, &t);}while(t <= ModTimeout);if (ModBusIdx == 0) return 0;ModBusMessage[ModBusIdx] = '\0';StopWatchStop(MODBUS_STOP_WATCH);CRC16 = GetCRC16(ModBusMessage,ModBusIdx - 2);/* for(i=0; i> 8 & 0x00FF) == ModBusMessage[ModBusIdx - 2] && (unsigned char)(CRC16 & 0x00FF) == ModBusMessage[ModBusIdx - 1]){*ModAddr = ModBusMessage[0];*ModFunction = ModBusMessage[1];*ModByteNum = ModBusMessage[2];strmcpy(ModData, ModBusMessage + 3, ModBusIdx - 5);/* Print(" idx%d ", ModBusIdx - 5); /*test*//* for(i = 3; i < ModBusIdx - 2; i++){ModData[i - 3] = ModBusMessage[i];}ModData[i] = '\0';*/*ModDataLen = ModBusIdx - 5;/* Print("{DataLen=%d}\n\r", *ModDataLen); */return 1;}else{*ModDataLen = 0;return 0;/* CRC16 error *//* Print("{CRC16 Error}\n\r"); */}}/*-------------------------------------------------------------------------------*//*********************************************************************************//*函数名称: ResponseFromModBusRtuSlave()*输入参数:共8 个参数;*输出参数:共5 个参数;*返回值:成功与否1:成功,2:失败;*需储存的参数:共0 个参数;*功能介绍:(1)写参数到ModBusRtuSlave后,ModbusRtuSlave反馈字符串;*修改日志:*[2006-3-1 12:34] Ver. 1.00开始编写;*[2006-3-1 12:48]完成;*[2006-3-6 16:32]strcpy(totalStr, ModBusMessage);改为strmcpy(totalStr, ModBusMessage, ModBusIdx);/* *//******************************************************************** *************/int ResponseFromModBusRtuSlave(int ModPort, unsigned char totalStr[], unsigned char *ModAddr, unsigned char *ModFunction, unsigned short *ModDataAddr,unsigned short *ModDataNum, unsigned ModTimeout, unsigned waitTime){unsigned char data;unsigned long t;unsigned short CRC16;int ModBusIdx = 0;int counter = 0;unsigned char ModBusMessage[MOD_STR_MAX_LEN] = {'\0'};while((!(IsCom(ModPort)) && (counter < waitTime))){DelayMs(1);counter ++;}StopWatchStart(MODBUS_STOP_WATCH);do{while(IsCom(ModPort) && (ModBusIdx < MOD_STR_MAX_LEN - 1)){data = ReadCom(ModPort);ModBusMessage[ModBusIdx ++]=data;StopWatchStart(MODBUS_STOP_WATCH);/* Print("[%02X]",data); */}StopWatchReadValue(MODBUS_STOP_WATCH, &t);}while(t <= ModTimeout);if (ModBusIdx == 0) return 0;ModBusMessage[ModBusIdx] = '\0';strmcpy(totalStr, ModBusMessage, ModBusIdx);StopWatchStop(MODBUS_STOP_WATCH);CRC16 = GetCRC16(ModBusMessage,ModBusIdx - 2);if((unsigned char)(CRC16 >> 8 & 0x00FF) == ModBusMessage[ModBusIdx - 2] && (unsigned char)(CRC16 & 0x00FF) == ModBusMessage[ModBusIdx - 1]) {*ModAddr = ModBusMessage[0];*ModFunction = ModBusMessage[1];*ModDataAddr = (unsigned short)((unsigned short)ModBusMessage[2] << 8 | ModBusMessage[3]);*ModDataNum = (unsigned short)((unsigned short)ModBusMessage[4] << 8 | ModBusMessage[5]);return 1;}else{return 0;/* CRC16 error *//* Print("{CRC16 Error}\n\r"); */}}/*-------------------------------------------------------------------------------*//******************************************************************** *************//*函数名称: ResponseSingleBitFromModBus()*输入参数:共8 个参数;*输出参数:共5 个参数;*返回值:成功与否1:成功,2:失败;*需储存的参数:共0 个参数;*功能介绍:(1)写参数到ModBusRtuSlave后,ModbusRtuSlave反馈字符串;*修改日志:*[2006-3-7 14:40] Ver. 1.00开始编写;*[2006-3-7 14:40]完成;/* *//******************************************************************** *************/int ResponseSingleBitFromModBus(int ModPort, unsigned char totalStr[], unsigned char *ModAddr, unsigned char *ModFunction, unsigned short *ModDataAddr,unsigned short *ModDataState, unsigned ModTimeout, unsigned waitTime){unsigned char data;unsigned long t;unsigned short CRC16;int ModBusIdx = 0;int counter = 0;unsigned char ModBusMessage[MOD_STR_MAX_LEN] = {'\0'};while((!(IsCom(ModPort)) && (counter < waitTime))){DelayMs(1);counter ++;}StopWatchStart(MODBUS_STOP_WATCH);do{while(IsCom(ModPort) && (ModBusIdx < MOD_STR_MAX_LEN - 1)){data = ReadCom(ModPort);ModBusMessage[ModBusIdx ++]=data;StopWatchStart(MODBUS_STOP_WATCH);/* Print("[%02X]",data); */}StopWatchReadValue(MODBUS_STOP_WATCH, &t);}while(t <= ModTimeout);if (ModBusIdx == 0) return 0;ModBusMessage[ModBusIdx] = '\0';strmcpy(totalStr, ModBusMessage, ModBusIdx);StopWatchStop(MODBUS_STOP_WATCH);CRC16 = GetCRC16(ModBusMessage,ModBusIdx - 2);if((unsigned char)(CRC16 >> 8 & 0x00FF) == ModBusMessage[ModBusIdx - 2] && (unsigned char)(CRC16 & 0x00FF) == ModBusMessage[ModBusIdx - 1]) {*ModAddr = ModBusMessage[0];*ModFunction = ModBusMessage[1];*ModDataAddr = (unsigned short)((unsigned short)ModBusMessage[2] << 8 | ModBusMessage[3]);if(ModBusMessage[4]) *ModDataState = 1;else *ModDataState = 0;return 1;}else{return 0;/* CRC16 error *//* Print("{CRC16 Error}\n\r"); */}}/*-------------------------------------------------------------------------------*//******************************************************************** *************//*函数名称: ChangeAllParameterDataByModBus()*输入参数:共个参数;*输出参数:共个参数;*返回值:无*需储存的参数:共个参数;*功能介绍:(1) 将MODBUSSLAVE返回的数据字符转化为参数值;(2) void *memcpy(void *dest, const void *src, size_t n)(3) 四个字符的顺序应倒一下。

VC实现串口通信项目源码

VC实现串口通信项目源码

VC实现串口通信项目源码以下是一个基于VC++实现串口通信的简单项目源码:```#include <windows.h>#include <iostream>using namespace std;//串口通信类class SerialPortprivate:HANDLE hSerial; // 串口句柄public:SerialPorhSerial = NULL;}bool openPort(const char* portName)//打开串口hSerial = CreateFileA(portName,GENERIC_READ,GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);if (hSerial == INVALID_HANDLE_VALUE)cerr << "Failed to open serial port!" << endl;return false;}//配置串口参数DCB dcbSerialParams = { 0 };dcbSerialParams.DCBlength = sizeof(dcbSerialParams);cerr << "Failed to get serial parameters!" << endl; CloseHandle(hSerial);return false;}dcbSerialParams.BaudRate = CBR_9600; // 波特率设置为9600 dcbSerialParams.ByteSize = 8; // 数据位设置为8 dcbSerialParams.StopBits = ONESTOPBIT; // 停止位设置为1 dcbSerialParams.Parity = NOPARITY; // 校验位设置为无cerr << "Failed to set serial parameters!" << endl; CloseHandle(hSerial);return false;}//设置读写超时时间CloseHandle(hSerial);return false;}return true;}bool closePor//关闭串口if (hSerial != NULL && hSerial != INVALID_HANDLE_VALUE) CloseHandle(hSerial);hSerial = NULL;return true;}return false;}bool writeData(const char* data, int dataSize)//向串口写数据DWORD bytesWritten;if (!WriteFile(hSerial, data, dataSize, &bytesWritten, NULL)) cerr << "Failed to write data!" << endl;return false;}if (bytesWritten != dataSize)cerr << "Failed to write all data!" << endl;return false;}return true;}bool readData(char* buffer, int bufferSize)//从串口读数据DWORD bytesRead;if (!ReadFile(hSerial, buffer, bufferSize, &bytesRead, NULL)) cerr << "Failed to read data!" << endl;return false;return true;}};int maiSerialPort serialPort;//打开串口if (!serialPort.openPort("COM1"))return 1;}//从用户输入获取数据char sendBuffer[256];cout << "Enter data to send: ";cin.getline(sendBuffer, sizeof(sendBuffer));//发送数据至串口if (!serialPort.writeData(sendBuffer, strlen(sendBuffer) + 1))serialPort.closePort(;return 1;//从串口接收数据char recvBuffer[256];if (!serialPort.readData(recvBuffer, sizeof(recvBuffer)))serialPort.closePort(;return 1;}//输出接收到的数据cout << "Received data: " << recvBuffer << endl;//关闭串口serialPort.closePort(;return 0;```这个项目实现了一个简单的串口通信程序,通过命令行交互,用户可以输入要发送的数据,程序将数据发送到串口,然后从串口接收并打印接收到的数据。

c语言 485通信源程序

c语言 485通信源程序
#endif
// This flag is set on USART1 Receiver buffer overflow
bit rx_buffer_overflow1;
// USART1 Receiver interrupt service routine
volatile bit comm_flg=false;
bit comm_flg1=true;
uchar comm_state=0;
uchar comm_over;
interrupt [USART0_RXC] void usart0_rx_isr(void)
{
char status,data;
uchar i;
status=UCSR0A;
data=UDR0;
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
{
rx_buffer1[rx_rd_index1]=data;
if (++rx_rd_index1 == RX_BUFFER_SIZE1) rx_rd_index1=0;
if (++rx_counter1 == RX_BUFFER_SIZE1)
uchar rx_process_buffer1[160];
uchar rx_process_counter1;
#if RX_BUFFER_SIZE1<256
unsigned char rx_rd_index1,rx_counter1;
#else
unsigned int rx_rd_index1,rx_counter1;
c语言 485通信源程序 #definerxb8 #definetxb8 #defineupe #defineovr #definefe #defineudre #definerxc #defineframing_error (1<<fe) #define parity_error (1<<upe) #define data_overrun (1<<ovr) #define data_register_empty (1<<udre) #define rx_complete (1<<rxc) usart1receiver buffer #define rx_buffer_size1 128 uchar rx_buffer1[rx_buffer_size1]; uchar rx_process_buffer1[160]; uchar rx_process_counter1; rx_buffer_size1<256unsigned char rx_rd_index1,rx_counter1; #else unsigned int rx_rd_index1,rx_counter1; #endif usart1receiver buffer overflow bit rx_buffer_overflow1; usart1receiver interrupt service routine volatile bit comm_flg=false; bit comm_flg1=true; uchar comm_state=0; uchar comm_over; interrupt [usart0_rxc] void usart0_rx_isr(void) charstatus,data; uchar status=ucsr0a;data=udr0; rx_buffer_size1)rx_rd_index1=0; rx_counter1=0;rx_buffer_overflow1=1; comm_over=250;if(rx_counter1==2) elseif((rx_counter1>=13)&amp;&amp;(rx_counter1==rx_buffer1[7]+10)) if(comm_state!=0){comm_flg1=true;}else for(i=0;i<rx_counter1;i++)rx_proces

c语言怎么写串口通信编程

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函数用于打开指定的串口设备并进行一些必要的设置。

C语言串口通信源代码

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)< bdsfid="112" p=""></maxbuflen)<>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++;< bdsfid="135" p=""></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 //接收#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++; //记录接收了多少个数据。

C51串口源代码实例

C51串口源代码实例

C51串口源代码实例串口实现函数:void init_uart(void){PCON=0x80; //倍频,减少误差率TMOD=0x25; //设置定时器1 为方式2(用于设置波特率);设置T0 为计数器模式1,用作HV 的检查TH1=0xF1; //装入初值波特率为9600 晶振27MHzTH1=0XF1TL1=0xF1;TR1=1; //启动定时器1SM0=0;SM1=1; //串口方式1,8 bit uartREN=1; //接收使能EA=1;ES=1;return;}void serial() interrupt 4{//uartflag = 1;RI=0;}//向串口发送一个字符void send_char(U8 ch) { ES=0;TI=0;SBUF=ch; while(!TI); TI=0;ES=1; } //向串口发送多个字符void send_chars(U8 *ch){U8i=0;ES=0;TI=0;for(i=0;ch[i]!=;i++){SBUF=ch[i];while(!TI);TI=0;}ES=1;}//向串口发送一个字符无需十六进制显示void send_u8(U8 ch){U8 tt;send_char(x30);//x30 其中30 是十六进制代表0send_char(x58); //x58 其中30 是十六进制代表xtt = ch >>4 ;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = ch &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}send_chars(““);}//向串口发送一个字符无需十六进制显示void send_u16(U16 ch){U8 tt;send_char(x30); //x30 其中30 是十六进制代表0send_char(x58); //x58 其中30 是十六进制代表xtt = ch >>12 ;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = (ch>>8) &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = (ch>>4) &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = ch &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}send_chars(““);}voiduart_welcome(){send_chars(“---------------------------------------------------------------”);send_chars(“Welcome to Tvia 5735 Uart Test V1.0”);send_chars(“Built time: 2013-09-24”);send_chars(“MCU FOSC:27Mhz Baud rate:9600”);send_chars(“Note:”);send_chars(“Serial debugging assistants do not need。

at32中串口1的接收与发送代码

at32中串口1的接收与发送代码

序号一:at32中串口1的接收代码1.1 我们需要定义用于接收数据的缓冲区。

这可以通过以下代码实现:```c#define RX_BUFFER_SIZE 64uint8_t rx_buffer[RX_BUFFER_SIZE];```1.2 我们需要初始化串口1。

这可以通过以下代码实现:```cUSART_InitTypeDef usart_init_struct;usart_init_ART_BaudRate = 9600;usart_init_ART_WordLength = USART_WordLength_8b; usart_init_ART_StopBits = USART_StopBits_1;usart_init_ART_Parity = USART_Parity_No;usart_init_ART_Mode = USART_Mode_Rx;usart_init_ART_HardwareFlowControl =USART_HardwareFlowControl_None;USART_Init(USART1, usart_init_struct);USART_Cmd(USART1, ENABLE);```1.3 接下来,我们需要编写接收数据的函数。

这可以通过以下代码实现:```cvoid USART1_IRQHandler(void){if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET){static uint8_t rx_index = 0;rx_buffer[rx_index] = USART_ReceiveData(USART1);rx_index++;if (rx_index >= RX_BUFFER_SIZE){rx_index = 0;}}}```1.4 我们需要启用接收中断。

这可以通过以下代码实现:```cUSART_ITConfig(USART1, USART_IT_RXNE, ENABLE);NVIC_EnableIRQ(USART1_IRQn);```序号二:at32中串口1的发送代码2.1 我们需要定义用于发送数据的缓冲区。

c语言通信问题的代码

c语言通信问题的代码

c语言通信问题的代码以下是一个简单的C语言通信问题的示例代码: c.#include <stdio.h>。

#include <stdlib.h>。

#include <string.h>。

#define MAX_MESSAGE_SIZE 100。

// 定义一个结构体来表示消息。

typedef struct {。

int sender_id;int receiver_id;char message[MAX_MESSAGE_SIZE];} Message;// 模拟发送消息的函数。

void sendMessage(Message msg) {。

printf("发送者ID,%d\n", msg->sender_id); printf("接收者ID,%d\n", msg->receiver_id); printf("消息内容,%s\n", msg->message);printf("消息发送成功!\n");}。

// 模拟接收消息的函数。

void receiveMessage(Message msg) {。

printf("接收者ID,%d\n", msg->receiver_id);printf("发送者ID,%d\n", msg->sender_id);printf("消息内容,%s\n", msg->message);printf("消息接收成功!\n");}。

int main() {。

Message msg1;msg1.sender_id = 1;msg1.receiver_id = 2;strcpy(msg1.message, "你好,这是一条测试消息!"); Message msg2;msg2.sender_id = 2;msg2.receiver_id = 1;strcpy(msg2.message, "你好,我收到了你的消息!"); sendMessage(&msg1);receiveMessage(&msg2);return 0;}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#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++; //记录接收了多少个数据。

outportb(ICREG,EOI);};void SerInit(int baud,int configuration){disable();outportb(portaddr+LCR,0x80);outportb(portaddr+LSB,baud);outportb(portaddr+MSB,0x00);outportb(portaddr+LCR,configuration);enable();};void SerOpen(void){vect_com=getvect(portf+8);disable();inportb(portaddr+RXD);inportb(portaddr+MSR);inportb(portaddr+LSR);inportb(portaddr+IIR);outportb(portaddr+IER,IERV);outportb(portaddr+MCR,OUT2|ERTS|EDTR);outportb(IMASKREG,inportb(IMASKREG)&(~(1<<portf))); setvect(portf+8,receiver);enable();};void SerClose(void){disable();outportb(portaddr+IER,0);outportb(portaddr+MCR,0);outportb(IMASKREG,inportb(IMASKREG)|(1<<portf)); enable();setvect(portf+8,vect_com);};void Getportaddr(int port){switch (port){case 0: portaddr=0x3F8; break;case 1: portaddr=0x2F8; break;case 2: portaddr=0x3E8; break;case 3: portaddr=0x2E8; break;}portf=(port==0)?4:3;};void Int(){unsigned char key,key2;port=ComNum-1;if(peek(0x40,port*2)==0){printf("have no special com .\n");exit(1);}else{printf("The used port is :COM%d\n",ComNum);};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!=0xff){printf("%x\t",key);FILE *fp;fp=fopen("C:\\Receivedata.dat","ab"); //可选择接收数据的存放文件路径和文件名if(fp==NULL) printf("File open error!");// fputc(key,fp);fwrite(&key,sizeof(unsigned char),1,fp);fclose(fp);}}while (key2!=27);SerClose();// printf("%d char has been received\n",incount);// printf("%d char has been sended\n",outcount);// printf("\nsum=%d \n",sum);}void main()//com1 receive{printf("Please input the receive COMnum:(1~4)\n");cin>>ComNum;printf("the current com set is:9600,even, data bits 8, stop 1,"); Int();printf("\n\nOVER\n");exit(0);};---------------发送文件程序#include <dos.h>#include <bios.h>#include <stdio.h>#include <math.h>#include <conio.h>#include <graphics.h>#ifdef __cplusplus#define __CPPARGS ...#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 receive buffer*/ 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:\\comfile.c";if(argc<2){printf("\nUsage:display filename.wav");// 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)不是从窗口派生的。

相关文档
最新文档