1 /*
2 * @brief Native TTY UART sample
3 *
4 * Copyright (c) 2023 Marko Sagadin
5 *
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9 #include <zephyr/kernel.h>
10 #include <zephyr/device.h>
11 #include <zephyr/drivers/uart.h>
12
13 #include <stdio.h>
14 #include <string.h>
15
16 const struct device *uart0 = DEVICE_DT_GET(DT_NODELABEL(uart0));
17 const struct device *uart2 = DEVICE_DT_GET(DT_NODELABEL(uart2));
18
19 struct uart_config uart_cfg = {
20 .baudrate = 9600,
21 .parity = UART_CFG_PARITY_NONE,
22 .stop_bits = UART_CFG_STOP_BITS_1,
23 .flow_ctrl = UART_CFG_FLOW_CTRL_NONE,
24 .data_bits = UART_CFG_DATA_BITS_8,
25 };
26
send_str(const struct device * uart,char * str)27 void send_str(const struct device *uart, char *str)
28 {
29 int msg_len = strlen(str);
30
31 for (int i = 0; i < msg_len; i++) {
32 uart_poll_out(uart, str[i]);
33 }
34
35 printk("Device %s sent: \"%s\"\n", uart->name, str);
36 }
37
recv_str(const struct device * uart,char * str)38 void recv_str(const struct device *uart, char *str)
39 {
40 char *head = str;
41 char c;
42
43 while (!uart_poll_in(uart, &c)) {
44 *head++ = c;
45 }
46 *head = '\0';
47
48 printk("Device %s received: \"%s\"\n", uart->name, str);
49 }
50
main(void)51 int main(void)
52 {
53 int rc;
54 char send_buf[64];
55 char recv_buf[64];
56 int i = 10;
57
58 while (i--) {
59 snprintf(send_buf, 64, "Hello from device %s, num %d", uart0->name, i);
60 send_str(uart0, send_buf);
61 /* Wait some time for the messages to arrive to the second uart. */
62 k_sleep(K_MSEC(100));
63 recv_str(uart2, recv_buf);
64
65 k_sleep(K_MSEC(1000));
66 }
67
68 uart_cfg.baudrate = 9600;
69 printk("\nChanging baudrate of both uart devices to %d!\n\n", uart_cfg.baudrate);
70
71 rc = uart_configure(uart0, &uart_cfg);
72 if (rc) {
73 printk("Could not configure device %s", uart0->name);
74 }
75 rc = uart_configure(uart2, &uart_cfg);
76 if (rc) {
77 printk("Could not configure device %s", uart2->name);
78 }
79
80 i = 10;
81 while (i--) {
82 snprintf(send_buf, 64, "Hello from device %s, num %d", uart0->name, i);
83 send_str(uart0, send_buf);
84 /* Wait some time for the messages to arrive to the second uart. */
85 k_sleep(K_MSEC(100));
86 recv_str(uart2, recv_buf);
87
88 k_sleep(K_MSEC(1000));
89 }
90
91 return 0;
92 }
93