- 论坛徽章:
- 0
|
本帖最后由 ruchong001 于 2010-05-04 08:27 编辑
linux下一个串口写数据的问题
大家好,我在linux下编写这样一个程序,想通过ttyUBS0向另一个pc的串口发送数据,pc上用超级终端接受数据,设置为8,n,1,数据流控制为无,波特率设置为9600,但是不知道为什么运行了程序以后,在pc的超级终端
根本显示不到接收了数据。我认为是程序对ttyUSB0设置出了问题,但是不知道出在哪里,希望各位高手帮忙看下,程序代码很简单。
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#define max_buffer_size 100 /*定义缓冲区最大宽度*/
/*******************************************/
int fd; /*定义设备文件描述符*/
int flag_close;
int open_serial(int k)
{
if(k==0) /*串口选择*/
{
fd = open("/dev/ttyUSB0",O_RDWR|O_NOCTTY); /*读写方式打开串口*/
perror("open /dev/ttyUSB0");
}
else
{
fd = open("/dev/ttyS1",O_RDWR|O_NOCTTY);
perror("open /dev/ttyS1");
}
if(fd == -1) /*打开失败*/
return -1;
else
return 0;
}
/********************************************************************/
int main(int argc, char *argv[ ] )
{
char sbuf[]={"Hello,this is a Serial_Port test!"};
int sfd,retv,i;
struct termios options;
int length=sizeof(sbuf);/*发送缓冲区数据宽度*/
/*******************************************************************/
open_serial(0); /*打开串口1*/
/*******************************************************************/
printf("ready for sending data...\n"); /*准备开始发送数据*/
bzero(&options,sizeof(options));
tcgetattr(fd,&options);
//cfmakeraw(&options);
/*****************************************************************/
options.c_cflag|=CLOCAL|CREAD;
options.c_cflag &= ~CSIZE;
cfsetispeed(&options,B9600); /*波特率设置为9600bps*/
cfsetospeed(&options,B9600);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag |= CS8;
options.c_cc[VMIN]=0;
options.c_cc[VTIME]=0;
/*******************************************************************/
tcflush(fd,TCIFLUSH);
tcsetattr(fd,TCSANOW,&options);
retv=write(fd,sbuf,length); /*接收数据*/
if(retv==-1)
{
perror("write");
}
printf("the number of char sent is %d\n",retv);
flag_close =close(fd);
if(flag_close==-1) /*判断是否成功关闭文件*/
printf("Close the Device failur!\n");
return 0;
} |
|