LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1426|回复: 1

51单片机和虚拟机下linux串口通信的问题

[复制链接]
发表于 2008-5-8 18:22:32 | 显示全部楼层 |阅读模式
51单片机发数据,虚拟机下的linux串口收数据.程序如下:
#include  <stdio.h>
#include  <string.h>
#include  <sys/types.h>
#include  <errno.h>
#include  <sys/stat.h>
#include  <fcntl.h>
#include  <unistd.h>
#include  <termios.h>
#include  <stdlib.h>

int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop)
{
    struct termios newtio,oldtio;
    if ( tcgetattr( fd,&oldtio) != 0)            //保存测试现有串口参数设置
    {  
        perror("SetupSerial 1");
        return -1;
    }
    bzero( &newtio, sizeof( newtio ) );
    newtio.c_cflag  ¦= CLOCAL  ¦ CREAD;      //初使化串口
    newtio.c_cflag &= ~CSIZE;  //无数据位

    switch( nBits ) //设置数据位
    {
    case 7:
        newtio.c_cflag  ¦= CS7;
        break;
    case 8:
        newtio.c_cflag  ¦= CS8;
        break;
    }
    switch( nEvent )    //设置奇偶校验位
    {
    case 'O': //奇数
        newtio.c_cflag  ¦= PARENB;
        newtio.c_cflag  ¦= PARODD;
        newtio.c_iflag  ¦= (INPCK  ¦ ISTRIP);
        break;
    case 'E':  //偶数
        newtio.c_iflag  ¦= (INPCK  ¦ ISTRIP);
        newtio.c_cflag  ¦= PARENB;
        newtio.c_cflag &= ~PARODD;
        break;
    case 'N':  //无奇偶校验位
newtio.c_iflag &= INPCK;
        newtio.c_cflag &= ~PARENB;
        break;
    }
switch( nSpeed ) //设置波特率
    {
    case 2400:
        cfsetispeed(&newtio, B2400);
        cfsetospeed(&newtio, B2400);
        break;
    case 4800:
        cfsetispeed(&newtio, B4800);
        cfsetospeed(&newtio, B4800);
        break;
    case 9600:
        cfsetispeed(&newtio, B9600);
        cfsetospeed(&newtio, B9600);
        break;
    case 115200:
        cfsetispeed(&newtio, B115200);
        cfsetospeed(&newtio, B115200);
        break;
    default:
        cfsetispeed(&newtio, B9600);
        cfsetospeed(&newtio, B9600);
        break;
    }

    if( nStop == 1 ) //设置停止位
        newtio.c_cflag &= ~CSTOPB;
    else if ( nStop == 2 )
     newtio.c_cflag  ¦= CSTOPB;

    newtio.c_cc[VMIN] = 0; //最少读取的字符数
    tcflush(fd,TCIFLUSH); // 刷清未决输入和/或输出
    if((tcsetattr(fd,TCSANOW,&newtio))!=0)
    {
        perror("com set error");
        return -1;
    }
    printf("set done!\n");
    return 0;
}

int main(void)
{
    int fd;
    char buff[2];
    fd = open( "/dev/ttyS0", O_RDWR);
     
    if (fd == -1)
    {
       perror("Can't Open Serial Port");
       return(-1);
    }
    else  
       printf("open ttyS0 .....\n");

    fcntl(fd, F_SETFL, 0);     //恢复串口的状态为阻塞状态,用于等待串口数据的读入
    set_opt(fd,9600,8,'N',1);   //设置串口

   while(1)
{
    while((read(fd,buff,2))==0);
    printf("%d,%d\n",buff[0],buff[1]);
}
  close(fd);
    return;
}


为什么程序执行后,一个数据都收不到,是怎么回事啊
发表于 2008-5-9 12:07:58 | 显示全部楼层
先用minicom/cutecom程序调试, 确定是单片机有数据发出, 然后再查你的程序
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表