简单的串口通信代码

python代码
#!/usr/bin/python2.7
import sys
import serial
import time


try:
 ser = serial.Serial('/dev/ttyUSB0', 9600)
except Exception, e:
 print 'open serial failed.%s'%e
 exit(1)

 # echo
print 'open serial success'
ser.write('B')
time.sleep(3)
ser.write('b')
ser.close()

C代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
  
int main()
{
  int fd, wr_num, rd_num, status;
  
  char send_buf[] = "B",send_buf2[] = "b", recv_buf[200];
  
  fd = open("/dev/ttyUSB0", O_RDWR);
  if (fd == -1)
    {
    printf("can't not open the COM1! \n");
    }
  else
    {
    printf("Open COM1 success! \n");
    }
  
  struct termios Opt;
  if (tcgetattr(fd, &Opt) != 0)
    {
    printf("tcgetattr fd \n");
    }
 
    /*设置数据位为8位*/
  Opt.c_cflag &= ~CSIZE;
  Opt.c_cflag |= CS8;
 
    /*设置校验位为None*/
  Opt.c_cflag &= ~PARENB;
  Opt.c_cflag &= INPCK;
 
    /*设置停止位为1*/
  Opt.c_cflag &= ~CSTOPB;
 
    /*数据处理*/
  Opt.c_lflag &= ~(ICANON|ECHO|ECHOE|ISIG);
  Opt.c_oflag &= ~OPOST;
  
  cfsetispeed(&Opt, B9600);
  cfsetospeed(&Opt, B9600);
  status = tcsetattr(fd, TCSANOW, &Opt);
  if (status != 0)
    {
    printf("tcsetattr fd1 \n");
    }
  tcflush(fd, TCIOFLUSH);
  

  wr_num = write(fd, send_buf, sizeof(send_buf));
  printf("write COM1 success! \n");
  sleep(5);
  wr_num = write(fd, send_buf2, sizeof(send_buf));
  printf("close COM1 success! \n");
  close(fd);  
  printf("close +%d \n",close(fd));
  return -1;  
}


你可能感兴趣的:(linux,python,C)