菜鸟学习笔记-----linux下的串口操作 嘿嘿

网上找的一个demo,编译后,没有问题,但将机器的串口的2 和 3 短接后,没有回显
正常的情况,应该是发什么回显什么,本程序发送的是 40 02 02 BC。

/*
** File: rs232.c
**
** Description:
**      Provides an RS-232 interface that is very similar to the CVI provided
**      interface library
*/
#include <stdio.h>
#include <assert.h>
//#include "rs232.h"
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>

#ifndef _RS232_H_
#define _RS232_H_

/* the maximum number of ports we are willing to open */
#define MAX_PORTS 4

/*this array hold information about each port we have opened */
struct PortInfo{
    int busy;
    char name[32];
    int handle;
};

int OpenCom(int portNo,const char deviceName[],long baudRate);
int CloseCom(int portNo);
int ComRd(int portNo,char buf[],int maxCnt,int Timeout);
int ComWrt(int portNo,const char * buf,int maxCnt);


#endif
//#define DEBUG

struct PortInfo ports[MAX_PORTS];

/*
** Function: OpenCom
**
** Description:
**    Opens a serial port with default parameters
**
** Arguments:
**    portNo - handle used for further access
**    deviceName - the name of the device to open
**
** Returns:
**    -1 on failure
*/
int OpenCom(int portNo, const char deviceName[],long baudRate)
{
    return OpenComConfig(portNo, deviceName, baudRate, 1, 8, 1, 0, 0);
}

/*

*/
long GetBaudRate(long baudRate)
{
    long BaudR;
    switch(baudRate)
    {
    case 115200:
        BaudR=B115200;
        break;
    case 57600:
        BaudR=B57600;
        break;
    case 19200:
        BaudR=B19200;
        break;
    case 9600:
        BaudR=B9600;
        break;
    default:
        BaudR=B0;
    }
    return BaudR;
}

/*
** Function: OpenComConfig
**
** Description:
**    Opens a serial port with the specified parameters
**
** Arguments:
**    portNo - handle used for further access
**    deviceName - the name of the device to open
**    baudRate - rate to open (57600 for example)
**    parity - 0 for no parity
**    dataBits - 7 or 8
**    stopBits - 1 or 2
**    iqSize - ignored
**    oqSize - ignored
**
** Returns:
**    -1 on failure
**
** Limitations:
**    parity, stopBits, iqSize, and oqSize are ignored
*/
int OpenComConfig(int port,
                  const char deviceName[],
                  long baudRate,
                  int parity,
                  int dataBits,
                  int stopBits,
                  int iqSize,
                  int oqSize)
{
    struct termios newtio;
    long BaudR;

    ports[port].busy = 1;
    strcpy(ports[port].name,deviceName);
    if ((ports[port].handle = open(deviceName, O_RDWR, 0666)) == -1)
    {
        perror("open");
       // assert(0);
    }

    /* set the port to raw I/O */
    newtio.c_cflag = CS8 | CLOCAL | CREAD ;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
    newtio.c_lflag = 0;
    newtio.c_cc[VINTR]    = 0;
    newtio.c_cc[VQUIT]    = 0;
    newtio.c_cc[VERASE]   = 0;
    newtio.c_cc[VKILL]    = 0;
    newtio.c_cc[VEOF]     = 4;
    newtio.c_cc[VTIME]    = 0;
    newtio.c_cc[VMIN]     = 1;
    newtio.c_cc[VSWTC]    = 0;
    newtio.c_cc[VSTART]   = 0;
    newtio.c_cc[VSTOP]    = 0;
    newtio.c_cc[VSUSP]    = 0;
    newtio.c_cc[VEOL]     = 0;
    newtio.c_cc[VREPRINT] = 0;
    newtio.c_cc[VDISCARD] = 0;
    newtio.c_cc[VWERASE]  = 0;
    newtio.c_cc[VLNEXT]   = 0;
    newtio.c_cc[VEOL2]    = 0;
    cfsetospeed(&newtio, GetBaudRate(baudRate));
    cfsetispeed(&newtio, GetBaudRate(baudRate));
    tcsetattr(ports[port].handle, TCSANOW, &newtio);
    return 0;
}

/*
** Function: CloseCom
**
** Description:
**    Closes a previously opened port
**
** Arguments:
**    The port handle to close
**
**    Returns:
**    -1 on failure
*/
int CloseCom(int portNo)
{
    if (ports[portNo].busy)
    {
        close(ports[portNo].handle);
        ports[portNo].busy = 0;
        return 0;
    }
    else
    {
        return -1;
    }
}

