⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 send.cpp

📁 LINUX下串口发送程序,初学者可以参考一下
💻 CPP
字号:
#include     <stdio.h>
#include     <stdlib.h> 
#include     <unistd.h>  
#include     <sys/types.h>
#include     <sys/stat.h>
#include     <fcntl.h> 
#include     <termios.h>
#include     <errno.h>   
int main(int argc, char **argv)
{
	int fd;
	int i,k;
	int nwrite,nread;   
	struct termios opt; 
    unsigned char read_buff[256];
	unsigned char write_buff[]={0x02,0x00,0x04,0x43,0x33,0x31,0x03,0x46,0x05};
    int len=9;

	fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);    //默认为阻塞读方式
	if(fd == -1)
		perror("open serial 0\n");
	
	tcgetattr(fd, &opt);      
	cfsetispeed(&opt, B57600);
	cfsetospeed(&opt, B57600);
    
	if(tcsetattr(fd, TCSANOW, &opt) != 0 )
	{     
		perror("tcsetattr error");
	    return -1;
	}
    
	opt.c_cflag &=~CSIZE;  
	opt.c_cflag |= CS8;   
	opt.c_cflag &=~CSTOPB; 
	opt.c_cflag &=~PARENB; 
	opt.c_cflag &=~INPCK;
	opt.c_cflag |= (CLOCAL | CREAD);
	
	opt.c_lflag &=~(ICANON | ECHO | ECHOE | ISIG);
	
	opt.c_oflag &=~OPOST;
	
	opt.c_iflag &=~ICRNL;
	opt.c_iflag &=~INLCR;
    
	opt.c_cc[VTIME] = 0;
	opt.c_cc[VMIN] = 0;
    
	tcflush(fd, TCIOFLUSH);
	
	printf("configure complete\n");
    
	if(tcsetattr(fd, TCSANOW, &opt) != 0)
	{
		perror("serial error");
		return -1;
	}
	printf("start send and receive data\n");
	
	
	for(i=0;i<len;i++)
	{   
		nwrite = write(fd,&write_buff[i],1);
		
		if(nwrite!=1)
		{
			printf("Send error!\n");
			break;
		}
		else 
		{
			printf("0x%x ",write_buff[i]);
		}
		//for(k=0;k<0xfffff;k++);
	}
	printf("\n");

	while(1)
	{
		while((nread = read(fd,read_buff,256))>0)
		{
			printf("\n Len %d\n",nread);
			read_buff[nread+1]='\0';
			printf("\n%s",read_buff);
		}
	}

	close(fd);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -