6_12_天天向上_TTYUSB0_embedded&&zigbee_2

来源:互联网 发布:如何在知乎回答问题 编辑:程序博客网 时间:2024/05/21 19:35

#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/ttyUSB0",O_RDWR|O_NOCTTY|O_NDELAY);
        if(fd==-1)
        {
                printf(" unable to open /dev/ttyUSB0\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,B38400);
        cfsetospeed(&options,B38400);
        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;
        unsigned char tmp[]={0x02,0x08,0xCB,0x01,0x00,0xD3,0x42,0x00,0x01,0x00,0x09};
        printf("in F_write_port\n");
        //n=write(fd,"hello world!\r",12);
       
  
   n=write(fd,tmp,11);
        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;
}

原创粉丝点击