我正在一個新的項目,我想與連接到我的debian機器的FTDI連接。我打算用C編寫代碼,而不是C++。這是我的問題。我找到的所有例子都不完整,或者是用C++編譯器代替GCC編譯器。初始化,讀取和寫入linux的串行設備與C
目標是與我的微控制器連接到FTDI。爲了調試我要開始建立一個Linux應用程序,它能夠:
- 初始化ttyUSB1
- 在啓動時通過串行連接發送的字符串
- 顯示字符串時,他們被PC 收到
- 將通信保存爲一個.txt文件
是否有任何示例代碼或教程來做到這一點?
如果我成功了,我會將這裏的代碼放在這裏,以便新的觀衆可以使用它!
編輯:
就像我說的,如果我有它,我會發布的代碼,這是對我工作:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#define MODEM "/dev/ttyUSB0"
#define BAUDRATE B115200
int main(int argc,char** argv)
{
struct termios tio;
struct termios stdio;
struct termios old_stdio;
int tty_fd, flags;
unsigned char c='D';
tcgetattr(STDOUT_FILENO,&old_stdio);
printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]);
memset(&stdio,0,sizeof(stdio));
stdio.c_iflag=0;
stdio.c_oflag=0;
stdio.c_cflag=0;
stdio.c_lflag=0;
stdio.c_cc[VMIN]=1;
stdio.c_cc[VTIME]=0;
tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
memset(&tio,0,sizeof(tio));
tio.c_iflag=0;
tio.c_oflag=0;
tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
tio.c_lflag=0;
tio.c_cc[VMIN]=1;
tio.c_cc[VTIME]=5;
if((tty_fd = open(MODEM , O_RDWR | O_NONBLOCK)) == -1){
printf("Error while opening\n"); // Just if you want user interface error control
return -1;
}
cfsetospeed(&tio,BAUDRATE);
cfsetispeed(&tio,BAUDRATE); // baudrate is declarated above
tcsetattr(tty_fd,TCSANOW,&tio);
while (c!='q'){
if (read(tty_fd,&c,1)>0){
write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out
printf("\n");
}
if (read(STDIN_FILENO,&c,1)>0){
write(tty_fd,&c,1);//if new data is available on the console, send it to serial port
printf("\n");
}
}
close(tty_fd);
tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
return EXIT_SUCCESS;
}
的大多數代碼從http://en.wikibooks.org/wiki/Serial_Programming/Serial_Linux但我也來了從下面的代碼中使用了一下。
甚至有一個[很好的howto致力於該主題](http://tldp.org/HOWTO/Serial-Programming-HOWTO/)。 – fvu
你檢查這個問題http://stackoverflow.com/questions/2982552/correct-initialization-sequence-for-linux-serial-port?rq=1 – 999k
這有什麼錯小型機? – KBart