6_11_天天向上_TTYUSB0_embedded&&zigbee_1

本文介绍了一个简单的串口通信程序实现,包括串口打开、初始化、写入及读取数据等功能。程序使用C语言编写,通过Linux系统提供的API完成串口设备的配置与交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#include<termios.h>

 

int open_port(void)
{
        int fd;
        fd=open("/dev/ttyS1",O_RDWR|O_NOCTTY|O_NDELAY);
        if(fd==-1)
        {
                printf(" unable to open /dev/ttyS1\n");

        }
        else
        {
                printf("\nOpen serial Ok~\n");
                      fcntl(fd,F_SETFL,0);


        }

        return(fd);
}


void init_serial(int fd)
{
        struct termios options;
        tcgetattr(fd,&options);
        cfsetispeed(&options,B115200);
        cfsetospeed(&options,B115200);
        options.c_cflag|=(CLOCAL|CREAD);
        options.c_cflag&=~CSIZE;
        options.c_cflag|=CS8;
        tcsetattr(fd,TCSANOW,&options);

}


int read_data(int fd)
{
        char buffer[255];
        char *bufptr;
        int nbytes;
        bufptr=buffer;

     while((nbytes=read(fd,bufptr,buffer+sizeof(buffer)-bufptr-1))>0)
        {

             
        bufptr+=nbytes;
        if(bufptr[-1]=='\n'|| bufptr[-1]=='\r')
                 break;


        }

        *bufptr='\0';
        printf("\n%s\n",buffer);

        return(0);
}

int write_port(int fd)
{
        int n;
        printf("in F_write_port\n");
        n=write(fd,"hello world!\r",12);
        if(n<0)
        {
                fputs("failed!\n",stderr);
        }
        else
        {
                printf("write ok\n");
        }
        return 0;
}

int main(void)
{
        int fd;
        fd=open_port();
        if(fd!=-1)
        {
           init_serial(fd);
               write_port(fd);

      
                //read_data(fd);

    

        }

        close(fd);
        return 0;
}

 

 

02 08 CB 01 00 D3 42 00 01 00 09
02 08 CB 14 06 D3 42 00 01 00 09
02 08 CB 27 0c D3 42 00 01 00 09
02 08 CB 3a 12 D3 42 00 01 00 09
02 08 CB 4d 18 D3 42 00 01 00 09
02 08 CB 60 1e D3 42 00 01 00 09

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

doublewei1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值