- #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>
- #include <string.h>
- #define FALSE -1
- #define TRUE 0
- int main(int argc, char *argv[]){
- //open port
- int fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY);
- if(FALSE == fd){
- perror("cant't open port\\n");
- exit(1);
- }
- //set port
- struct termios options, optionsOld;
- if(tcgetattr(fd, &optionsOld) != 0){
- perror("SetupSerial 1");
- exit(1);
- }
- bzero(&options, sizeof(optionsOld));
- tcflush(fd, TCIOFLUSH);
- options.c_cflag |= (CLOCAL | CREAD);
- //设置数据位
- options.c_cflag &= ~CSIZE;
- options.c_cflag |= CS8;
- //偶校验
- options.c_iflag |= (INPCK | ISTRIP);
- options.c_cflag |= PARENB;
- options.c_cflag &= ~PARODD;
- //19200波特率
- cfsetispeed(&options, B38400);
- cfsetospeed(&options, B38400);
- //1个停止位
- options.c_cflag &= ~CSTOPB;
- //原始数据输出
- options.c_oflag &= ~OPOST;
- options.c_cc[VTIME] = 0;
- options.c_cc[VMIN] = 1;
- tcflush(fd, TCIOFLUSH);
- tcsetattr(fd, TCSANOW, &options);
- //send data
- int sendLen = write(fd, argv[1], strlen(argv[1]));
- printf("send: %d\\n", sendLen);
- //read data
- char readC[1];
- readC[0] = ' ';
- int i = 0, j = strlen(argv[2]);
- //usleep(600000)
- //get resultStr sum
- int resStrSum = 0;
- for(i=0; i<j; i++){
- resStrSum = resStrSum*10+argv[2][i]-48;
- }
- printf("%d\\n", resStrSum);
- char *readStr = (char *)malloc(sizeof(char)*resStrSum*5);
- i = 0;
- while(read(fd, readC, 1)){
- if(readC[0] != '\\r'){
- readStr[i] = readC[0];
- putchar(readC[0]);
- i++;
- }else{
- break;
- }
- }
- readStr[i] = '\\0';
- printf("%s\\n", readStr);
- close(fd);
- }
- //该片段来自于http://www.codesnippet.cn/detail/1708201513463.html
来源: http://www.codesnippet.cn/detail/1708201513463.html