Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 串口驅動測試:S3C2440 設備節點與 mdev 實務

一、終端(串口)概況

210 開發板有 4 個串口,2440 開發板有 3 個。在 2440 上,三個串口的名稱與主/次設備號對應如下:

串口名稱主設備號次設備號
s3c2410_serial020464
s3c2410_serial120465
s3c2410_serial220466

有些系統中則改用這三個名字:

名稱主設備號次設備號
ttySAC020464
ttySAC120465
ttySAC220466

二、建立 /dev 目錄

方法一:靜態建立設備節點

從開機流程可知,系統啟動最少需要這些節點:/dev/mtdblock*(MTD 塊設備)、/dev/ttySAC*(串口)、/dev/console、/dev/null。

cd /dev
mknod console c 5 1
mknod null    c 1 3
mknod ttySAC0 c 204 64

方法二:用 mdev 動態建立

# 使用内核文件系统,减少对 flash 的读写
mount -t tmpfs mdev /dev

mkdir /dev/pts                    # 支持 telnet 等外部网络链接的虚拟终端
mount -t devpts devpts /dev/pts

mount -t sysfs sysfs /sys         # mdev 透过 sysfs 取得设备资讯
echo /bin/mdev > /proc/sys/kernel/hotplug   # 有设备插拔时呼叫 mdev
mdev -s                           # 依内核资讯生成所有设备节点

若要在開機時自動執行 mdev,需要改兩個檔案:etc/fstab 自動掛載檔案系統,以及 etc/init.d/rcS 加入執行命令。

etc/fstab:

# device   mount-point  type   option    dump  fsck order
proc       /proc        proc   defaults  0     0
tmpfs      /tmp         tmpfs  defaults  0     0    # 提高速度,减少磨损
sysfs      /sys         sysfs  defaults  0     0    # 让 mdev 知道有哪些设备
tmpfs      /dev         tmpfs  defaults  0     0    # 减少热插拔时的 flash 磨损

要注意:mdev 產生的 /dev 目錄中,S3C2410 的串口名是 s3c2410_serial0,因此必須修改 etc/inittab:

# 修改前
ttySAC0::askfirst:~/bin/sh

# 修改後
s3c2410_serial0::askfirst:~/bin/sh

三、用 mdev.conf 自訂節點名稱

檔案系統中若存在 /etc/mdev.conf,mdev 會讀取它作為設定。透過這個檔案,你可以自訂設備節點的名稱或建立別名連結。以下為 root qtopia 中的內容:

# console devices
tty[0-9]*   0:5  0660
vc/[0-9]*   0:5  0660

# serial port devices
s3c2410_serial0   0:5  0666  =ttySAC0
s3c2410_serial1   0:5  0666  =ttySAC1
s3c2410_serial2   0:5  0666  =ttySAC2
s3c2410_serial3   0:5  0666  =ttySAC3

# loop devices
loop[0-9]*   0:0  0660  =loop/

# i2c devices
i2c-0   0:0  0666  =i2c/0
i2c-1   0:0  0666  =i2c/1

可見串口驅動註冊的設備名是 s3c2410_serial0/1/2,而 mdev 會依這份設定在 /dev 下另外產生 ttySAC0/1/2,以符合應用程式對串口名稱的習慣。這也是為什麼同一塊板子在不同系統裡,串口名字會不一樣。

四、由開機參數選擇 console

核心採用哪個串口當 console,由 bootloader 傳入的參數決定:

init=/linuxrc console=ttySAC1,115200
noinitrd root=/dev/mtdblock2 init=/linuxrc console=ttySAC0,115200
noinitrd root=/dev/mtdblock2 init=/linuxrc console=s3c2410_serial0,115200

五、測試程式

程式一:設定串口參數並週期性寫入資料

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <sys/time.h>
#include <signal.h>
#include <string.h>
#include <fcntl.h>
#include <asm/param.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_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[VTIME] = 0;
    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 open_port(int fd, int comport)
{
    if (comport == 1)
    {
        fd = open("/dev/s3c2410_serial0", O_RDWR | O_NOCTTY | O_NDELAY);
        if (-1 == fd) { perror("Can't Open s3c2410_serial0"); return -1; }
        printf("open s3c2410_serial0 .....\n");
    }
    else if (comport == 2)
    {
        fd = open("/dev/s3c2410_serial1", O_RDWR | O_NOCTTY | O_NDELAY);
        if (-1 == fd) { perror("Can't Open s3c2410_serial1"); return -1; }
        printf("open s3c2410_serial1 .....\n");
    }
    else if (comport == 3)
    {
        fd = open("/dev/s3c2410_serial2", O_RDWR | O_NOCTTY | O_NDELAY);
        if (-1 == fd) { perror("Can't Open s3c2410_serial2"); return -1; }
        printf("open s3c2410_serial2 .....\n");
    }
    else if (comport == 4)
    {
        fd = open("/dev/s3c2410_serial3", O_RDWR | O_NOCTTY | O_NDELAY);
        if (-1 == fd) { perror("Can't Open s3c2410_serial3"); return -1; }
        printf("open s3c2410_serial3 .....\n");
    }

    // 恢复为阻塞模式,用于等待串口数据
    if (fcntl(fd, F_SETFL, 0) < 0)
        printf("fcntl failed!\n");
    else
        printf("fcntl=%d\n", fcntl(fd, F_SETFL, 0));

    // 确认打开的是终端设备
    if (isatty(STDIN_FILENO) == 0)
        printf("standard input is not a terminal device\n");
    else
        printf("isatty success!\n");

    printf("fd-open=%d\n", fd);
    return fd;
}

