⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 uart_test1.c

📁 串口驱动源代码 基于linux 单片机是arm的 2410
💻 C
字号:
#include     <stdio.h>      /*标准输入输出定义*/
#include     <stdlib.h>     /*标准函数库定义*/
#include     <unistd.h>     /*Unix 标准函数定义*/
#include     <sys/types.h>  
#include     <sys/stat.h>   
#include     <fcntl.h>      /*文件控制定义*/
#include <termios.h> /*PPSIX 终端控制定义*/
#include     <errno.h>      /*错误号定义*/

#define BAUDRATE B115200
#define DEVICE "/dev/ttyS0"
#define _POSIX_SOURCE 1
#define FALSE 0
#define TRUE 1

int main(void) {
    int fd, res_w, res_r, i, j, k;
    struct termios oldtio,newtio;
    char inbuf[255];
    char cbuf[16]="hello";
      char buf[255];  

    res_w = 0;
    res_r = 0;
    
    fd = open(DEVICE, O_RDWR | O_NOCTTY ); // | O_NDELAY);
    if(fd < 0) {
        perror(DEVICE);
        exit(-1);
    }

    tcgetattr(fd, &oldtio);

bzero(&newtio,sizeof(struct termios));

newtio.c_cflag|= (CLOCAL | CREAD);
newtio.c_cflag|=BAUDRATE;
newtio.c_cflag&=~CSTOPB;
newtio.c_cflag&=~PARENB;
newtio.c_cflag&=~CSIZE;
newtio.c_cflag|=CS8;
newtio.c_cflag&=~CRTSCTS;

newtio.c_lflag=0;

newtio.c_oflag=0;

newtio.c_cc[VMIN]=10;
newtio.c_cc[VTIME]=0;

newtio.c_iflag&=~(IXON|IXOFF|IXANY); 

cfsetispeed(&newtio, BAUDRATE);
cfsetospeed(&newtio, BAUDRATE);

tcsetattr(fd, TCSANOW, &newtio);

tcflush(fd, TCIFLUSH);

//while(1)
{        
		write(fd, cbuf, 16);
}

    res_r = read(fd, &inbuf, 255);
    
    if(res_r != -1) {
       for(i = 0; i < res_r; i++) {
            buf[i] = (int)inbuf[i];
           buf[i] = buf[i] & 0xff;
            printf(" %x ", buf[i]);            
        }
        //printf("\n");
        //if(insertdb(buf[0], buf[1], buf[2], buf[3]))
         //  printf("insert into db success!");
    }
    else {
        perror("read fail");
        exit(-1);
    }// if end here
//}// for end here    

    tcsetattr(fd, TCSANOW, &oldtio);

    close(fd);
    exit(0);
} // main end here

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -