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#串口调试助手

//serialPort1.Parity = (Parity)Enum.Parse(typeof(Parityset), comboBox4.SelectedItem.ToString());
} public enum Parityset {
None, odd, Even, Mark, Space } private void comboBox5_SelectedIndexChanged(object sender, EventArgs e) //停止位 { serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), boBox5.Text); }
serialPort1.BaudRate = int.Parse(comboBox2.Text); serialPort1.DataBits = int.Parse(comboBox3.Text); serialPort1.Parity = (Parity)Enum.Parse(typeof(Parityset),
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) {
textBox3.Text = serialPort.ReadExisting();
label10.Text = (int.Parse(label10.Text.Trim()) + 1).ToString(); //统计接收区 数据 组数

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

三菱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; }。

51单片机的串口通信程序(C语言)

51单片机的串口通信程序(C语言)

#include <reg52.h>#include<intrins.h>#include <stdio.h>#include <math.h>#define uchar unsigned char#define uint unsigned intsbit Key1 = P2^3;sbit Key2 = P2^2;sbit Key3 = P2^1;sbit Key4 = P2^0;sbit BELL = P3^6;sbit CONNECT = P3^7;unsigned int Key1_flag = 0;unsigned int Key2_flag = 0;unsigned int Key3_flag = 0;unsigned int Key4_flag = 0;unsigned char b;unsigned char code Num[21]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00, 0x10,0x89};unsigned char code Disdigit[4] = {0x7F,0xBF,0xDF,0xEF};unsigned char Disbuf[4];void delayms(uint t){uint i;while(t--){/* 对于11.0592M时钟,约延时1ms */for (i=0;i<125;i++){}}}//-----------------------------------------------------void SendData(uchar Dat){uchar i=0;SBUF = Dat;while (1){if(TI){TI=0;break;}}}void ScanKey(){if(Key1 == 0){delayms(100); if(Key1 == 0){Key1_flag = 1; Key2_flag = 0; Key3_flag = 0;Key4_flag = 0;Key1 = 1;}else;}if(Key2 == 0){delayms(100);if(Key2 == 0){Key2_flag = 1; Key1_flag = 0; Key3_flag = 0;Key4_flag = 0;Key2 = 1;}else;}if(Key3 == 0){delayms(50);if(Key3 == 0){Key3_flag = 1; Key1_flag = 0; Key2_flag = 0;Key4_flag = 0;Key3 = 1;}else;}if(Key4 == 0){delayms(50);if(Key4 == 0){Key4_flag = 1;Key1_flag = 0;Key2_flag = 0;Key3_flag = 0;Key4 = 1;}else;}else;}void KeyProc(){if(Key1_flag){TR1 = 1;SendData(0x55);Key1_flag = 0; }else if(Key2_flag){TR1 = 1;SendData(0x11); Key2_flag = 0;}else if(Key3_flag) {P1=0xff;BELL = 0;CONNECT = 1;Key3_flag = 0;}else if(Key4_flag){CONNECT = 0;BELL = 1;Key4_flag = 0;}else;}void Initdisplay(void){Disbuf[0] = 1;Disbuf[1] = 2;Disbuf[2] = 3;Disbuf[3] = 4;}void Display() //显示{unsigned int i = 0;unsigned int temp,count;temp = Disdigit[count]; P2 =temp;temp = Disbuf[count];temp = Num[temp];P0 =temp;count++;if (count==4)count=0;}void time0() interrupt 1 using 2 {Display();TH0 = (65535 - 2000)/256;TL0 = (65535 - 2000)%256;}void main(){Initdisplay();TMOD = 0x21;TH0 = (65535 - 2000)/256;TL0 = (65535 - 2000)%256;TR0 = 1;ET0 = 1;TH1 = 0xFD; //11.0592MTL1 = 0xFD;PCON&=0x80;TR1 = 1;ET1 = 1;SCON = 0x40; //串口方式REN = 1;PT1 = 0;PT0 = 1;EA = 1;while(1){ScanKey();KeyProc();if(RI){Disbuf[0] = 0;Disbuf[1] = 20;Disbuf[2] = SBUF>>4;Disbuf[3] = SBUF&0x0f;RI = 0;}else;}}51单片机串口通信C语言程序2**************************************************************; 平凡单片机工作室;ckss.asm;功能:反复向主机送AA和55两个数;主机使用一个串口调试软件设置19200,n,8,1***************************************************************/#include "reg51.h"#define uchar unsigned char#define uint unsigned int//延时程序//////////////////由Delay参数确定延迟时间*/void mDelay(unsigned int Delay){ unsigned int i;for(;Delay>0;Delay--){ for(i=0;i<124;i++){;}}}//////////////////// 主程序////////////////////void main(){ uchar OutDat; //定义输出变量TMOD=0x20; //TMOD=0TH1=0xf3; //12MHZ ,BPS:4800,N,8,1TL1=0xf3;PCON=0x80; //方式一TR1=1; //?????????????????????????????SCON=0x40; //串口通信控制寄存器模式一OutDat=0xaa; //向串口发送固定数据值for(;;) //循环程序{SBUF=OutDat;//发送数据for(;;){ if(TI) //发送中断位当发送停止位时置1,表示发送完成break;}mDelay(500);TI=0; //清零中断位OutDat=~OutDat; //显示内容按位取反}}。

VC(MFC)编写串口调试助手

VC(MFC)编写串口调试助手

VC(MFC)编写串口调试助手1.序确定基本功能:1.自动寻找串口,并自动添加到下拉框中共选择;2.有波特率、数据位、停止位、校验位的选择设置;3.串口打开控制按钮;4.发送、清除按钮;5.接收是自动实现的;6.有定时自动发送功能;7.有传送文件功能;8.有状态栏显示,指示串口状态,设置参数和发送接收显示。

下面就一步步实现,本人纯业余,只是记录下来这个学习过程,请勿拍砖。

开发平台Visual C++6.0英文版,电脑是i7-2670Q四核8G内存1G独显的笔记本,装的win7 64位旗舰版,因此VC6兼容不是太好,有些小毛病,不过不影响编写。

2.创建MFC项目File -> New -> Projects选择MFC AppWizard(exe),项目名称commassist选择OK选中Dialog based,点击Next> 。

默认选项,点击Next> ,继续默认选项,点击Next> ,如果选中As a statically linked library,生产的EXE可直接在没装VC的机器上运行。

可以在项目中进行更改。

选择第二个CCommassistDlg,点击Finish点击OK。

项目创建完毕,进入项目。

删除界面上确定和取消按钮以及静态文字。

3.创建界面保存后便可以开始创建界面了。

参考界面仿照设计的界面,具体添加按钮或编辑框等的布局步骤就不用细说了。

4.图标修改在资源视图中选择Icon右键InsertIcon加入打开和关闭的Icon图标或自行绘制,如下图IDR_MAINFRAME原为MFC提供的图标,这里我直接改成自己的,生成EXE后将会显示这个图标。

下面将帮助页面图标也改为自绘图标。

在打开按钮旁边加入自绘的打开和关闭图标:先加入工具条中的Picture,然后选中右键看属性,并如图将Image选为默认的IDI_ICON_CLOSE。

如下图5.基本设置下面对各个按钮及编辑框设置进行描述右键串口对应的Combo Box,ID设置为IDC_COMLIST,Type设置为Drop List,Sort不选择(我系统是WIN7 64位,不选中反而自动排序,至于XP得试试看了,以下的选择相同)。

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

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

该程序全部由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);}。

相关文档
最新文档