This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision | |||
|
products:sbc:edge2:applications:gpio:uart [2022/12/02 02:23] ivan [UART] |
products:sbc:edge2:applications:gpio:uart [2023/08/13 22:40] (current) jacobe |
||
|---|---|---|---|
| Line 36: | Line 36: | ||
| ``` | ``` | ||
| + | ===== Demo Source Code ===== | ||
| + | ```c uart.c | ||
| + | #include < | ||
| + | #include < | ||
| + | #include < | ||
| + | #include < | ||
| + | #include < | ||
| + | #include < | ||
| + | |||
| + | // set serial path | ||
| + | #define SERIAL_PORT "/ | ||
| + | |||
| + | int main() { | ||
| + | int serial_port; | ||
| + | struct termios tty; | ||
| + | | ||
| + | // open | ||
| + | serial_port = open(SERIAL_PORT, | ||
| + | if (serial_port < 0) { | ||
| + | perror(" | ||
| + | return 1; | ||
| + | } | ||
| + | | ||
| + | // Configuration of serial | ||
| + | memset(& | ||
| + | if (tcgetattr(serial_port, | ||
| + | perror(" | ||
| + | close(serial_port); | ||
| + | return 1; | ||
| + | } | ||
| + | | ||
| + | cfsetospeed(& | ||
| + | cfsetispeed(& | ||
| + | | ||
| + | tty.c_cflag |= (CLOCAL | CREAD); | ||
| + | tty.c_cflag &= ~PARENB; | ||
| + | tty.c_cflag &= ~CSTOPB; | ||
| + | tty.c_cflag &= ~CSIZE; | ||
| + | tty.c_cflag |= CS8; | ||
| + | | ||
| + | // write configration to serial | ||
| + | if (tcsetattr(serial_port, | ||
| + | perror(" | ||
| + | close(serial_port); | ||
| + | return 1; | ||
| + | } | ||
| + | | ||
| + | // loop test | ||
| + | while (1) { | ||
| + | // receive data | ||
| + | char received_data[64]; | ||
| + | if (read(serial_port, | ||
| + | // get data | ||
| + | printf(" | ||
| + | } | ||
| + | |||
| + | // Only send " | ||
| + | char data_to_send[] = " | ||
| + | write(serial_port, | ||
| + | | ||
| + | // sleep 100ms | ||
| + | usleep(100000); | ||
| + | } | ||
| + | | ||
| + | // close | ||
| + | close(serial_port); | ||
| + | | ||
| + | return 0; | ||
| + | } | ||
| + | ``` | ||
| + | |||
| + | Compile test code: | ||
| + | |||
| + | ``` | ||
| + | $ gcc uart.c -o uart | ||
| + | ``` | ||
| + | |||
| + | Run '' | ||
| + | |||
| + | ``` | ||
| + | $ ./uart | ||
| + | ``` | ||
| + | |||
| + | After connecting PIN12(STX), PIN14(CSO) and GND to PC, open ttyUSBX and input hello | ||
| + | |||
| + | ``` | ||
| + | 1 hello | ||
| + | 2 Hello, UART! | ||
| + | ``` | ||
| + | |||
| + | Check output data: | ||
| + | |||
| + | ``` | ||
| + | $ ./uart | ||
| + | Received: hello | ||
| + | ``` | ||
| ===== Disable UART to Use GPIO ===== | ===== Disable UART to Use GPIO ===== | ||
| If you want to use normal GPIO instead of UART, you can remove the UART node in [[products: | If you want to use normal GPIO instead of UART, you can remove the UART node in [[products: | ||