串口通信关键代码
串口通信代码
串口通信代码TMSCOMN::~TMSCOMN(){if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}};void TMSCOMN::CloseComs(){if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}};AnsiString TMSCOMN::GetComError(){AnsiString Errors;if(ComReg==0) Errors = AnsiString("串口设备与串口工作良好"); else if(ComReg==1) Errors = AnsiString("串口未打开");else Errors = AnsiString(" 串口设备与串口未连接上");return Errors;};void TMSCOMN::SetRs232Coms(int NoComs,int Bps){AnsiString ComNo;DCB dcb;COMMTIMEOUTS TimeOuts;char str[100];ComErr = AnsiString("");if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}ComNo = AnsiString("COM")+AnsiString(NoComs+1);hComs=CreateFile(ComNo.c_str(),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,0);if(hComs == INVALID_HANDLE_VALUE){ComReg = 1; ComErr = AnsiString("串口RS232未打开");Application->MessageBoxA("串口RS232打开出错!","错误",MB_OK|MB_ICONERROR); }else{GetCommState(hComs,&dcb);if(Bps==0) dcb.BaudRate = CBR_300;else if(Bps==1) dcb.BaudRate = CBR_1200;else if(Bps==2) dcb.BaudRate = CBR_2400;else if(Bps==3) dcb.BaudRate = CBR_4800;else if(Bps==4) dcb.BaudRate = CBR_9600;else if(Bps==5) dcb.BaudRate = CBR_19200;else if(Bps==6) dcb.BaudRate = CBR_38400;dcb.ByteSize = 8;dcb.Parity = NOPARITY;dcb.StopBits = ONESTOPBIT;SetCommState(hComs,&dcb);TimeOuts.ReadIntervalTimeout=0; //读间隔超时TimeOuts.ReadTotalTimeoutMultiplier=10; //读时间系数TimeOuts.ReadTotalTimeoutConstant=100; //读时间常量TimeOuts.WriteTotalTimeoutMultiplier=10; //写时间系数TimeOuts.WriteTotalTimeoutConstant=100; //写时间常数SetCommTimeouts(hComs, &TimeOuts); // 保存设置值生效lpOverlapped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);ComReg = 0;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)==0){ComReg = 2;sprintf(str,"串口%d 与设备PM300未连接上!",(NoComs+1));ComErr = AnsiString(str);Application->MessageBoxA(str,"错误",MB_OK|MB_ICONERROR);}}};void TMSCOMN::SetRs485Coms(int NoComs,int Bps)AnsiString ComNo;DCB dcb;COMMTIMEOUTS TimeOuts;char str[100];ComErr = AnsiString("");if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}ComNo = AnsiString("COM")+AnsiString(NoComs+1);hComs=CreateFile(ComNo.c_str(),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,0);if(hComs == INVALID_HANDLE_VALUE){ComReg = 1; ComErr = AnsiString("串口RS485未打开");Application->MessageBoxA("串口RS485打开出错!","错误",MB_OK|MB_ICONERROR); }else{GetCommState(hComs,&dcb);if(Bps==0) dcb.BaudRate = CBR_300;else if(Bps==1) dcb.BaudRate = CBR_1200;else if(Bps==2) dcb.BaudRate = CBR_2400;else if(Bps==3) dcb.BaudRate = CBR_4800;else if(Bps==4) dcb.BaudRate = CBR_9600;else if(Bps==5) dcb.BaudRate = CBR_19200;else if(Bps==6) dcb.BaudRate = CBR_38400;dcb.ByteSize = 8;dcb.Parity = NOPARITY; //MARKPARITYdcb.StopBits = ONESTOPBIT;SetCommState(hComs,&dcb);TimeOuts.ReadIntervalTimeout=0; //读间隔超时TimeOuts.ReadTotalTimeoutMultiplier=10; //读时间系数TimeOuts.ReadTotalTimeoutConstant=100; //读时间常量TimeOuts.WriteTotalTimeoutMultiplier=10; //写时间系数TimeOuts.WriteTotalTimeoutConstant=100; //写时间常数SetCommTimeouts(hComs, &TimeOuts); // 保存设置值生效lpOverlapped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);ComReg = 0;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)==0){ComReg = 2;sprintf(str,"串口%d 与485设备未连接上!",(NoComs+1));ComErr = AnsiString(str);Application->MessageBoxA(str,"错误",MB_OK|MB_ICONERROR);}}};void TMSCOMN::SendData(char *str,int Len){unsigned long lrc;PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,Len,&lrc,&lpOverlapped);};void TMSCOMN::GetData(char *str,int &Len){COMSTAT cs;DWORD dwError;ClearCommError(hComs,&dwError,&cs);dwError = cs.cbInQue;if(cs.cbInQue>0) ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped); str[dwError]=0;Len = dwError;};float TMSCOMN::StrToFloat(unsigned char *Datas){union{float f;unsigned char c[4];}covf;covf.c[0] = Datas[3];covf.c[1] = Datas[2];covf.c[2] = Datas[1];covf.c[3] = Datas[0];return covf.f;};void TMSCOMN::GetPm300dks(int &dIks , float &dUks){if(SysData.DadoNo==14 && SysData.R1Irang==0) dIks = 2000 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==1) dIks = 1500 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==2) dIks = 1000 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==3) dIks = 500 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==4) dIks = 250 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==5) dIks = 100 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==0) dIks = 4000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==1) dIks = 3000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==2) dIks = 2500 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==3) dIks = 2000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==4) dIks = 1500 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==5) dIks = 1000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==6) dIks = 500 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==7) dIks = 250 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==8) dIks = 100 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==0 && SysData.R1Way==0) dIks = 3000 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==1 && SysData.R1Way==0) dIks = 2000 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==2 && SysData.R1Way==0) dIks = 1000 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==3 && SysData.R1Way==0) dIks = 500 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==4 && SysData.R1Way==0) dIks = 250 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==5 && SysData.R1Way==0) dIks = 100 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==0 && SysData.R1Way==1) dIks = 200 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==0 && SysData.R1Way==0) dIks = 4000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==1 && SysData.R1Way==0) dIks = 3000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==2 && SysData.R1Way==0) dIks = 2500 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==3 && SysData.R1Way==0) dIks = 2000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==4 && SysData.R1Way==0) dIks = 1500 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==5 && SysData.R1Way==0) dIks = 1000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==6 && SysData.R1Way==0) dIks = 500/5;else if(SysData.DadoNo==17 && SysData.R1Irang==7 && SysData.R1Way==0) dIks = 250 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==8 && SysData.R1Way==0) dIks = 100 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==0 && SysData.R1Way==1) dIks = 200 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==0) dIks = 4000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==1) dIks = 3000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==2) dIks = 2500 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==3) dIks = 2000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==4) dIks = 1500 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==5) dIks = 1000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==6) dIks = 500 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==7) dIks = 250 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==8) dIks = 100 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==0) dIks = 2500 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==1) dIks = 1500 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==2) dIks = 1000 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==3) dIks = 500 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==4) dIks = 250 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==5) dIks = 100 /5;else dIks = 1;if(SysData.DadoNo==14) dUks =1;else if(SysData.DadoNo==15) dUks =1;else if(SysData.DadoNo==16 && SysData.R1Urang==0 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==16 && SysData.R1Urang==1 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==16 && SysData.R1Urang==2 && SysData.R1Way==0) dUks = 607.4/209;else if(SysData.DadoNo==16 && SysData.R1Urang==0 && SysData.R1Way==1) dUks = 10000/100;else if(SysData.DadoNo==16 && SysData.R1Urang==1 && SysData.R1Way==1) dUks = 6000 /600;else if(SysData.DadoNo==17 && SysData.R1Urang==0 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==17 && SysData.R1Urang==1 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==17 && SysData.R1Urang==2 && SysData.R1Way==0) dUks = 607.4/209;else if(SysData.DadoNo==17 && SysData.R1Urang==0 && SysData.R1Way==1) dUks = 10000/100;else if(SysData.DadoNo==17 && SysData.R1Urang==1 && SysData.R1Way==1) dUks = 6000 /600;else if(SysData.DadoNo==18) dUks =1;else if(SysData.DadoNo==19) dUks =1;else dUks =1;};void TMSCOMN::SetPM300UI(){int dIks;float dUks;unsigned long fbl;COMSTAT cs;DWORD dwError;GetCommModemStatus(hComs,&Stats);if(Stats&16){GetPm300dks(dIks,dUks);PurgeComm(hComs,PURGE_RXCLEAR);strcpy(FileBuffer,":SEL:CLR\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,":SEL:CH1;:SEL:CH2;:SEL:CH3\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,":SEL:VLT;:SEL:AMP;:SEL:WAT;:SEL:FRQ\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,":CFG1,4\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); sprintf(FileBuffer,":CFG38,%.3f\r",dUks);WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); sprintf(FileBuffer,":CFG39,%d\r",dIks);WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,"*TRG\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); }};void TMSCOMN::BegPM300Data(){unsigned long fbl;COMSTAT cs;DWORD dwError;GetCommModemStatus(hComs,&Stats);if(ComReg==0 && (Stats&16)){strcpy(FileBuffer,":FRD?\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped);ComRs = 1;}};void TMSCOMN::GetPM300UI(double *RData,int RsUu){static int Counts;static char str[1025],StrData[100];int i,j,Len;double dtemp;COMSTAT cs;DWORD dwError;ZeroMemory(str,sizeof(char)*1025);GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0 && ComRs == 1) {ClearCommError(hComs,&dwError,&cs);for(;(dwError==0)&&((Stats)&16);){if(cs.cbInQue>0){Counts = 0;Len = cs.cbInQue;for(i=0;i<Len;i++){ReadFile(hComs,&(FileBuffer[i]),1,&dwError,&lpOverlapped);if(FileBuffer[i]=='\r') { FileBuffer[i+1]=0; break; }}FileBuffer[Len] = 0;strcat(str,FileBuffer);if(FileBuffer[i]=='\r') break;}else{Sleep(50);Counts++;if(Counts > 69) {ResetPm300(); SetPM300UI(); Counts =0; return;}}ClearCommError(hComs,&dwError,&cs);GetCommModemStatus(hComs,&Stats);}ComReg=0;ComErr = AnsiString("");}else if(ComReg==0 ){ComReg=2;ComErr = AnsiString("串口Rs232与Pm300断开连接");MainF->DisplayHint(NULL);}//RData[0] = 230; RData[4] = 230; RData[8] = 230; RData[15] = 230; RData[12] = 50; //RData[3] = 0.9; RData[7] = 0.9; RData[11]= 0.9; RData[14] = 0.9;if(ComReg!=0 ) return;Len=strlen(str);for(i=0,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[2] = atof(StrData)/1000.0;// * SysData.AcLa / 5000;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[6] = atof(StrData)/1000.0;// * SysData.AcLb / 5000;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[10] = atof(StrData)/1000.0;// * SysData.AcLc / 5000;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[0] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[4] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[8] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[1] = atof(StrData);// * SysData.AcLa / 5;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[5] = atof(StrData);// * SysData.AcLb / 5;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[9] = atof(StrData);// * SysData.AcLc / 5;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;if(RsUu==1 || RsUu==4) RData[12] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;if(RsUu==2) RData[12] = atof(StrData);if(RsUu==4) RData[12] = RData[12] + atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;if(RsUu==3) RData[12] = atof(StrData);if(RsUu==4) RData[12] = (RData[12] + atof(StrData))/3.0;dtemp = RData[0]*RData[1];if(dtemp>0.0001) RData[3] = RData[2]*1000/dtemp;else RData[3] = 1;dtemp = RData[4]*RData[5];if(dtemp>0.0001) RData[7] = RData[6]*1000/dtemp;else RData[7] = 1;dtemp = RData[8]*RData[9];if(dtemp>0.0001) RData[11] = RData[10]*1000/dtemp;else RData[11] = 1;if(RData[3] > 1) RData[3] =1; else if(RData[3] < -1) RData[3] =-1;if(RData[7] > 1) RData[7] =1; else if(RData[7] < -1) RData[7] =-1;if(RData[11]> 1) RData[11]=1; else if(RData[11]< -1) RData[11]=-1;if(SysData.R1Udx == 2){if(RsUu==1) {RData[17]=RData[0]*RData[1]/1000.0; RData[13]=RData[2]; RData[14]=RData[3]; RData[15]=RData[0];}else if(RsUu==2) {RData[17]=RData[4]*RData[5]/1000.0; RData[13]=RData[6]; RData[14]=RData[7]; RData[15]=RData[4];}else if(RsUu==3) {RData[17]=RData[8]*RData[9]/1000.0; RData[13]=RData[10]; RData[14]=RData[11]; RData[15]=RData[8];}else if(RsUu==4) {RData[17]=RData[0]*RData[1]/1000.0; RData[13]=RData[2];RData[14]=RData[3]; RData[15]=RData[0];}}else{RData[13] = RData[2] + RData[6] + RData[10];RData[14] = (RData[3] + RData[7] + RData[11])/3.0;RData[15] = (RData[0] + RData[4] + RData[8] )/3.0;RData[17] = (RData[0]*RData[1] + RData[4]*RData[5] + RData[8]*RData[9])/1000.0; }RData[28] = sqrt(fabs(RData[17]*RData[17] - RData[13]*RData[13]));RData[24] = SysData.R1Ux; RData[25] = SysData.R1Fr;RData[26] = SysData.R1Ur; RData[27] = SysData.R1Pr;RData[31] = SysData.R1PF;};void TMSCOMN::ClearPm300Data(double *RData){RData[0] = 0; RData[1] = 0; RData[2] = 0; RData[3] = 1;RData[4] = 0; RData[5] = 0; RData[6] = 0; RData[7] = 1;RData[8] = 0; RData[9] = 0; RData[10]= 0; RData[11]= 1;RData[12]= 0; RData[13]= 0; RData[14]= 1; RData[15]= 0;RData[17]= 0; RData[28]= 0;};void TMSCOMN::ResetPm300(){int dIks;float dUks;unsigned long fbl;COMSTAT cs;DWORD dwError;GetCommModemStatus(hComs,&Stats);if(Stats&16){PurgeComm(hComs,PURGE_TXCLEAR);PurgeComm(hComs,PURGE_RXCLEAR);PurgeComm(hComs,PURGE_TXABORT);PurgeComm(hComs,PURGE_RXABORT);Sleep(100);strcpy(FileBuffer,":DVC\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped);Sleep(3000);}};bool TMSCOMN::SetZW1401dUk(unsigned char Base,float dUK){unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;union{float f;unsigned char c[4];}covf;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0) { ///设置电压倍率系数 0x1f00 str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x00; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dUK;str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT = true; }}return BoolT;};bool TMSCOMN::GetZW1401dUV(unsigned char Base, double &dUs) {unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;double dtemp;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0) {str[0] = Base; str[1] = 0x03;str[2] = 0x10; str[3] = 0x00;str[4] = 0x00; str[5] = 0x02;cov.i=CRC16(str,6);str[6] = cov.c[1]; str[7] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,8,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 9 && str[0]== Base && str[1]==0x03){cov.i=CRC16(str,7);if(str[7] == cov.c[1] && str[8] == cov.c[0]){dUs = StrToFloat(&(str[3])); // 线电压BoolT = true;}}}return BoolT;};bool TMSCOMN::SetZW1402dIk(unsigned char Base,float dIK){unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;union{float f;unsigned char c[4];}covf;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0) { ///设置电流倍率系数 0x1f02 str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x02; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dIK;str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT = true; }}return BoolT;};bool TMSCOMN::GetZW1402dIA(unsigned char Base, double &dIs) {unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;double dtemp;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){str[0] = Base; str[1] = 0x03;str[2] = 0x10; str[3] = 0x02;str[4] = 0x00; str[5] = 0x02;cov.i=CRC16(str,6);str[6] = cov.c[1]; str[7] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,8,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 9 && str[0]== Base && str[1]==0x03){cov.i=CRC16(str,7);if(str[7] == cov.c[1] && str[8] == cov.c[0]){dIs = StrToFloat(&(str[3])); // 中线电流BoolT = true;}}}return BoolT;};bool TMSCOMN::SetZW5433dUIk(unsigned char Base, float dUk, float dIk){unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;union{float f;unsigned char c[4];}covf;bool BoolT1 = false , BoolT2 = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){ ///设置电压与电流倍率系数 0x1f00 0x1f02 str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x00; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dUk; //设置电压倍率系数 0x1f00str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT1 = true; }str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x02; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dIk; //设置电流倍率系数 0x1f02str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT2 = true; }}return (BoolT1 && BoolT2);};bool TMSCOMN::GetZW5433dPQ(unsigned char Base, double &dPs, double &dQs) {unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;double dtemp;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){str[0] = Base; str[1] = 0x03;str[2] = 0x16; str[3] = 0x14;str[4] = 0x00; str[5] = 0x06;cov.i=CRC16(str,6);str[6] = cov.c[1]; str[7] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,8,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 17 && str[0]==Base && str[1]==0x03){cov.i=CRC16(str,15);if(str[15] == cov.c[1] && str[16] == cov.c[0]){dPs = StrToFloat(&(str[3])) /1000.0; // 并联总有功dQs = StrToFloat(&(str[11]))/1000.0; // 并联总无功BoolT = true;}}}return BoolT;};void TMSCOMN::OutSideSend(double dU,double dI,double df,double dP){int i,IdU,IdF,IdA,IdP;unsigned char str[255];unsigned long lrc;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){if(dU>999.9) IdU = dU/100.0;else IdU = dU*10;IdA = dI;IdF = df*10;IdP = dP;if((dU*10 - IdU)>0.5) IdU++;if((dI - IdA)>0.5) IdA++;if((df*10 - IdF)>0.5) IdF++;if((dP - IdP)>0.5) IdP++;if(IdU<0 || IdU>9999) IdU = 0;if(IdA<0 || IdA>9999) IdA = 0;if(IdF<0 || IdF>9999) IdF = 0;if(IdP<0 || IdP>9999) IdP = 0;ZeroMemory(str,sizeof(char)*250);sprintf(str,":%04d%04d%04d%04d;",IdF,IdU,IdA,IdP);str[0] = 0xFF;for(i=1;i<17;i++) str[i]= str[i] - 0x30;str[1] = (str[1]<<4) + (str[2] & 0x0F);str[2] = (str[3]<<4) + (str[4] & 0x0F);str[3] = (str[5]<<4) + (str[6] & 0x0F);str[4] = (str[7]<<4) + (str[8] & 0x0F);str[5] = (str[9]<<4) + (str[10] & 0x0F);str[6] = (str[11]<<4)+ (str[12] & 0x0F);str[7] = (str[13]<<4)+ (str[14] & 0x0F);str[8] = (str[15]<<4)+ (str[16] & 0x0F);str[9] = (str[1]+str[2] + str[3]+str[4] + str[5]+str[6] + str[7]+str[8]) & 0x7F;PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,10,&lrc,&lpOverlapped);Sleep(50);} };。
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)不是从窗口派生的。
详解RS485通讯程序代码及技术介绍
} } //主函数 void main() { DDRD|=BIT(PD2); //PORTD|=BIT(PD2); USART_Init(); //UART_Puts("\r\n 你发送的字符串是:");//发送字符串 PORTD&=~BIT(PD2); DDRD|=BIT(PD2); while(1) { if(RX_Flag)
{
PORTD|=BIT(PD2);
//UART_Puts();
USART_Send('1');
//USART_Send(RX_Buffer);
RX_Flag=0;
PORTD&=~BIT(PD2);
PORTD|=BIT(PD2);
//UART_Puts();
USART_Send('2');
//USART_Send(RX_Buffer);
HART 网络:HART 是由现在的艾默生提出一个过度性总线标准,他主要是在 4~20 毫安电流信号上面叠加数字信号,物理层采用 BELL202 频移键控技术,以 实现部分智能仪表的功能,但此协议不是一个真正意义上开放的标准,要加入他 的基金会才能拿到协议,加入基金会要一部分的费用。技术主要被国外几家大公 司垄断,近两年国内也有公司再做,但还没有达到国外公司的水平。现在有很大 一部分的智能仪表都带有 HART 圆卡,都具备 HART 通讯功能。但从国内来看还没 有真正利用其这部分功能,最多只是利用手操器对其进行参数设定,没有发挥出 HART 智能仪表应有的功能,没有联网进行设备监控。从长远来看由于 HART 通信 速率低组网困难等原因,HART 仪表的采购量会程下滑趋势,但由于 HART 仪表已 经有十多年的历史现在在装数量非常的大,对于一些系统集成商来说还有很大的 可利用空间。
「51单片机」RS232串口通信代码分析
「51单⽚机」RS232串⼝通信代码分析想来想去不知道要怎么样把232串⼝通信说清楚,想想还是直接把代码分析⼀遍吧...重点是“常⽤波特率与定时器1的参数关系”这张表格!波特率的设置很重要!⼀、串⼝初始化void usart_init(){SCON = 0x50; //REN=1允许串⾏接受状态,串⼝⼯作模式1TMOD = 0x20; //定时器⼯作⽅式2PCON = 0x00;TH1 = 0xFD; //波特率9600、数据位8、停⽌位1。
效验位⽆ (11.0592M)TL1 = 0xFD;ES = 1; //开串⼝中断EA = 1; //开总中断TR1 = 1; //启动定时器}SCON寄存器1.SM0、SM1:串⾏⼝⼯作⽅式控制位2.SM2:多机通信控制位3.REN:允许接收位4.TB8:发送接收数据位85.RB8:接收数据位86.TI:发送中断标志位 TI=1表⽰帧发送结束7.RI:接收中断标志位 RI=1表⽰帧接收完成1.GATE:门控制位 GATE=0,仅受TRX控制 GATE=1,受TRX和外部中断引脚共同控制2.C/T:定时器模式和计数器模式选择器 C/T=1,计数器 C/T=0,定时器3.M1、M0:⼯作⽅式选择位PCON寄存器SMOD:是波特率是否加倍的选择位。
SMOD=0时:波特率不加倍。
SMOD=1时:波特率加倍。
⼆、串⼝数据发送void send_data(unsigned char a){SBUF = a; //SUBF接受/发送缓冲器while(0 == TI); //每次等待发送完毕,再执⾏下⼀条TI=0; //⼿动清0}SBUF:有两个物理上独⽴的接收、发送缓冲器SBUF,它们占⽤同⼀地址99H ;接收器是双缓冲结构;发送缓冲器,因为发送时CPU是主动的,不会产⽣重叠错误。
TI:发送中断标志位 TI=1表⽰帧发送结束三、串⼝中断程序void ser_int (void) interrupt 4using1{if(1 == RI) //RI接受中断标志{RI = 0; //清除RI接受中断标志ReData = SBUF; //SUBF接受/发送缓冲器Flag=1; //标志位置1表⽰有新数据进来}}RI:接收中断标志位 RI=1表⽰帧接收完成四、总代码#include<reg51.h>//变量声明unsigned char SenData, //发送数据Flag, //标志位ReData; //接收数据//函数声明void usart_init(); //串⼝中断初始化void send_data(unsigned char a); //串⼝数据发送//---------------------------//串⼝中断初始化//---------------------------void usart_init(){SCON = 0x50; //REN=1允许串⾏接受状态,串⼝⼯作模式1TMOD = 0x20; //定时器⼯作⽅式2PCON = 0x00;TH1 = 0xFD; //波特率9600、数据位8、停⽌位1。
c#上位机串口通信助手源代码详解
c#上位机串口通信助手源代码实例详解一、功能1软件打开时,自动检测有效COM端口2 软件打开时,自动复原到上次关闭时的状态3 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开4 可统计接收字节和发送字节的个数5 接收数据可按16进制数据和非16进制数据进行整体转换6 可将接收到数据进行保存7 可设置自动发送,发送时间可进行实时更改8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰9 按16进制发送时,可自动校验格式,不会输错10 可清空发送或接收区域的数据二、使用工具Visual Studio2015三、程序详解1 界面创建图1用winform创建如图1所示界面,控件名字分别为:端口号:cbxCOMPort 波特率:cbxBaudRate数据位:cbxDataBits 停止位:cbxStopBits校验位:label5 打开串口按钮:btnOpenCom发送(byte):tbSendCount 接收(byte):tbReceivedCount 清空计数按钮:btnClearCount 按16进制显示:cb16Display接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile接收数据框:tbReceivedData 发送数据框:tbSendData自动发送:cbAutomaticSend 间隔时间:tbSpaceTime按16进制发送:cb16Send 发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile 发送按钮:btnSend2 创建一个方法类按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:using System;using System.Collections;using System.Collections.Generic;using System.IO.Ports;using System.Linq;using System.Text;using System.Threading.Tasks;namespace串口助手sdd{class Methods{//获取有效的COM口public static string[] ActivePorts(){ArrayList activePorts = new ArrayList();foreach (string pname in SerialPort.GetPortNames()){activePorts.Add(Convert.ToInt32(pname.Substring(3)));}activePorts.Sort();string[] mystr = new string[activePorts.Count];int i = 0;foreach (int num in activePorts){mystr[i++] = "COM" + num.ToString();}return mystr;}//16进制字符串转换为byte字符数组public static Byte[] _16strToHex(string strValues){string[] hexValuesSplit = strValues.Split(' ');Byte[] hexValues = new Byte[hexValuesSplit.Length];Console.WriteLine(hexValuesSplit.Length);for (int i = 0; i < hexValuesSplit.Length; i++){hexValues[i] = Convert.ToByte(hexValuesSplit[i], 16);}return hexValues;}//byte数组以16进制形式转字符串public static string ByteTo16Str(byte[] bytes){string recData = null;//创建接收数据的字符串foreach (byte outByte in bytes)//将字节数组以16进制形式遍历到一个字符串内 {recData += outByte.ToString("X2") + " ";}return recData;}//16进制字符串转换字符串public static string _16strToStr(string _16str){string outStr = null;byte[] streamByte = _16strToHex(_16str);outStr = Encoding.Default.GetString(streamByte);return outStr;}}}2 Form1.cs的代码为:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.IO.Ports;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Collections;namespace串口助手sdd{public partial class Form1 : Form{//声明变量SerialPort sp = new SerialPort();bool isSetProperty = false;//串口属性设置标志位private enum PortState//声明接口显示状态,枚举型{打开,关闭}string path = AppDomain.CurrentDomain.BaseDirectory + "confing.ini";//声明配置文件路径string tbSendDataStr = "";//发送窗口字符串存储string tbSendData16 = "";//发送窗口16进制存储List<byte> receivedDatas = new List<byte>();//接收数据泛型数组//接收串口数据private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) {byte[] ReceivedData = new byte[sp.BytesToRead];//创建接收字节数组sp.Read(ReceivedData, 0, ReceivedData.Length);//读取所接收到的数据receivedDatas.AddRange(ReceivedData);tbReceivedCount.Text = (Convert.ToInt32(tbReceivedCount.Text) + ReceivedData.Length).ToString();if (cb16Display.Checked)tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());sp.DiscardInBuffer();//丢弃接收缓冲区数据}//发送串口数据private void DataSend(){try{if (cb16Send.Checked){byte[] hexBytes = Methods._16strToHex(tbSendData16);sp.Write(hexBytes, 0, hexBytes.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + hexBytes.Length).ToString();}else{sp.WriteLine(tbSendDataStr);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + tbSendDataStr.Length).ToString();}}catch (Exception ex){MessageBox.Show(ex.Message.ToString());return;}}//设置串口属性private void SetPortProperty(){sp.PortName = cbxCOMPort.Text.Trim();//设置串口名sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//设置波特率switch (cbxStopBits.Text.Trim())//设置停止位{case"1": sp.StopBits = StopBits.One; break;case"1.5": sp.StopBits = StopBits.OnePointFive; break;case"2": sp.StopBits = StopBits.Two; break;default: sp.StopBits = StopBits.None; break;}sp.DataBits = Convert.ToInt32(cbxDataBits.Text.Trim());//设置数据位switch (cbxParity.Text.Trim())//设置奇偶校验位{case"无": sp.Parity = Parity.None; break;case"奇校验": sp.Parity = Parity.Odd; break;case"偶校验": sp.Parity = Parity.Even; break;default: sp.Parity = Parity.None; break;}sp.ReadTimeout = 5000;//设置超时时间为5sControl.CheckForIllegalCrossThreadCalls = false;//这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)//定义DataReceived事件的委托,当串口收到数据后出发事件sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);}//设置端口显示状态private void DisplayPortState(PortState portState){toolStripStatusLabel1.Text = cbxCOMPort.Text + "端口处于" + portState + "状态 " + cbxBaudRate.Text + " " + cbxDataBits.Text + " " + cbxStopBits.Text + " " + cbxParity.Text;}//重新打开串口private void AgainOpenPort(){if (sp.IsOpen){try{sp.Close();SetPortProperty();isSetProperty = true;sp.Open();}catch (Exception){isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);MessageBox.Show("串口无效或已被占用!", "错误提示");return;}DisplayPortState(PortState.打开);}else{DisplayPortState(PortState.关闭);}}public Form1(){InitializeComponent();}//软件启动时加载事件private void Form1_Load(object sender, EventArgs e){#region加载配置文件Hashtable ht = new Hashtable();if (File.Exists(path)){try{string myline = "";string[] str = new string[2];using (StreamReader sr = new StreamReader(path)) {myline = sr.ReadLine();while (myline != null){str = myline.Split('=');ht.Add(str[0], str[1]);myline = sr.ReadLine();}}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}#endregion#region设置窗口为固定大小且不可最大化this.MaximumSize = this.Size;this.MinimumSize = this.Size;this.MaximizeBox = false;#endregion#region列出常用的波特率cbxBaudRate.Items.Add("1200");cbxBaudRate.Items.Add("2400");cbxBaudRate.Items.Add("4800");cbxBaudRate.Items.Add("9600");cbxBaudRate.Items.Add("19200");cbxBaudRate.Items.Add("38400");cbxBaudRate.Items.Add("43000");cbxBaudRate.Items.Add("56000");cbxBaudRate.Items.Add("57600");cbxBaudRate.Items.Add("115200");if (ht.ContainsKey("cbxBaudRate"))cbxBaudRate.SelectedIndex =cbxBaudRate.Items.IndexOf(ht["cbxBaudRate"].ToString());elsecbxBaudRate.SelectedIndex = 3;cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出停止位cbxStopBits.Items.Add("1");cbxStopBits.Items.Add("1.5");cbxStopBits.Items.Add("2");if (ht.ContainsKey("cbxStopBits"))cbxStopBits.SelectedIndex =cbxStopBits.Items.IndexOf(ht["cbxStopBits"].ToString());elsecbxStopBits.SelectedIndex = 0;cbxStopBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出数据位cbxDataBits.Items.Add("8");cbxDataBits.Items.Add("7");cbxDataBits.Items.Add("6");cbxDataBits.Items.Add("5");if (ht.ContainsKey("cbxDataBits"))cbxDataBits.SelectedIndex =cbxDataBits.Items.IndexOf(ht["cbxDataBits"].ToString());elsecbxDataBits.SelectedIndex = 0;cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出奇偶校验位cbxParity.Items.Add("无");cbxParity.Items.Add("奇校验");cbxParity.Items.Add("偶校验");if (ht.ContainsKey("cbxParity"))cbxParity.SelectedIndex =cbxParity.Items.IndexOf(ht["cbxParity"].ToString());elsecbxParity.SelectedIndex = 0;cbxParity.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region COM口重新加载cbxCOMPort.Items.Clear();//清除当前串口号中的所有串口名称 cbxCOMPort.Items.AddRange(Methods.ActivePorts());if (ht.ContainsKey("cbxCOMPort") &&cbxCOMPort.Items.Contains(ht["cbxCOMPort"].ToString()))cbxCOMPort.SelectedIndex =cbxCOMPort.Items.IndexOf(ht["cbxCOMPort"].ToString());elsecbxCOMPort.SelectedIndex = 0;cbxCOMPort.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region初始化计数器tbSendCount.Text = "0";tbSendCount.ReadOnly = true;tbReceivedCount.Text = "0";tbReceivedCount.ReadOnly = true;#endregion#region初始化当前时间toolStripStatusLabel3.Text = DateTime.Now.ToString();#endregion#region初始化串口状态toolStripStatusLabel1.ForeColor = Color.Blue;if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }#endregion#region初始化间隔时间if (ht.ContainsKey("tbSpaceTime"))tbSpaceTime.Text = ht["tbSpaceTime"].ToString();elsetbSpaceTime.Text = "1000";#endregion#region初始化按16进制显示状态if (ht.ContainsKey("cb16Display") && ht["cb16Display"].ToString() == "True") cb16Display.Checked = true;elsecb16Display.Checked = false;#endregion#region初始化按16进制发送状态if (ht.ContainsKey("cb16Send") && ht["cb16Send"].ToString() == "True")cb16Send.Checked = true;elsecb16Send.Checked = false;#endregion#region初始化发送区文本if(ht.ContainsKey("tbSendData16") && ht.ContainsKey("tbSendDataStr")){tbSendData16 = ht["tbSendData16"].ToString();tbSendDataStr = ht["tbSendDataStr"].ToString();if (cb16Send.Checked)tbSendData.Text = ht["tbSendData16"].ToString();elsetbSendData.Text = ht["tbSendDataStr"].ToString();}#endregiontbSendData.Focus();}//显示当前时间private void timer1_Tick(object sender, EventArgs e){toolStripStatusLabel3.Text = DateTime.Now.ToString();}//点击打开串口按钮private void btnOpenCom_Click(object sender, EventArgs e){if (!sp.IsOpen)//串口没有打开时{if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }}else//串口已经打开{try{sp.Close();isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);}catch (Exception){MessageBox.Show("关闭串口时发生错误", "错误提示"); }}}//发送串口数据private void btnSend_Click(object sender, EventArgs e){if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{MessageBox.Show("请输入要发送的数据!", "错误提示");return;}if (sp.IsOpen){DataSend();}else{MessageBox.Show("串口未打开!", "错误提示");}}//点击端口号选择下拉框按钮private void cbxCOMPort_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击波特率选择下拉框按钮private void cbxBaudRate_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击数据位选择下拉框按钮private void cbxDataBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击停止位选择下拉框按钮private void cbxStopBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击校验位选择下拉框按钮private void cbxParity_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击数据接收区清空按钮private void btnClearReceived_Click(object sender, EventArgs e){receivedDatas.Clear();tbReceivedData.Text = "";}//点击是否按16进制显示接收数据private void cb16Display_CheckedChanged(object sender, EventArgs e){if (cb16Display.Checked)tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());//点击是否按16进制发送数据private void cb16Send_CheckedChanged(object sender, EventArgs e){if (cb16Send.Checked){tbSendData.Text = tbSendData16;}else{tbSendData.Text = tbSendDataStr;}}//发送文本框键盘按键检测private void tbSendData_KeyPress(object sender, KeyPressEventArgs e){if (cb16Send.Checked){//正则匹配string pattern = "[0-9a-fA-F]|\b";//\b:退格键Match m = Regex.Match(e.KeyChar.ToString(), pattern);if (m.Success){if(e.KeyChar != '\b'){if (tbSendData.Text.Length % 3 == 2){tbSendData.Text += " ";tbSendData.SelectionStart = tbSendData.Text.Length;}e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper()); }e.Handled = false;}else{e.Handled = true;}}else{e.Handled = false;}}//点击清空发送内容private void btnClearSend_Click(object sender, EventArgs e){tbSendData.Text = "";if (cb16Send.Checked)tbSendData16 = "";elsetbSendDataStr = "";//点击清空计数器数据private void btnClearCount_Click(object sender, EventArgs e){tbReceivedCount.Text = "0";tbSendCount.Text = "0";}//点击是否设置自动发送private void cbAutomaticSend_CheckedChanged(object sender, EventArgs e) {if (cbAutomaticSend.Checked){timer2.Enabled = true;timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);}else{timer2.Enabled = false;}}//自动发送时间文本框键盘按键检测private void tbSpaceTime_KeyPress(object sender, KeyPressEventArgs e) {//正则匹配string pattern = "[0-9]|\b";Match m = Regex.Match(e.KeyChar.ToString(),pattern);if (m.Success){timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);e.Handled = false;}else{e.Handled = true;}}//串口显示状态private void timer2_Tick(object sender, EventArgs e){if (sp.IsOpen){DataSend();}else{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("串口未打开!", "错误提示");return;}if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("请输入要发送的数据!", "错误提示");return;}}//关闭窗口时出发的事件private void Form1_FormClosed(object sender, FormClosedEventArgs e){try{using (StreamWriter sw = new StreamWriter(path, false)){sw.WriteLine("cbxCOMPort=" + cbxCOMPort.Text);sw.WriteLine("cbxBaudRate=" + cbxBaudRate.Text);sw.WriteLine("cbxDataBits=" + cbxDataBits.Text);sw.WriteLine("cbxStopBits=" + cbxStopBits.Text);sw.WriteLine("cbxParity=" + cbxParity.Text);sw.WriteLine("cb16Display="+ cb16Display.Checked.ToString()); sw.WriteLine("tbSpaceTime=" + tbSpaceTime.Text);sw.WriteLine("cb16Send=" + cb16Send.Checked.ToString());sw.WriteLine("tbSendDataStr=" + tbSendDataStr);sw.WriteLine("tbSendData16=" + tbSendData16);sp.Close();}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}//发送文本框按键抬起时出发的事件private void tbSendData_KeyUp(object sender, KeyEventArgs e){if (cb16Send.Checked){tbSendData16 = tbSendData.Text.Trim();}else{tbSendDataStr = tbSendData.Text;}}//点击读入文件按钮private void btnReadFile_Click(object sender, EventArgs e){openFileDialog1.Filter = "所有文件(*.*)|*.*";//文件筛选器的设定openFileDialog1.FilterIndex = 1;openFileDialog1.Title = "选择文件";openFileDialog1.FileName = "";openFileDialog1.ShowHelp = true;if(openFileDialog1.ShowDialog() == DialogResult.OK){using (FileStream fs = newFileStream(openFileDialog1.FileName,FileMode.Open)){byte[] bufferByte = new byte[fs.Length];fs.Read(bufferByte, 0, Convert.ToInt32(fs.Length));sp.Write(bufferByte, 0, bufferByte.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + bufferByte.Length).ToString();}}}//点击保存数据按钮private void btnSaveFile_Click(object sender, EventArgs e){saveFileDialog1.Filter = "所有文件(*.*)|*.*";if(saveFileDialog1.ShowDialog() == DialogResult.OK){string fName = saveFileDialog1.FileName;using(FileStream fs = File.Open(fName, FileMode.Append)){fs.Write(receivedDatas.ToArray(), 0, receivedDatas.Count);}}}}}需要源代码或有疑问的c#爱好者们,欢迎加入c#技术交流群(33647125),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。
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;}。
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;}/*监视串口错误时使用的函数*/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,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;}bool openport(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;}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 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;}/*串口读取相关时间设置*/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;elsereturn true;}int Clearn() //清除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}}}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 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:{int ctr;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);}。
WinCC串口通信代码
objMSComm.RThreshold=1
objMSComm.SThreshold=0
objMSComm.InBufferCount=0
objMSComm.InputLen=0
objMSComm.PortOpen=Ture
tagConnection.Write(Ture)
通过MSComm控件进行WINCC串口通讯
一、通过C脚本实现串口通讯
画面对象“打开画面”C事件脚本
#include“apdefap.h”
Viod OnOpenPicture(char*IpszPictureName,char*IpszObjectName,char*IpszPropertyName)
if(pic)
{
printf(“portopen get pic ok”);
}
obj=pic->GetObject(“COM”);
if(obj)
{
printf(“portopen get obj ok”);
}
SetTagChar(“BufferTemp”,obj->Input);
Printf(“BufferTemp:%s”,GetTagChar(“BufferTemp”));
HMIRuntime.Trace(“4#Port open.”& vbCrLf)
Else
HMIRuntime.Trace(“4# Port is already opened.”& vbCrLf)
End If
End Sub
MSComm控件OnComm对象事件
Sub OnOpen()
Dim objMSComm, tagConnection
51单片机与串口通信代码
51单片机与串口通信代码串口调试1. 发送:向总线上发命令2. 接收:从总线接收命令,并分析是地址还是数据。
3. 定时发送:从内存中取数并向主机发送.经过调试,以上功能基本实现,目前可以通过上位机对单片机进行实时控制。
程序如下://这是一个单片机C51串口接收(中断)和发送例程,可以用来测试51单片机的中断接收//和查询发送,另外我觉得发送没有必要用中断,因为程序的开销是一样的#i nclude <reg51.h>#i nclude<stdio.h>#i nclude <string.h>#define INBUF_LEN 4 //数据长度unsigned char inbuf1[INBUF_LEN];unsigned char checksum,count3 , flag,temp,ch;bit read_flag=0;sbit cp=P1^1;sbit DIR=P1^2;int i;unsigned int xdata *RAMDATA; /*定义RAM地址指针*/unsigned char a[6] ={0x11,0x22,0x33,0x44,0x55,0x66} ;void init_serialcomm(void){SCON=0x50; //在11.0592MHz下,设置串行口波特率为9600,方式1,并允许接收PCON=0x00;ES=1;TMOD=0x21; //定时器工作于方式2,自动装载方式 TH0=(65536-1000)%256;TL0=(65536-1000)/256;TL1=0xfd;TH1=0xfd;ET0=1;TR0=1;TR1=1;// TI=0;EA=1;// TI=1;RAMDATA=0x1F45;}void serial () interrupt 4 using 3{if(RI){ RI=0;ch=SBUF;TI=1; //置SBUF空switch(ch){case 0x01 :printf("A"); TI=0;break;case 0x02 :printf("B"); TI=0;break;case 0x03 :printf("C"); TI=0;break;case 0x04 :printf("D"); TI=0;break; default :printf("fg"); TI=0;break; }}}//向串口发送一个字符void timer0() interrupt 1 using 3{// char i;flag++;TH0=0x00;TL0=0x00;if(flag==10){// cp=!cp;// for(i=0;i<6;i++)P2=0x25;TI=1;temp=*RAMDATA;printf("%c",temp); TI=0;// RAMDATA--;flag=0;}}//主程序main(){init_serialcomm(); //初始化串口//向6264中送数据{*RAMDATA=0x33;}while(1){*RAMDATA=0x33;;}}调试过程中遇到的问题:1. 发送过程:在发送时必须保证TI=1:即发送缓冲器为空,否则将导致数据发不出去,如果想强制发送可以用:TI=1.具体发送数据:利用printf(“akjdfaklfj”);函数直接发送即可。
STM32串口通信-代码实现
STM32串⼝通信-代码实现代码实现功能实现:与上位机进⾏通信宏定义需要的GPIO//头⽂件中的引脚宏定义#ifndef _USART_H#define _USART_H#include "stm32f10x.h"#include <stdio.h>// 串⼝1-USART1//#define USART1 USART1#define USART1_CLK RCC_APB2Periph_USART1#define USART1_APBxClkCmd RCC_APB2PeriphClockCmd#define USART1_BAUDRATE 115200// USART GPIO 引脚宏定义#define USART1_GPIO_CLK (RCC_APB2Periph_GPIOA)#define USART1_GPIO_APBxClkCmd RCC_APB2PeriphClockCmd#define USART1_TX_GPIO_PORT GPIOA#define USART1_TX_GPIO_PIN GPIO_Pin_9#define USART1_RX_GPIO_PORT GPIOA#define USART1_RX_GPIO_PIN GPIO_Pin_10#define USART1_IRQ USART1_IRQn#define USART1_IRQHandler USART1_IRQHandlervoid USART_Config(void);void Usart_SendByte(USART_TypeDef *TX, uint8_t data);void Usart_Two_SendByte(USART_TypeDef *TX_usart, uint16_t data);void Usart_SendArray(USART_TypeDef *TX_usart, uint8_t *array, uint8_t num);void Usart_SendStr(USART_TypeDef *TX_usart, uint8_t *str);#endif串⼝初始化配置//这⾥只在这个函数使⽤可⽤static限制⼀下//中断分组配置函数static void NVIC_Configuration(void){NVIC_InitTypeDef NVIC_InitStructure;/* 嵌套向量中断控制器组选择 */NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);/* 配置USART为中断源 */NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQ;/* 抢断优先级*/NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;/* ⼦优先级 */NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;/* 使能中断 */NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;/* 初始化配置NVIC */NVIC_Init(&NVIC_InitStructure);}//串⼝初始化函数void USART_Config(void){GPIO_InitTypeDef GPIO_InitStructure;USART_InitTypeDef USART_InitStructure;// 打开串⼝GPIO的时钟//DEBUG_USART_GPIO_APBxClkCmd(DEBUG_USART_GPIO_CLK, ENABLE);RCC_APB2PeriphClockCmd(USART1_GPIO_CLK, ENABLE);// 打开串⼝外设的时钟//DEBUG_USART_APBxClkCmd(DEBUG_USART_CLK, ENABLE);RCC_APB2PeriphClockCmd(USART1_CLK, ENABLE);//将USART TX的GPIO配置为推挽复⽤模式GPIO_InitStructure.GPIO_Pin = USART1_TX_GPIO_PIN;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(USART1_TX_GPIO_PORT,&GPIO_InitStructure);//将USART RX的GPIO配置为浮空输⼊模式GPIO_InitStructure.GPIO_Pin = USART1_RX_GPIO_PIN;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(USART1_RX_GPIO_PORT, &GPIO_InitStructure);//配置串⼝的⼯作参数//波特率USART_ART_BaudRate = USART1_BAUDRATE;// 配置针数据字长USART_ART_WordLength = USART_WordLength_8b;// 配置停⽌位USART_ART_StopBits = USART_StopBits_1;// 配置校验位USART_ART_Parity = USART_Parity_No ;// 配置硬件流控制USART_ART_HardwareFlowControl =USART_HardwareFlowControl_None;// 配置⼯作模式,收发⼀起USART_ART_Mode = USART_Mode_Rx | USART_Mode_Tx; // 完成串⼝的初始化配置USART_Init(USART1, &USART_InitStructure);// 串⼝中断优先级配置NVIC_Configuration();// 使能串⼝接收中断USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);// 使能串⼝USART_Cmd(USART1, ENABLE);}给上位机发送数据提⽰:下⾯这些函数都在usart.c中哦(⊙o⊙)发送⼀个字节void Usart_SendByte(USART_TypeDef *TX_usart, uint8_t data){USART_SendData(TX_usart,data);//检测串⼝发送的数据//若没有数据来就会⼀直等待while(USART_GetFlagStatus(TX_usart,USART_FLAG_TXE) == RESET);发送两个字节void Usart_Two_SendByte(USART_TypeDef *TX_usart, uint16_t data){uint8_t temp_h,temp_l;temp_h = (data&0xff00) >> 8;temp_l = data&0xff;//发送⾼⼋位USART_SendData(TX_usart,temp_h);while(USART_GetFlagStatus(TX_usart,USART_FLAG_TXE) == RESET);//发送低⼋位USART_SendData(TX_usart,temp_l);while(USART_GetFlagStatus(TX_usart,USART_FLAG_TXE) == RESET);}发送⼋位数组void Usart_SendArray(USART_TypeDef *TX_usart, uint8_t *array, uint8_t num) {uint8_t i;for(i=0; i<num; i++){Usart_SendByte(TX_usart,array[i]);}while(USART_GetFlagStatus(TX_usart,USART_FLAG_TC) == RESET);}发送字符串void Usart_SendStr(USART_TypeDef *TX_usart, uint8_t *str){uint8_t i = 0;do{Usart_SendByte(TX_usart,str[i]);i++;}while(str[i] != '\0');while(USART_GetFlagStatus(TX_usart,USART_FLAG_TC) == RESET);}注意:要勾选keil中的 ues MicroLIB选项重定向c库函数调⽤//重定向c库函数printf到串⼝,重定向后可使⽤printf函数int fputc(int ch, FILE *f){/* 发送⼀个字节数据到串⼝ */USART_SendData(USART1, (uint8_t) ch);/* 等待发送完毕 */while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); return (ch);}//重定向c库函数scanf到串⼝,重写向后可使⽤scanf、getchar等函数int fgetc(FILE *f){/* 等待串⼝输⼊数据 */while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); return (int)USART_ReceiveData(USART1);}主程序测试#include "stm32f10x.h"#include "led.h"#include "key.h"#include "systick.h"#include "usart.h"int main(void){uint8_t array[] = {0x00,0x01,0x03,0x04,0x05};USART_Config();Usart_SendByte(USART1,100);Usart_Two_SendByte(USART1,0xff00);Usart_SendArray(USART1,array,5);Usart_SendStr(USART1,"陈⼀⼀哇龘\n");printf("chen yi yi wa\n\n\n\n");while(1){}}。
vb串口通讯代码
严重同意ZZJ1382的观点,可是在wincc里使用VBS还是还是很困难,不知道哪位能说明白一点。
下面是我在VB里的代码,已经测试过,可以读取串口数据,希望有一位高手帮忙研究在wincc中使用,谢谢!Dim SMSType As IntegerDim Senddata() As ByteDim Readsmsno As ByteSub opentestnote()wrap$ = Chr$(13) & Chr$(10)CommonDialog1.Filter = "text filer (*.txt)|*.txt"CommonDialog1.FileName = ""CommonDialog1.ShowOpen '使用通用对话框对象提示用户输入路径名'If Err = cdlCancel Then Exit SubIf CommonDialog1.FileName <> "" ThenForm1.MousePointer = 11Open CommonDialog1.FileName For Input As #1 '打开用户所指定的输入文件(Open...For Input)On Error GoTo toobig ' 处理所有可能发生的错误Do Until EOF(1) '复制过程直至达到文件尾(EOF)或者字符串空间全部被占满为止Line Input #1, lineoftext$ '将文件逐行复制到名为AllText$的字符串中(Line Input)alltext$ = alltext$ & lineoftext$ & wrap$ '在文本框中显示AllText$字符串,并提供滚动条'LoopClose #1Form1.MousePointer = 0Text3.Text = alltext$End IfGoTo nextfiletoobig:nextfile:End SubSub savetestnote()wrap$ = Chr$(13) & Chr$(10)CommonDialog1.Filter = "text filer (*.txt)|*.txt"CommonDialog1.ShowSave '使用通用对话框对象提示用户输入路径名If CommonDialog1.FileName <> "" ThenOpen CommonDialog1.FileName For Output As #3 'COPY到记录Print #3, Text1.TextClose #3End IfEnd SubSub cleartestnote()Form1.Text1.Text = ""End SubFunction ASCNUM(TXT As String) As Bytei = Asc(TXT)Select Case Asc(TXT)Case 48 ASCNUM = 0 Case 49 ASCNUM = 1 Case 50 ASCNUM = 2 Case 51 ASCNUM = 3 Case 52 ASCNUM = 4 Case 53 ASCNUM = 5 Case 54 ASCNUM = 6 Case 55 ASCNUM = 7 Case 56 ASCNUM = 8 Case 57 ASCNUM = 9Case 65ASCNUM = 10Case 66ASCNUM = 11Case 67ASCNUM = 12Case 68ASCNUM = 13Case 69ASCNUM = 14Case 70ASCNUM = 15Case ElseASCNUM = 16End SelectEnd FunctionPrivate Sub Cls_Click() frmProperties.Show vbModal End SubPrivate Sub Print_Click() Form1.Text1 = bufferEnd SubPrivate Sub Init_Click()sign = 0mPort = 1If MSComm1.PortOpen = False ThenMSComm1.Settings = "9600,n,8,1"MSComm1.PortOpen = TrueEnd IfMSComm1.OutBufferCount = 0MSComm1.InBufferCount = 0MSComm1.Output = Chr$(2) & Chr$(27) & "]R" & Chr$(3) MSComm1.Output = Chr$(2) & Chr$(27) & "ZB1" & Chr$(3)buffer = ""End SubPrivate Sub Form_Load()'设置串口Settings = GetSetting(App.Title, "属性", "设置", "") ' frmTerminal.MSComm1.Settings] If Settings <> "" Then MSComm1.Settings = SettingsIf Err ThenMsgBox Error$, 48Exit SubEnd IfElseMSComm1.Settings = "2400,N,8,1"End IfCommPort = GetSetting(App.Title, "属性", "通信端口", "") ' mPortIf CommPort <> "" ThenmPort = CommPortElsemPort = 1End IfHandshaking = GetSetting(App.Title, "属性", "握手", "") 'frmTerminal.MSComm1.HandshakingIf Handshaking <> "" ThenMSComm1.Handshaking = HandshakingIf Err ThenMsgBox Error$, 48Exit SubEnd IfElseMSComm1.Handshaking = 0End IfTHESMSTYPE = GetSetting(App.Title, "属性", "SMS", "") ' mPortIf THESMSTYPE <> "" ThenSMSType = Val(THESMSTYPE)ElseSMSType = 1End IfTHENUMBER = GetSetting(App.Title, "属性", "NUMBER", "") ' mPortIf THENUMBER <> "" ThenEnd IfReadsmsno = 1'显示状态栏With Form1.StatusBar1.Panels.Item(1).Text = "串口状态:" & "COM" & mPort & " Set=" & Form1.MSComm1.Settings & " " & Form1.MSComm1.PortOpenEnd WithEnd SubPrivate Sub mnuclear_Click()cleartestnoteEnd SubPrivate Sub mnuclrdistxt_Click()Form1.Text1.Text = ""End SubPrivate Sub mnucommopen_Click()MSComm1.PortOpen = Not MSComm1.PortOpenmnucommopen.Checked = MSComm1.PortOpenWith Form1.StatusBar1.Panels.Item(1).Text = "串口状态:" & "COM" & mPort & " Set=" & Form1.MSComm1.Settings & " " & Form1.MSComm1.PortOpenEnd WithEnd SubPrivate Sub mnucommseting_Click()frmProperties.Show vbModalEnd SubPrivate Sub mnuexit_Click()Unload MeEnd SubPrivate Sub mnuopen_Click()opentestnoteEnd SubPrivate Sub mnusave_Click()savetestnoteEnd SubPrivate Sub MSComm1_OnComm()Dim buffer() As ByteDim Bufferlength As IntegerSelect Case mEvent' Handle each event or error by placing' code below each case statement' 错误Case comEventBreak ' 收到Break。
串行口通信开启和关闭紧急处理功能程序设计代码
串行口通信开启和关闭紧急处理功能程序设计代码串行口通信开启和关闭紧急处理功能程序设计代码一、介绍串行口通信是计算机与外部设备进行数据交互的一种常见方式。
在某些情况下,可能会遇到紧急处理的需求,例如在发生故障或异常情况时需要立即停止通信。
本文将详细介绍如何设计一个程序,在串行口通信中实现开启和关闭紧急处理功能。
二、程序设计思路为了实现串行口通信开启和关闭紧急处理功能,我们需要使用一个编程语言来编写程序。
在这里,我们选择使用Python语言进行示例演示。
下面是程序设计的主要思路:1. 导入所需的库和模块:我们需要导入Python的serial模块来实现串行口通信功能。
2. 设置串行口参数:在开始通信之前,我们需要设置好串行口的参数,包括波特率、数据位、停止位等。
3. 打开串行口:通过调用serial模块中的open()函数来打开指定的串行口。
4. 开启紧急处理功能:通过向外部设备发送特定指令来开启紧急处理功能。
5. 进行数据交互:使用read()和write()函数进行数据的读取和写入操作。
6. 关闭紧急处理功能:通过向外部设备发送特定指令来关闭紧急处理功能。
7. 关闭串行口:通信结束后,通过调用serial模块中的close()函数来关闭串行口。
三、程序设计代码下面是一个简单的示例代码,演示了如何实现串行口通信开启和关闭紧急处理功能:```pythonimport serial# 设置串行口参数port = 'COM1' # 串行口号baudrate = 9600 # 波特率bytesize = serial.EIGHTBITS # 数据位parity = serial.PARITY_NONE # 校验位stopbits = serial.STOPBITS_ONE # 停止位# 打开串行口ser = serial.Serial(port, baudrate, bytesize, parity, stopbits)# 开启紧急处理功能ser.write(b'Emergency:ON')# 进行数据交互data = ser.read(10) # 读取10个字节的数据ser.write(b'Send data')# 关闭紧急处理功能ser.write(b'Emergency:OFF')# 关闭串行口ser.close()```四、代码解释和注意事项1. 在代码中,我们首先导入了serial模块,并设置了需要的串行口参数。
51单片机与串口通信代码
51单片机与串口通信代码在当今科技发展迅速的时代,嵌入式系统的应用越来越广泛。
而51单片机是一类常见的嵌入式控制器,它具有体积小巧、功耗低、价格便宜等特点,因此被广泛应用于各个领域。
而串口通信是实现单片机与计算机之间数据传输的常见方式,本文将介绍51单片机与串口通信的相关代码。
1. 串口通信概述串口通信是指通过串行接口,将数据一位一位地传输。
单片机通过串口与计算机或其他设备之间进行数据传输,实现信息的收发和控制指令的执行。
串口通信常用的协议包括RS232、RS485和UART等。
在51单片机中,一般选用UART协议。
2. 串口通信的硬件连接在使用51单片机与计算机进行串口通信时,需要进行相应的硬件连接。
首先,需要将单片机的串口引脚(一般是P3口)与计算机的串口(COM口)进行连接。
单片机的TXD引脚连接到计算机的RXD引脚,而单片机的RXD引脚连接到计算机的TXD引脚。
此外,还需要相连的地线进行电位的匹配。
3. 串口通信的软件设置在使用51单片机进行串口通信时,需要对单片机的串口进行相应的软件设置。
首先,需要设置波特率,波特率指每秒传送的位数,常见的波特率有9600、115200等。
通过设置相同的波特率,实现单片机与计算机之间的数据传输。
其次,还需要设置数据位、停止位和校验位等参数,以确保数据的正确传输。
4. 单片机发送数据的代码示例下面是一个简单的51单片机发送数据的代码示例:```c#include <reg51.h>void main() {TMOD = 0x20; // 配置定时器1为工作方式2TH1 = 0xFD; // 设置波特率为9600SCON = 0x50; // 允许串口工作TR1 = 1; // 启动定时器1while (1) {SBUF = 'A'; // 发送数据while (!TI); // 等待数据发送完毕TI = 0; // 清除发送标志位}}```5. 单片机接收数据的代码示例下面是一个简单的51单片机接收数据的代码示例:```c#include <reg51.h>void main() {TMOD = 0x20; // 配置定时器1为工作方式2TH1 = 0xFD; // 设置波特率为9600SCON = 0x50; // 允许串口工作TR1 = 1; // 启动定时器1while (1) {if (RI) { // 判断是否有数据接收P1 = SBUF; // 将接收到的数据存入P1口RI = 0; // 清除接收标志位}}}```6. 总结本文介绍了51单片机与串口通信代码的相关内容。
串口通信—串口发送和接收代码讲解
串⼝通信—串⼝发送和接收代码讲解 USART 初始化结构体详解 标准库函数对每个外设都建⽴了⼀个初始化结构体,⽐如USART_InitTypeDef,结构体成员⽤于设置外设⼯作参数,并由外设初始化配置函数,⽐如USART_Init()调⽤,这些设定参数将会设置外设相应的寄存器,达到配置外设⼯作环境的⽬的。
初始化结构体和初始化库函数配合使⽤是标准库精髓所在,理解了初始化结构体每个成员意义基本上就可以对该外设运⽤⾃如了。
初始化结构体定义在stm32f10x_usart.h ⽂件中,初始化库函数定义在stm32f10x_usart.c ⽂件中,编程时我们可以结合这两个⽂件内注释使⽤。
USART_BaudRate:波特率设置。
⼀般设置为2400、9600、19200、115200。
标准库函数会根据设定值计算得到USARTDIV 值,从⽽设置USART_BRR 寄存器值。
USART_WordLength:数据帧字长,可选8 位或9 位。
它设定USART_CR1 寄存器的M 位的值。
如果没有使能奇偶校验控制,⼀般使⽤8 数据位;如果使能了奇偶校验则⼀般设置为9 数据位。
USART_StopBits:停⽌位设置,可选0.5 个、1 个、1.5 个和2 个停⽌位,它设定USART_CR2 寄存器的STOP[1:0]位的值,⼀般我们选择1 个停⽌位。
USART_Parity :奇偶校验控制选择,可选USART_Parity_No( ⽆校验) 、USART_Parity_Even( 偶校验) 以及USART_Parity_Odd( 奇校验) ,它设定USART_CR1 寄存器的PCE 位和PS 位的值。
USART_Mode:USART 模式选择,有USART_Mode_Rx 和USART_Mode_Tx,允许使⽤逻辑或运算选择两个,它设定USART_CR1 寄存器的RE 位和TE 位。
USART_HardwareFlowControl:硬件流控制选择,只有在硬件流控制模式才有效,可选有⑴使能RTS、⑵使能CTS、⑶同时使能RTS 和CTS、⑷不使能硬件流。
串口通信源代码
//
#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语言串口通信-源代码
#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++; //记录接收了多少个数据。
python串口通信语法
python串口通信语法Python串口通信语法1. 引言在很多应用中,串口通信是一种常见的通信方式。
Python提供了丰富的库和模块来实现串口通信功能。
本文将介绍Python中串口通信的基本语法和常用操作。
2. 引入串口库在使用Python进行串口通信之前,首先需要引入相应的串口库。
在Python中,常用的串口库有pySerial、serial等。
可以通过pip命令安装这些库。
3. 打开串口使用Python进行串口通信时,首先需要打开串口。
可以通过以下代码来打开串口:```import serialser = serial.Serial('COM1', 9600)```上述代码中,'COM1'表示串口的名称,9600表示波特率。
4. 读取数据打开串口后,可以使用read()函数来读取串口数据。
以下代码演示了如何读取串口数据:```data = ser.read(10)print(data)```上述代码中,read(10)表示从串口读取10个字节的数据,并将数据存储在变量data中。
5. 写入数据除了读取数据,还可以使用write()函数向串口写入数据。
以下代码演示了如何向串口写入数据:```ser.write(b'Hello World')```上述代码中,b'Hello World'表示要写入的数据。
需要注意的是,写入的数据必须是字节类型。
6. 设置串口参数在打开串口之前,可以通过设置串口参数来满足通信需求。
常用的串口参数包括波特率、数据位、停止位和校验位等。
以下代码演示了如何设置串口参数:```ser = serial.Serial('COM1', 9600, bytesize=8, parity='N',stopbits=1)```上述代码中,bytesize表示数据位,parity表示校验位,stopbits表示停止位。
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++; //记录接收了多少个数据。
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语言代码编写技巧,为实际应用提供有力支持。