/*
** Function: ComRd
**
** Description:
**    Reads the specified number of bytes from the port.
**    Returns when these bytes have been read, or timeout occurs.
**
** Arguments:
**    portNo - the handle
**    buf - where to store the data
**    maxCnt - the maximum number of bytes to read
**
** Returns:
**    The actual number of bytes read
*/
int ComRd(int portNo, char buf[], int maxCnt,int Timeout)
{
    int actualRead = 0;
    fd_set rfds;
    struct timeval tv;
    int retval;

    if (!ports[portNo].busy)
    {
        assert(0);
    }

    /* camp on the port until data appears or 5 seconds have passed */
    FD_ZERO(&rfds);
    FD_SET(ports[portNo].handle, &rfds);
    tv.tv_sec = Timeout/1000;
    tv.tv_usec = (Timeout%1000)*1000;
    retval = select(16, &rfds, NULL, NULL, &tv);

    if (retval)
    {
        actualRead = read(ports[portNo].handle, buf, maxCnt);
    }
    
#ifdef DEBUG
    if(actualRead>0)
    {
        unsigned int i;
        for (i = 0; i < actualRead; ++i)
        {
            if ((buf[i] > 0x20) && (buf[i] < 0x7f))
            {
                printf("<'%c'", buf[i]);
            }
            else
            {
                printf("<%02X", buf[i]);
            }
        }
    printf("/n");
    }
    fflush(stdout);
#endif /* DEBUG */

    return actualRead;
}

/*
** Function: ComWrt
**
** Description:
**    Writes out the specified bytes to the port
**
** Arguments:
**    portNo - the handle of the port
**    buf - the bytes to write
**    maxCnt - how many to write
**
** Returns:
**    The actual number of bytes written
*/
int ComWrt(int portNo, const char *buf, int maxCnt)
{
    int written;

    if (!ports[portNo].busy)
    {
        assert(0);
    }
#ifdef DEBUG
    {
        int i;
        for (i = 0; i < maxCnt; ++i)
        {
            if ((buf[i] > 0x20) && (buf[i] < 0x7f))
            {
                printf(">'%c'", buf[i]);
            }
            else
            {
                printf(">%02X", buf[i]);
            }
        }
    printf("/n");
    }
    fflush(stdout);
#endif /* DEBUG */
    
    written = write(ports[portNo].handle, buf, maxCnt);
    return written;
}





main(int argc, char *argv[])
{
    int ret,portno,nWritten,nRead,i;
    char buf[256];
    char wbuf[256];
    wbuf[0]=0x40;
    wbuf[1]=0x02;
    wbuf[2]=0x02;
    wbuf[3]=0xbc;
   
    portno=0;
   
    //open ttys1
    ret=OpenCom(portno,"/dev/ttyS0",115200);
        if(ret==-1)
        {
            perror("The /dev/ttyS1 open error.");
            exit(1);
        }
    printf("com aleadyv.../n");   
    nRead=ComWrt(portno,wbuf,4);
    printf("com sending.../n");   
    //loop for read       
    while(1)
    {
        printf("com readinging.../n");
        nRead=ComRd(portno,buf,4,1000);
        printf("com read over .../n");
       
        printf("value is %d/n",nRead);
        if(nRead>0)
        {
            for(i=0;i<nRead;i++)
                printf("%d/n",buf[i]);
        }
    }
   
    //close ttys1   
    if((ret=CloseCom(portno)==-1))
        {
            perror("Close com");
            exit(1);
        }
    printf("/n/n");
    printf("Exit now./n");
    return(1);
}

上面的程序,其实没有问题,问题出在VM上,尝试了几个demo程序后,发现和预期的结果都相去甚远,无奈发帖到论坛询
问,多数的人回答都是 打开选项设置有问题,我尝试着按他们的建议修改,发现问题依旧…
无奈,暂停了 嘿嘿, 去玩u-boot移植,乖乖的,问题更多了… 甚至都不想再碰linux,反正工作中也不涉及linux嘛,但总
是不甘心呀…  功夫不付有心人呀,u-boot顺利编译通过,问题是出在,自己对linux的不熟悉,最搞笑的是,居然在NTFS文
件格式上编译u-boot,后来经 小苦 朋友的提醒,哈哈 解决了… 当然后来还遇到了一些问题,具体的解决办法,都在另篇
笔记里,都作了详细的说明…
u-boot 顺利通过后,就继续串口的程序,玩了两周的linux,似乎变聪明了,关键是前面的教训深刻呀,就想到了是不是VM
里需要设置下呢?要不串口用不起来呢?上午在图书馆里一查,果真如此也!
回来后,按文档设置,步骤如下:
在VM->Setting......->点击ADD,把串口加进来,
呵呵设置时尽量不要用自动检测,要选中串口,
同时要把串口设为启动时就连接拉,

前段时间写的程序未做任何修改,就有反映了,结果如下:

com aleadyv...
com sending...
com readinging...
com read over ...
value is 4
64
2
2
-68
至此,应该算是OK了 嘿嘿

其实也是自己玩的,就是想在linux下,通过串口控制我们的设备而已,周一到公司,连设备玩咯 嘿嘿
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值