int main(int argc, char **argv)
{
    int fd, i;
    unsigned char buff[512];

    bzero(buff, 512);

    if ((fd = open_port(fd, 4)) < 0)
    {
        printf("open_port error\n");
        return -1;
    }
    if ((i = set_opt(fd, 115200, 8, 'N', 1)) < 0)
    {
        printf("set_opt error\n");
        return -1;
    }
    printf("fd=%d\n", fd);

    strcpy((char *)buff, "HelloWorld");

    while (1)
    {
        write(fd, buff, sizeof(buff));
        sleep(1);
    }

    close(fd);
    return 0;
}

程式二:完整的收發範例(含 select 超時接收)

#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>

#define DEVICE "/dev/s3c2410_serial3"

int serial_fd = 0;

int init_serial(void)
{
    serial_fd = open(DEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
    if (serial_fd < 0)
    {
        perror("open");
        return -1;
    }

    struct termios options;

    // 1. 取得目前终端参数
    tcgetattr(serial_fd, &options);

    // 2. 修改参数
    options.c_cflag |= (CLOCAL | CREAD);   // 本地连接、接收使能
    options.c_cflag &= ~CSIZE;             // 设置数据位前必须先屏蔽这一位
    options.c_cflag &= ~CRTSCTS;           // 无硬件流控
    options.c_cflag |= CS8;                // 8 位数据位
    options.c_cflag &= ~CSTOPB;            // 1 位停止位
    options.c_iflag |= IGNPAR;             // 无奇偶校验
    options.c_oflag = 0;
    options.c_lflag = 0;                   // 不激活终端模式
    cfsetospeed(&options, B115200);

    // 3. 生效:TCSANOW 表示所有改变立即生效
    tcflush(serial_fd, TCIFLUSH);
    tcsetattr(serial_fd, TCSANOW, &options);

    return 0;
}

/**
 * 串口发送数据
 * @fd: 串口描述符  @data: 待发送数据  @datalen: 数据长度
 */
int uart_send(int fd, char *data, int datalen)
{
    int len = write(fd, data, datalen);
    if (len == datalen)
    {
        return len;
    }
    else
    {
        tcflush(fd, TCOFLUSH);   // 刷新写入但未传送的数据
        return -1;
    }
}

/**
 * 串口接收数据,启动后在 PC 端发送 ascii 文件
 */
int uart_recv(int fd, char *data, int datalen)
{
    int len = 0, ret = 0;
    fd_set fs_read;
    struct timeval tv_timeout;

    FD_ZERO(&fs_read);
    FD_SET(fd, &fs_read);

    tv_timeout.tv_sec  = (10 * 20 / 115200 + 2);
    tv_timeout.tv_usec = 0;

    ret = select(fd + 1, &fs_read, NULL, NULL, &tv_timeout);
    printf("ret = %d\n", ret);
    // 返回 0 表示超时,-1 表示错误

    if (FD_ISSET(fd, &fs_read))
    {
        len = read(fd, data, datalen);
        printf("len = %d\n", len);
        return len;
    }
    else
    {
        perror("select");
        return -1;
    }
}

int main(int argc, char **argv)
{
    init_serial();

    char buf[] = "hello world";
    char buf1[10] = {0};

    uart_send(serial_fd, buf, 10);
    printf("\n");

    uart_recv(serial_fd, buf1, 10);
    printf("uart receive %s\n", buf1);

    close(serial_fd);
    return 0;
}

測試時記得:接收端(PC)要設定相同的波特率、資料位、停止位與檢核方式,否則只會收到一堆亂碼;uart_recv 中的 buf1 若不預先清零,印出來的字串可能多出無意義的尾巴。

Copyright © Linux教程網 All Rights Reserved