主题 : mini2440与pc串口通信 复制链接 | 浏览器收藏 | 打印
级别: 新手上路
UID: 120848
精华: 0
发帖: 1
金钱: 5 两
威望: 1 点
贡献值: 0 点
综合积分: 2 分
注册时间: 2015-11-23
最后登录: 2015-11-24
楼主  发表于: 2015-11-23 21:09

 mini2440与pc串口通信

开发板上运行后就是没有反应,串口即使显示打开也并没有收到pc发送的数据啊,求大神们看看
#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 | ISTRIP);
        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/ttyS1", O_RDWR|O_NOCTTY|O_NDELAY);//此处ttys0,1,2以及ttySA0,1,2匀以测试过 都没有什么反应,但是用ttySA0,1,2的时候显示能正确打开串口,前面那三个就找不到文件了
    
    if (fd == -1)
    {
       perror("Can't Open Serial Port");
       return(-1);
    }
    else
       printf("open ttySAC2 .....\n");

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

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