esp_hal/uart.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
//! # Universal Asynchronous Receiver/Transmitter (UART)
//!
//! ## Overview
//!
//! The UART is a hardware peripheral which handles communication using serial
//! communication interfaces, such as RS232 and RS485. This peripheral provides
//! a cheap and ubiquitous method for full- and half-duplex communication
//! between devices.
//!
//! Depending on your device, two or more UART controllers are available for
//! use, all of which can be configured and used in the same way. All UART
//! controllers are compatible with UART-enabled devices from various
//! manufacturers, and can also support Infrared Data Association (IrDA)
//! protocols.
//!
//! ## Configuration
//!
//! Each UART controller is individually configurable, and the usual setting
//! such as baud rate, data bits, parity, and stop bits can easily be
//! configured. Additionally, the receive (RX) and transmit (TX) pins need to
//! be specified.
//!
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! # use esp_hal::uart::{Config, Uart};
//!
//! let mut uart1 = Uart::new(
//! peripherals.UART1,
//! Config::default())
//! .unwrap()
//! .with_rx(peripherals.GPIO1)
//! .with_tx(peripherals.GPIO2);
//! # }
//! ```
//!
//! The UART controller can be configured to invert the polarity of the pins.
//! This is achieved by inverting the desired pins, and then constructing the
//! UART instance using the inverted pins.
//!
//! ## Usage
//!
//! The UART driver implements a number of third-party traits, with the
//! intention of making the HAL inter-compatible with various device drivers
//! from the community. This includes, but is not limited to, the [embedded-hal]
//! and [embedded-io] blocking traits, and the [embedded-hal-async] and
//! [embedded-io-async] asynchronous traits.
//!
//! In addition to the interfaces provided by these traits, native APIs are also
//! available. See the examples below for more information on how to interact
//! with this driver.
//!
//! ## Examples
//! ### Sending and Receiving Data
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! # use esp_hal::uart::{Config, Uart};
//! # let mut uart1 = Uart::new(
//! # peripherals.UART1,
//! # Config::default(),
//! # ).unwrap()
//! # .with_rx(peripherals.GPIO1)
//! # .with_tx(peripherals.GPIO2);
//! // Write bytes out over the UART:
//! uart1.write_bytes(b"Hello, world!").expect("write error!");
//! # }
//! ```
//!
//! ### Splitting the UART into RX and TX Components
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! # use esp_hal::uart::{Config, Uart};
//! # let mut uart1 = Uart::new(
//! # peripherals.UART1,
//! # Config::default(),
//! # ).unwrap()
//! # .with_rx(peripherals.GPIO1)
//! # .with_tx(peripherals.GPIO2);
//! // The UART can be split into separate Transmit and Receive components:
//! let (mut rx, mut tx) = uart1.split();
//!
//! // Each component can be used individually to interact with the UART:
//! tx.write_bytes(&[42u8]).expect("write error!");
//! let mut byte = [0u8; 1];
//! rx.read_bytes(&mut byte);
//! # }
//! ```
//!
//! ### Inverting RX and TX Pins
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! # use esp_hal::uart::{Config, Uart};
//!
//! let (rx, _) = peripherals.GPIO2.split();
//! let (_, tx) = peripherals.GPIO1.split();
//! let mut uart1 = Uart::new(
//! peripherals.UART1,
//! Config::default())
//! .unwrap()
//! .with_rx(rx.inverted())
//! .with_tx(tx.inverted());
//! # }
//! ```
//!
//! ### Constructing RX and TX Components
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! # use esp_hal::uart::{Config, UartTx, UartRx};
//!
//! let tx = UartTx::new(
//! peripherals.UART0,
//! Config::default())
//! .unwrap()
//! .with_tx(peripherals.GPIO1);
//! let rx = UartRx::new(
//! peripherals.UART1,
//! Config::default())
//! .unwrap()
//! .with_rx(peripherals.GPIO2);
//! # }
//! ```
//!
//! ### Operation with interrupts that by UART/Serial
//! Notice, that in practice a proper serial terminal should be used
//! to connect to the board (espmonitor and espflash won't work)
//! ```rust, no_run
#![doc = crate::before_snippet!()]
//! # use esp_hal::delay::Delay;
//! # use esp_hal::uart::{AtCmdConfig, Config, Uart, UartInterrupt};
//! let delay = Delay::new();
//!
//! // Default pins for UART/Serial communication
#![cfg_attr(
esp32,
doc = "let (tx_pin, rx_pin) = (peripherals.GPIO1, peripherals.GPIO3);"
)]
#![cfg_attr(
esp32c2,
doc = "let (tx_pin, rx_pin) = (peripherals.GPIO20, peripherals.GPIO19);"
)]
#![cfg_attr(
esp32c3,
doc = "let (tx_pin, rx_pin) = (peripherals.GPIO21, peripherals.GPIO20);"
)]
#![cfg_attr(
esp32c6,
doc = "let (tx_pin, rx_pin) = (peripherals.GPIO16, peripherals.GPIO17);"
)]
#![cfg_attr(
esp32h2,
doc = "let (tx_pin, rx_pin) = (peripherals.GPIO24, peripherals.GPIO23);"
)]
#![cfg_attr(
any(esp32s2, esp32s3),
doc = "let (tx_pin, rx_pin) = (peripherals.GPIO43, peripherals.GPIO44);"
)]
//! let config = Config::default().with_rx_fifo_full_threshold(30);
//!
//! let mut uart0 = Uart::new(
//! peripherals.UART0,
//! config)
//! .unwrap()
//! .with_rx(rx_pin)
//! .with_tx(tx_pin);
//!
//! uart0.set_interrupt_handler(interrupt_handler);
//!
//! critical_section::with(|cs| {
//! uart0.set_at_cmd(AtCmdConfig::default().with_cmd_char(b'#'));
//! uart0.listen(UartInterrupt::AtCmd | UartInterrupt::RxFifoFull);
//!
//! SERIAL.borrow_ref_mut(cs).replace(uart0);
//! });
//!
//! loop {
//! critical_section::with(|cs| {
//! let mut serial = SERIAL.borrow_ref_mut(cs);
//! let serial = serial.as_mut().unwrap();
//! writeln!(serial,
//! "Hello World! Send a single `#` character or send
//! at least 30 characters to trigger interrupts.")
//! .ok();
//! });
//! delay.delay(1.secs());
//! }
//! # }
//!
//! # use core::cell::RefCell;
//! # use critical_section::Mutex;
//! # use esp_hal::uart::Uart;
//! static SERIAL: Mutex<RefCell<Option<Uart<esp_hal::Blocking>>>> =
//! Mutex::new(RefCell::new(None));
//!
//! # use esp_hal::uart::UartInterrupt;
//! # use core::fmt::Write;
//! #[handler]
//! fn interrupt_handler() {
//! critical_section::with(|cs| {
//! let mut serial = SERIAL.borrow_ref_mut(cs);
//! let serial = serial.as_mut().unwrap();
//!
//! let mut buf = [0u8; 64];
//! if let Ok(cnt) = serial.read_buffered_bytes(&mut buf) {
//! writeln!(serial, "Read {} bytes", cnt).ok();
//! }
//!
//! let pending_interrupts = serial.interrupts();
//! writeln!(
//! serial,
//! "Interrupt AT-CMD: {} RX-FIFO-FULL: {}",
//! pending_interrupts.contains(UartInterrupt::AtCmd),
//! pending_interrupts.contains(UartInterrupt::RxFifoFull),
//! ).ok();
//!
//! serial.clear_interrupts(
//! UartInterrupt::AtCmd | UartInterrupt::RxFifoFull
//! );
//! });
//! }
//! ```
//!
//! [embedded-hal]: https://docs.rs/embedded-hal/latest/embedded_hal/
//! [embedded-io]: https://docs.rs/embedded-io/latest/embedded_io/
//! [embedded-hal-async]: https://docs.rs/embedded-hal-async/latest/embedded_hal_async/
//! [embedded-io-async]: https://docs.rs/embedded-io-async/latest/embedded_io_async/
use core::{marker::PhantomData, sync::atomic::Ordering, task::Poll};
#[cfg(any(doc, feature = "unstable"))]
use embassy_embedded_hal::SetConfig;
use enumset::{EnumSet, EnumSetType};
use portable_atomic::AtomicBool;
use crate::{
asynch::AtomicWaker,
clock::Clocks,
gpio::{
interconnect::{PeripheralInput, PeripheralOutput},
InputSignal,
OutputSignal,
Pull,
},
interrupt::{InterruptConfigurable, InterruptHandler},
peripheral::{Peripheral, PeripheralRef},
peripherals::{uart0::RegisterBlock, Interrupt},
system::{PeripheralClockControl, PeripheralGuard},
Async,
Blocking,
DriverMode,
};
const UART_FIFO_SIZE: u16 = 128;
const CMD_CHAR_DEFAULT: u8 = 0x2b;
/// UART Error
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Error {
/// The RX FIFO overflow happened.
///
/// This error occurs when RX FIFO is full and a new byte is received.
FifoOverflowed,
/// A glitch was detected on the RX line.
///
/// This error occurs when an unexpected or erroneous signal (glitch) is
/// detected on the UART RX line, which could lead to incorrect data
/// reception.
GlitchOccurred,
/// A framing error was detected on the RX line.
///
/// This error occurs when the received data does not conform to the
/// expected UART frame format.
FrameFormatViolated,
/// A parity error was detected on the RX line.
///
/// This error occurs when the parity bit in the received data does not
/// match the expected parity configuration.
ParityMismatch,
}
impl core::error::Error for Error {}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::FifoOverflowed => write!(f, "The RX FIFO overflowed"),
Error::GlitchOccurred => write!(f, "A glitch was detected on the RX line"),
Error::FrameFormatViolated => write!(f, "A framing error was detected on the RX line"),
Error::ParityMismatch => write!(f, "A parity error was detected on the RX line"),
}
}
}
impl embedded_hal_nb::serial::Error for Error {
fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {
embedded_hal_nb::serial::ErrorKind::Other
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl embedded_io::Error for Error {
fn kind(&self) -> embedded_io::ErrorKind {
embedded_io::ErrorKind::Other
}
}
// (outside of `config` module in order not to "use" it an extra time)
/// UART clock source
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum ClockSource {
/// APB_CLK clock source
#[cfg_attr(not(any(esp32c6, esp32h2, lp_uart)), default)]
Apb,
/// RC_FAST_CLK clock source (17.5 MHz)
#[cfg(not(any(esp32, esp32s2)))]
RcFast,
/// XTAL_CLK clock source
#[cfg(not(any(esp32, esp32s2)))]
#[cfg_attr(any(esp32c6, esp32h2, lp_uart), default)]
Xtal,
/// REF_TICK clock source (derived from XTAL or RC_FAST, 1MHz)
#[cfg(any(esp32, esp32s2))]
RefTick,
}
// see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L61>
const UART_FULL_THRESH_DEFAULT: u16 = 120;
// see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L63>
const UART_TOUT_THRESH_DEFAULT: u8 = 10;
/// Number of data bits
///
/// This enum represents the various configurations for the number of data
/// bits used in UART communication. The number of data bits defines the
/// length of each transmitted or received data frame.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DataBits {
/// 5 data bits per frame.
_5 = 0,
/// 6 data bits per frame.
_6 = 1,
/// 7 data bits per frame.
_7 = 2,
/// 8 data bits per frame.
#[default]
_8 = 3,
}
/// Parity check
///
/// Parity is a form of error detection in UART communication, used to
/// ensure that the data has not been corrupted during transmission. The
/// parity bit is added to the data bits to make the number of 1-bits
/// either even or odd.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Parity {
/// No parity bit is used.
#[default]
None,
/// Even parity: the parity bit is set to make the total number of
/// 1-bits even.
Even,
/// Odd parity: the parity bit is set to make the total number of 1-bits
/// odd.
Odd,
}
/// Number of stop bits
///
/// The stop bit(s) signal the end of a data packet in UART communication.
/// This enum defines the possible configurations for the number of stop
/// bits.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum StopBits {
/// 1 stop bit.
#[default]
_1 = 1,
/// 1.5 stop bits.
_1p5 = 2,
/// 2 stop bits.
_2 = 3,
}
/// UART Configuration
#[derive(Debug, Clone, Copy, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct Config {
/// The baud rate (speed) of the UART communication in bits per second
/// (bps).
pub baudrate: u32,
/// Number of data bits in each frame (5, 6, 7, or 8 bits).
pub data_bits: DataBits,
/// Parity setting (None, Even, or Odd).
pub parity: Parity,
/// Number of stop bits in each frame (1, 1.5, or 2 bits).
pub stop_bits: StopBits,
/// Clock source used by the UART peripheral.
pub clock_source: ClockSource,
/// Threshold level at which the RX FIFO is considered full.
pub rx_fifo_full_threshold: u16,
/// Optional timeout value for RX operations.
pub rx_timeout: Option<u8>,
}
impl Config {
/// Calculates the total symbol length in bits based on the configured
/// data bits, parity, and stop bits.
fn symbol_length(&self) -> u8 {
let mut length: u8 = 1; // start bit
length += match self.data_bits {
DataBits::_5 => 5,
DataBits::_6 => 6,
DataBits::_7 => 7,
DataBits::_8 => 8,
};
length += match self.parity {
Parity::None => 0,
_ => 1,
};
length += match self.stop_bits {
StopBits::_1 => 1,
_ => 2, // esp-idf also counts 2 bits for settings 1.5 and 2 stop bits
};
length
}
}
impl Default for Config {
fn default() -> Config {
Config {
baudrate: 115_200,
data_bits: Default::default(),
parity: Default::default(),
stop_bits: Default::default(),
clock_source: Default::default(),
rx_fifo_full_threshold: UART_FULL_THRESH_DEFAULT,
rx_timeout: Some(UART_TOUT_THRESH_DEFAULT),
}
}
}
/// Configuration for the AT-CMD detection functionality
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
#[non_exhaustive]
pub struct AtCmdConfig {
/// Optional idle time before the AT command detection begins, in clock
/// cycles.
pub pre_idle_count: Option<u16>,
/// Optional idle time after the AT command detection ends, in clock
/// cycles.
pub post_idle_count: Option<u16>,
/// Optional timeout between characters in the AT command, in clock
/// cycles.
pub gap_timeout: Option<u16>,
/// The character that triggers the AT command detection.
pub cmd_char: u8,
/// Optional number of characters to detect as part of the AT command.
pub char_num: u8,
}
impl Default for AtCmdConfig {
fn default() -> Self {
Self {
pre_idle_count: None,
post_idle_count: None,
gap_timeout: None,
cmd_char: CMD_CHAR_DEFAULT,
char_num: 1,
}
}
}
struct UartBuilder<'d, Dm> {
uart: PeripheralRef<'d, AnyUart>,
phantom: PhantomData<Dm>,
}
impl<'d, Dm> UartBuilder<'d, Dm>
where
Dm: DriverMode,
{
fn new(uart: impl Peripheral<P = impl Instance> + 'd) -> Self {
crate::into_mapped_ref!(uart);
Self {
uart,
phantom: PhantomData,
}
}
fn init(self, config: Config) -> Result<Uart<'d, Dm>, ConfigError> {
let rx_guard = PeripheralGuard::new(self.uart.parts().0.peripheral);
let tx_guard = PeripheralGuard::new(self.uart.parts().0.peripheral);
let mut serial = Uart {
rx: UartRx {
uart: unsafe { self.uart.clone_unchecked() },
phantom: PhantomData,
guard: rx_guard,
},
tx: UartTx {
uart: self.uart,
phantom: PhantomData,
guard: tx_guard,
},
};
serial.init(config)?;
Ok(serial)
}
}
/// UART (Full-duplex)
pub struct Uart<'d, Dm> {
rx: UartRx<'d, Dm>,
tx: UartTx<'d, Dm>,
}
/// UART (Transmit)
pub struct UartTx<'d, Dm> {
uart: PeripheralRef<'d, AnyUart>,
phantom: PhantomData<Dm>,
guard: PeripheralGuard,
}
/// UART (Receive)
pub struct UartRx<'d, Dm> {
uart: PeripheralRef<'d, AnyUart>,
phantom: PhantomData<Dm>,
guard: PeripheralGuard,
}
/// A configuration error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum ConfigError {
/// The requested timeout is not supported.
UnsupportedTimeout,
/// The requested FIFO threshold is not supported.
UnsupportedFifoThreshold,
}
impl core::error::Error for ConfigError {}
impl core::fmt::Display for ConfigError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ConfigError::UnsupportedTimeout => write!(f, "The requested timeout is not supported"),
ConfigError::UnsupportedFifoThreshold => {
write!(f, "The requested FIFO threshold is not supported")
}
}
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> SetConfig for Uart<'_, Dm>
where
Dm: DriverMode,
{
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> SetConfig for UartRx<'_, Dm>
where
Dm: DriverMode,
{
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> SetConfig for UartTx<'_, Dm>
where
Dm: DriverMode,
{
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
impl<'d, Dm> UartTx<'d, Dm>
where
Dm: DriverMode,
{
/// Configure RTS pin
pub fn with_rts(self, rts: impl Peripheral<P = impl PeripheralOutput> + 'd) -> Self {
crate::into_mapped_ref!(rts);
rts.set_to_push_pull_output();
self.uart.info().rts_signal.connect_to(rts);
self
}
/// Assign the TX pin for UART instance.
///
/// Sets the specified pin to push-pull output and connects it to the UART
/// TX signal.
pub fn with_tx(self, tx: impl Peripheral<P = impl PeripheralOutput> + 'd) -> Self {
crate::into_mapped_ref!(tx);
// Make sure we don't cause an unexpected low pulse on the pin.
tx.set_output_high(true);
tx.set_to_push_pull_output();
self.uart.info().tx_signal.connect_to(tx);
self
}
/// Change the configuration.
///
/// Note that this also changes the configuration of the RX half.
pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.uart.info().apply_config(config)
}
/// Writes bytes
pub fn write_bytes(&mut self, data: &[u8]) -> Result<usize, Error> {
let count = data.len();
data.iter()
.try_for_each(|c| nb::block!(self.write_byte(*c)))?;
Ok(count)
}
fn write_byte(&mut self, word: u8) -> nb::Result<(), Error> {
if self.tx_fifo_count() < UART_FIFO_SIZE {
self.register_block()
.fifo()
.write(|w| unsafe { w.rxfifo_rd_byte().bits(word) });
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
#[allow(clippy::useless_conversion)]
/// Returns the number of bytes currently in the TX FIFO for this UART
/// instance.
fn tx_fifo_count(&self) -> u16 {
self.register_block()
.status()
.read()
.txfifo_cnt()
.bits()
.into()
}
/// Flush the transmit buffer of the UART
pub fn flush(&mut self) -> nb::Result<(), Error> {
if self.is_tx_idle() {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
/// Checks if the TX line is idle for this UART instance.
///
/// Returns `true` if the transmit line is idle, meaning no data is
/// currently being transmitted.
fn is_tx_idle(&self) -> bool {
#[cfg(esp32)]
let status = self.register_block().status();
#[cfg(not(esp32))]
let status = self.register_block().fsm_status();
status.read().st_utx_out().bits() == 0x0
}
/// Disables all TX-related interrupts for this UART instance.
///
/// This function clears and disables the `transmit FIFO empty` interrupt,
/// `transmit break done`, `transmit break idle done`, and `transmit done`
/// interrupts.
fn disable_tx_interrupts(&self) {
self.register_block().int_clr().write(|w| {
w.txfifo_empty().clear_bit_by_one();
w.tx_brk_done().clear_bit_by_one();
w.tx_brk_idle_done().clear_bit_by_one();
w.tx_done().clear_bit_by_one()
});
self.register_block().int_ena().write(|w| {
w.txfifo_empty().clear_bit();
w.tx_brk_done().clear_bit();
w.tx_brk_idle_done().clear_bit();
w.tx_done().clear_bit()
});
}
fn register_block(&self) -> &RegisterBlock {
self.uart.info().register_block()
}
}
impl<'d> UartTx<'d, Blocking> {
/// Create a new UART TX instance in [`Blocking`] mode.
pub fn new(
uart: impl Peripheral<P = impl Instance> + 'd,
config: Config,
) -> Result<Self, ConfigError> {
let (_, uart_tx) = UartBuilder::new(uart).init(config)?.split();
Ok(uart_tx)
}
/// Reconfigures the driver to operate in [`Async`] mode.
pub fn into_async(self) -> UartTx<'d, Async> {
if !self.uart.state().is_rx_async.load(Ordering::Acquire) {
self.uart
.info()
.set_interrupt_handler(self.uart.info().async_handler);
}
self.uart.state().is_tx_async.store(true, Ordering::Release);
UartTx {
uart: self.uart,
phantom: PhantomData,
guard: self.guard,
}
}
}
impl<'d> UartTx<'d, Async> {
/// Reconfigures the driver to operate in [`Blocking`] mode.
pub fn into_blocking(self) -> UartTx<'d, Blocking> {
self.uart
.state()
.is_tx_async
.store(false, Ordering::Release);
if !self.uart.state().is_rx_async.load(Ordering::Acquire) {
self.uart.info().disable_interrupts();
}
UartTx {
uart: self.uart,
phantom: PhantomData,
guard: self.guard,
}
}
}
#[inline(always)]
fn sync_regs(_register_block: &RegisterBlock) {
#[cfg(any(esp32c3, esp32c6, esp32h2, esp32s3))]
{
cfg_if::cfg_if! {
if #[cfg(any(esp32c6, esp32h2))] {
let update_reg = _register_block.reg_update();
} else {
let update_reg = _register_block.id();
}
}
update_reg.modify(|_, w| w.reg_update().set_bit());
while update_reg.read().reg_update().bit_is_set() {
// wait
}
}
}
impl<'d, Dm> UartRx<'d, Dm>
where
Dm: DriverMode,
{
/// Configure CTS pin
pub fn with_cts(self, cts: impl Peripheral<P = impl PeripheralInput> + 'd) -> Self {
crate::into_mapped_ref!(cts);
cts.init_input(Pull::None);
self.uart.info().cts_signal.connect_to(cts);
self
}
/// Assign the RX pin for UART instance.
///
/// Sets the specified pin to input and connects it to the UART RX signal.
///
/// Note: when you listen for the output of the UART peripheral, you should
/// configure the driver side (i.e. the TX pin), or ensure that the line is
/// initially high, to avoid receiving a non-data byte caused by an
/// initial low signal level.
pub fn with_rx(self, rx: impl Peripheral<P = impl PeripheralInput> + 'd) -> Self {
crate::into_mapped_ref!(rx);
rx.init_input(Pull::Up);
self.uart.info().rx_signal.connect_to(rx);
self
}
/// Change the configuration.
///
/// Note that this also changes the configuration of the TX half.
pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.uart.info().apply_config(config)
}
/// Reads and clears errors.
#[instability::unstable]
pub fn check_for_errors(&mut self) -> Result<(), Error> {
let errors = RxEvent::FifoOvf
| RxEvent::FifoTout
| RxEvent::GlitchDetected
| RxEvent::FrameError
| RxEvent::ParityError;
let events = self.uart.info().rx_events(errors);
let result = rx_event_check_for_error(events);
if result.is_err() {
self.uart.info().clear_rx_events(errors);
}
result
}
// Read a byte from the UART
fn read_byte(&mut self) -> Option<u8> {
cfg_if::cfg_if! {
if #[cfg(esp32s2)] {
// On the ESP32-S2 we need to use PeriBus2 to read the FIFO:
let fifo = unsafe {
&*((self.register_block().fifo().as_ptr() as *mut u8).add(0x20C00000)
as *mut crate::peripherals::uart0::FIFO)
};
} else {
let fifo = self.register_block().fifo();
}
}
if self.rx_fifo_count() > 0 {
// https://docs.espressif.com/projects/esp-chip-errata/en/latest/esp32/03-errata-description/esp32/cpu-subsequent-access-halted-when-get-interrupted.html
cfg_if::cfg_if! {
if #[cfg(esp32)] {
let byte = crate::interrupt::free(|| fifo.read().rxfifo_rd_byte().bits());
} else {
let byte = fifo.read().rxfifo_rd_byte().bits();
}
}
Some(byte)
} else {
None
}
}
/// Reads bytes from the UART
pub fn read_bytes(&mut self, buf: &mut [u8]) -> Result<(), Error> {
let buffered = self.read_buffered_bytes(buf)?;
let buf = &mut buf[buffered..];
for byte in buf.iter_mut() {
loop {
if let Some(b) = self.read_byte() {
*byte = b;
break;
}
self.check_for_errors()?;
}
}
Ok(())
}
/// Read all available bytes from the RX FIFO into the provided buffer and
/// returns the number of read bytes without blocking.
pub fn read_buffered_bytes(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
let mut count = 0;
while count < buf.len() {
if let Some(byte) = self.read_byte() {
buf[count] = byte;
count += 1;
} else {
break;
}
}
if let Err(err) = self.check_for_errors() {
// Drain the buffer. We don't know where the error occurred, so returning
// these bytes would be incorrect. We also don't know if the number of buffered
// bytes fit into the buffer.
// TODO: make this behaviour configurable using UART_ERR_WR_MASK. If the user
// wants to keep the bytes regardless of errors, they should be able to do so.
while self.read_byte().is_some() {}
return Err(err);
}
Ok(count)
}
/// Read bytes from the RX FIFO without checking for errors.
fn flush_buffer(&mut self, buf: &mut [u8]) -> usize {
let mut count = 0;
while count < buf.len() {
if let Some(byte) = self.read_byte() {
buf[count] = byte;
count += 1;
} else {
break;
}
}
count
}
#[allow(clippy::useless_conversion)]
fn rx_fifo_count(&self) -> u16 {
let fifo_cnt: u16 = self
.register_block()
.status()
.read()
.rxfifo_cnt()
.bits()
.into();
// Calculate the real count based on the FIFO read and write offset address:
// https://www.espressif.com/sites/default/files/documentation/esp32_errata_en.pdf
// section 3.17
#[cfg(esp32)]
{
let status = self.register_block().mem_rx_status().read();
let rd_addr = status.mem_rx_rd_addr().bits();
let wr_addr = status.mem_rx_wr_addr().bits();
if wr_addr > rd_addr {
wr_addr - rd_addr
} else if wr_addr < rd_addr {
(wr_addr + UART_FIFO_SIZE) - rd_addr
} else if fifo_cnt > 0 {
UART_FIFO_SIZE
} else {
0
}
}
#[cfg(not(esp32))]
fifo_cnt
}
/// Disables all RX-related interrupts for this UART instance.
///
/// This function clears and disables the `receive FIFO full` interrupt,
/// `receive FIFO overflow`, `receive FIFO timeout`, and `AT command
/// character detection` interrupts.
fn disable_rx_interrupts(&self) {
self.register_block().int_clr().write(|w| {
w.rxfifo_full().clear_bit_by_one();
w.rxfifo_ovf().clear_bit_by_one();
w.rxfifo_tout().clear_bit_by_one();
w.at_cmd_char_det().clear_bit_by_one()
});
self.register_block().int_ena().write(|w| {
w.rxfifo_full().clear_bit();
w.rxfifo_ovf().clear_bit();
w.rxfifo_tout().clear_bit();
w.at_cmd_char_det().clear_bit()
});
}
fn register_block(&self) -> &RegisterBlock {
self.uart.info().register_block()
}
}
impl<'d> UartRx<'d, Blocking> {
/// Create a new UART RX instance in [`Blocking`] mode.
pub fn new(
uart: impl Peripheral<P = impl Instance> + 'd,
config: Config,
) -> Result<Self, ConfigError> {
let (uart_rx, _) = UartBuilder::new(uart).init(config)?.split();
Ok(uart_rx)
}
/// Reconfigures the driver to operate in [`Async`] mode.
pub fn into_async(self) -> UartRx<'d, Async> {
if !self.uart.state().is_tx_async.load(Ordering::Acquire) {
self.uart
.info()
.set_interrupt_handler(self.uart.info().async_handler);
}
self.uart.state().is_rx_async.store(true, Ordering::Release);
UartRx {
uart: self.uart,
phantom: PhantomData,
guard: self.guard,
}
}
}
impl<'d> UartRx<'d, Async> {
/// Reconfigures the driver to operate in [`Blocking`] mode.
pub fn into_blocking(self) -> UartRx<'d, Blocking> {
self.uart
.state()
.is_rx_async
.store(false, Ordering::Release);
if !self.uart.state().is_tx_async.load(Ordering::Acquire) {
self.uart.info().disable_interrupts();
}
UartRx {
uart: self.uart,
phantom: PhantomData,
guard: self.guard,
}
}
}
impl<'d> Uart<'d, Blocking> {
/// Create a new UART instance in [`Blocking`] mode.
pub fn new(
uart: impl Peripheral<P = impl Instance> + 'd,
config: Config,
) -> Result<Self, ConfigError> {
UartBuilder::new(uart).init(config)
}
/// Reconfigures the driver to operate in [`Async`] mode.
pub fn into_async(self) -> Uart<'d, Async> {
Uart {
rx: self.rx.into_async(),
tx: self.tx.into_async(),
}
}
/// Assign the RX pin for UART instance.
///
/// Sets the specified pin to input and connects it to the UART RX signal.
///
/// Note: when you listen for the output of the UART peripheral, you should
/// configure the driver side (i.e. the TX pin), or ensure that the line is
/// initially high, to avoid receiving a non-data byte caused by an
/// initial low signal level.
pub fn with_rx(self, rx: impl Peripheral<P = impl PeripheralInput> + 'd) -> Self {
crate::into_mapped_ref!(rx);
rx.init_input(Pull::Up);
self.rx.uart.info().rx_signal.connect_to(rx);
self
}
/// Assign the TX pin for UART instance.
///
/// Sets the specified pin to push-pull output and connects it to the UART
/// TX signal.
pub fn with_tx(self, tx: impl Peripheral<P = impl PeripheralOutput> + 'd) -> Self {
crate::into_mapped_ref!(tx);
// Make sure we don't cause an unexpected low pulse on the pin.
tx.set_output_high(true);
tx.set_to_push_pull_output();
self.tx.uart.info().tx_signal.connect_to(tx);
self
}
}
impl<'d> Uart<'d, Async> {
/// Reconfigures the driver to operate in [`Blocking`] mode.
pub fn into_blocking(self) -> Uart<'d, Blocking> {
Uart {
rx: self.rx.into_blocking(),
tx: self.tx.into_blocking(),
}
}
}
/// List of exposed UART events.
#[derive(Debug, EnumSetType)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
#[instability::unstable]
pub enum UartInterrupt {
/// Indicates that the received has detected the configured
/// [`Uart::set_at_cmd`] character.
AtCmd,
/// The transmitter has finished sending out all data from the FIFO.
TxDone,
/// The receiver has received more data than what
/// [`Config::rx_fifo_full_threshold`] specifies.
RxFifoFull,
}
impl<'d, Dm> Uart<'d, Dm>
where
Dm: DriverMode,
{
/// Configure CTS pin
pub fn with_cts(mut self, cts: impl Peripheral<P = impl PeripheralInput> + 'd) -> Self {
self.rx = self.rx.with_cts(cts);
self
}
/// Configure RTS pin
pub fn with_rts(mut self, rts: impl Peripheral<P = impl PeripheralOutput> + 'd) -> Self {
self.tx = self.tx.with_rts(rts);
self
}
fn register_block(&self) -> &RegisterBlock {
// `self.tx.uart` and `self.rx.uart` are the same
self.tx.uart.info().register_block()
}
/// Split the UART into a transmitter and receiver
///
/// This is particularly useful when having two tasks correlating to
/// transmitting and receiving.
pub fn split(self) -> (UartRx<'d, Dm>, UartTx<'d, Dm>) {
(self.rx, self.tx)
}
/// Write bytes out over the UART
pub fn write_bytes(&mut self, data: &[u8]) -> Result<usize, Error> {
self.tx.write_bytes(data)
}
/// Reads and clears errors set by received data.
#[instability::unstable]
pub fn check_for_rx_errors(&mut self) -> Result<(), Error> {
self.rx.check_for_errors()
}
/// Reads bytes from the UART
pub fn read_bytes(&mut self, buf: &mut [u8]) -> Result<(), Error> {
self.rx.read_bytes(buf)
}
/// Read all available bytes from the RX FIFO into the provided buffer and
/// returns the number of read bytes without blocking.
pub fn read_buffered_bytes(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.rx.read_buffered_bytes(buf)
}
/// Configures the AT-CMD detection settings
#[instability::unstable]
pub fn set_at_cmd(&mut self, config: AtCmdConfig) {
let register_block = self.register_block();
#[cfg(not(any(esp32, esp32s2)))]
register_block
.clk_conf()
.modify(|_, w| w.sclk_en().clear_bit());
register_block.at_cmd_char().write(|w| unsafe {
w.at_cmd_char().bits(config.cmd_char);
w.char_num().bits(config.char_num)
});
if let Some(pre_idle_count) = config.pre_idle_count {
register_block
.at_cmd_precnt()
.write(|w| unsafe { w.pre_idle_num().bits(pre_idle_count as _) });
}
if let Some(post_idle_count) = config.post_idle_count {
register_block
.at_cmd_postcnt()
.write(|w| unsafe { w.post_idle_num().bits(post_idle_count as _) });
}
if let Some(gap_timeout) = config.gap_timeout {
register_block
.at_cmd_gaptout()
.write(|w| unsafe { w.rx_gap_tout().bits(gap_timeout as _) });
}
#[cfg(not(any(esp32, esp32s2)))]
register_block
.clk_conf()
.modify(|_, w| w.sclk_en().set_bit());
sync_regs(register_block);
}
// Write a byte out over the UART
fn write_byte(&mut self, word: u8) -> nb::Result<(), Error> {
self.tx.write_byte(word)
}
/// Flush the transmit buffer of the UART
pub fn flush(&mut self) -> nb::Result<(), Error> {
self.tx.flush()
}
// Read a byte from the UART
fn read_byte(&mut self) -> nb::Result<u8, Error> {
embedded_hal_nb::serial::Read::read(&mut self.rx)
}
/// Change the configuration.
pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.rx.apply_config(config)?;
Ok(())
}
#[inline(always)]
fn init(&mut self, config: Config) -> Result<(), ConfigError> {
cfg_if::cfg_if! {
if #[cfg(any(esp32, esp32s2))] {
// Nothing to do
} else if #[cfg(any(esp32c2, esp32c3, esp32s3))] {
unsafe { crate::peripherals::SYSTEM::steal() }
.perip_clk_en0()
.modify(|_, w| w.uart_mem_clk_en().set_bit());
} else {
self.register_block()
.conf0()
.modify(|_, w| w.mem_clk_en().set_bit());
}
};
self.uart_peripheral_reset();
self.rx.disable_rx_interrupts();
self.tx.disable_tx_interrupts();
self.rx.uart.info().apply_config(&config)?;
// Setting err_wr_mask stops uart from storing data when data is wrong according
// to reference manual
self.register_block()
.conf0()
.modify(|_, w| w.err_wr_mask().set_bit());
crate::rom::ets_delay_us(15);
// Make sure we are starting in a "clean state" - previous operations might have
// run into error conditions
self.register_block()
.int_clr()
.write(|w| unsafe { w.bits(u32::MAX) });
Ok(())
}
fn is_instance(&self, other: impl Instance) -> bool {
self.tx.uart.info().is_instance(other)
}
#[inline(always)]
fn uart_peripheral_reset(&self) {
// don't reset the console UART - this will cause trouble (i.e. the UART will
// start to transmit garbage)
//
// We should only reset the console UART if it was absolutely unused before.
// Apparently the bootloader (and maybe the ROM code) writing to the UART is
// already enough to make this a no-go. (i.e. one needs to mute the ROM
// code via efuse / strapping pin AND use a silent bootloader)
//
// TODO: make this configurable
// see https://github.com/espressif/esp-idf/blob/5f4249357372f209fdd57288265741aaba21a2b1/components/esp_driver_uart/src/uart.c#L179
if self.is_instance(unsafe { crate::peripherals::UART0::steal() }) {
return;
}
fn rst_core(_reg_block: &RegisterBlock, _enable: bool) {
#[cfg(not(any(esp32, esp32s2, esp32c6, esp32h2)))]
_reg_block
.clk_conf()
.modify(|_, w| w.rst_core().bit(_enable));
}
rst_core(self.register_block(), true);
PeripheralClockControl::reset(self.tx.uart.info().peripheral);
rst_core(self.register_block(), false);
}
}
impl crate::private::Sealed for Uart<'_, Blocking> {}
impl InterruptConfigurable for Uart<'_, Blocking> {
fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) {
// `self.tx.uart` and `self.rx.uart` are the same
self.tx.uart.info().set_interrupt_handler(handler);
}
}
impl Uart<'_, Blocking> {
/// Listen for the given interrupts
#[instability::unstable]
pub fn listen(&mut self, interrupts: impl Into<EnumSet<UartInterrupt>>) {
self.tx.uart.info().enable_listen(interrupts.into(), true)
}
/// Unlisten the given interrupts
#[instability::unstable]
pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<UartInterrupt>>) {
self.tx.uart.info().enable_listen(interrupts.into(), false)
}
/// Gets asserted interrupts
#[instability::unstable]
pub fn interrupts(&mut self) -> EnumSet<UartInterrupt> {
self.tx.uart.info().interrupts()
}
/// Resets asserted interrupts
#[instability::unstable]
pub fn clear_interrupts(&mut self, interrupts: EnumSet<UartInterrupt>) {
self.tx.uart.info().clear_interrupts(interrupts)
}
}
impl<Dm> ufmt_write::uWrite for Uart<'_, Dm>
where
Dm: DriverMode,
{
type Error = Error;
#[inline]
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.tx.write_str(s)
}
#[inline]
fn write_char(&mut self, ch: char) -> Result<(), Self::Error> {
self.tx.write_char(ch)
}
}
impl<Dm> ufmt_write::uWrite for UartTx<'_, Dm>
where
Dm: DriverMode,
{
type Error = Error;
#[inline]
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.write_bytes(s.as_bytes())?;
Ok(())
}
}
impl<Dm> core::fmt::Write for Uart<'_, Dm>
where
Dm: DriverMode,
{
#[inline]
fn write_str(&mut self, s: &str) -> core::fmt::Result {
self.tx.write_str(s)
}
}
impl<Dm> core::fmt::Write for UartTx<'_, Dm>
where
Dm: DriverMode,
{
#[inline]
fn write_str(&mut self, s: &str) -> core::fmt::Result {
self.write_bytes(s.as_bytes())
.map_err(|_| core::fmt::Error)?;
Ok(())
}
}
impl<Dm> embedded_hal_nb::serial::ErrorType for Uart<'_, Dm> {
type Error = Error;
}
impl<Dm> embedded_hal_nb::serial::ErrorType for UartTx<'_, Dm> {
type Error = Error;
}
impl<Dm> embedded_hal_nb::serial::ErrorType for UartRx<'_, Dm> {
type Error = Error;
}
impl<Dm> embedded_hal_nb::serial::Read for Uart<'_, Dm>
where
Dm: DriverMode,
{
fn read(&mut self) -> nb::Result<u8, Self::Error> {
self.read_byte()
}
}
impl<Dm> embedded_hal_nb::serial::Read for UartRx<'_, Dm>
where
Dm: DriverMode,
{
fn read(&mut self) -> nb::Result<u8, Self::Error> {
match self.read_byte() {
Some(b) => Ok(b),
None => Err(nb::Error::WouldBlock),
}
}
}
impl<Dm> embedded_hal_nb::serial::Write for Uart<'_, Dm>
where
Dm: DriverMode,
{
fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
self.write_byte(word)
}
fn flush(&mut self) -> nb::Result<(), Self::Error> {
self.flush()
}
}
impl<Dm> embedded_hal_nb::serial::Write for UartTx<'_, Dm>
where
Dm: DriverMode,
{
fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
self.write_byte(word)
}
fn flush(&mut self) -> nb::Result<(), Self::Error> {
self.flush()
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::ErrorType for Uart<'_, Dm> {
type Error = Error;
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::ErrorType for UartTx<'_, Dm> {
type Error = Error;
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::ErrorType for UartRx<'_, Dm> {
type Error = Error;
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::Read for Uart<'_, Dm>
where
Dm: DriverMode,
{
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
self.rx.read(buf)
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::Read for UartRx<'_, Dm>
where
Dm: DriverMode,
{
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
if buf.is_empty() {
return Ok(0);
}
while self.rx_fifo_count() == 0 {
// Block until we received at least one byte
}
self.read_buffered_bytes(buf)
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::ReadReady for Uart<'_, Dm>
where
Dm: DriverMode,
{
fn read_ready(&mut self) -> Result<bool, Self::Error> {
self.rx.read_ready()
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::ReadReady for UartRx<'_, Dm>
where
Dm: DriverMode,
{
fn read_ready(&mut self) -> Result<bool, Self::Error> {
Ok(self.rx_fifo_count() > 0)
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::Write for Uart<'_, Dm>
where
Dm: DriverMode,
{
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.tx.write(buf)
}
fn flush(&mut self) -> Result<(), Self::Error> {
embedded_io::Write::flush(&mut self.tx)
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl<Dm> embedded_io::Write for UartTx<'_, Dm>
where
Dm: DriverMode,
{
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.write_bytes(buf)
}
fn flush(&mut self) -> Result<(), Self::Error> {
loop {
match self.flush() {
Ok(_) => break,
Err(nb::Error::WouldBlock) => { /* Wait */ }
Err(nb::Error::Other(e)) => return Err(e),
}
}
Ok(())
}
}
#[derive(Debug, EnumSetType)]
pub(crate) enum TxEvent {
Done,
FiFoEmpty,
}
#[derive(Debug, EnumSetType)]
pub(crate) enum RxEvent {
FifoFull,
CmdCharDetected,
FifoOvf,
FifoTout,
GlitchDetected,
FrameError,
ParityError,
}
fn rx_event_check_for_error(events: EnumSet<RxEvent>) -> Result<(), Error> {
for event in events {
match event {
RxEvent::FifoOvf => return Err(Error::FifoOverflowed),
RxEvent::GlitchDetected => return Err(Error::GlitchOccurred),
RxEvent::FrameError => return Err(Error::FrameFormatViolated),
RxEvent::ParityError => return Err(Error::ParityMismatch),
RxEvent::FifoFull | RxEvent::CmdCharDetected | RxEvent::FifoTout => continue,
}
}
Ok(())
}
/// A future that resolves when the passed interrupt is triggered,
/// or has been triggered in the meantime (flag set in INT_RAW).
/// Upon construction the future enables the passed interrupt and when it
/// is dropped it disables the interrupt again. The future returns the event
/// that was initially passed, when it resolves.
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct UartRxFuture {
events: EnumSet<RxEvent>,
uart: &'static Info,
state: &'static State,
registered: bool,
}
impl UartRxFuture {
fn new(uart: impl Peripheral<P = impl Instance>, events: impl Into<EnumSet<RxEvent>>) -> Self {
crate::into_ref!(uart);
Self {
events: events.into(),
uart: uart.info(),
state: uart.state(),
registered: false,
}
}
}
impl core::future::Future for UartRxFuture {
type Output = EnumSet<RxEvent>;
fn poll(
mut self: core::pin::Pin<&mut Self>,
cx: &mut core::task::Context<'_>,
) -> core::task::Poll<Self::Output> {
if !self.registered {
self.state.rx_waker.register(cx.waker());
self.uart.enable_listen_rx(self.events, true);
self.registered = true;
}
let events = self.uart.enabled_rx_events(self.events);
if !events.is_empty() {
Poll::Ready(events)
} else {
Poll::Pending
}
}
}
impl Drop for UartRxFuture {
fn drop(&mut self) {
// Although the isr disables the interrupt that occurred directly, we need to
// disable the other interrupts (= the ones that did not occur), as
// soon as this future goes out of scope.
self.uart.enable_listen_rx(self.events, false);
}
}
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct UartTxFuture {
events: EnumSet<TxEvent>,
uart: &'static Info,
state: &'static State,
registered: bool,
}
impl UartTxFuture {
fn new(uart: impl Peripheral<P = impl Instance>, events: impl Into<EnumSet<TxEvent>>) -> Self {
crate::into_ref!(uart);
Self {
events: events.into(),
uart: uart.info(),
state: uart.state(),
registered: false,
}
}
fn triggered_events(&self) -> bool {
let interrupts_enabled = self.uart.register_block().int_ena().read();
let mut event_triggered = false;
for event in self.events {
event_triggered |= match event {
TxEvent::Done => interrupts_enabled.tx_done().bit_is_clear(),
TxEvent::FiFoEmpty => interrupts_enabled.txfifo_empty().bit_is_clear(),
}
}
event_triggered
}
fn enable_listen(&self, enable: bool) {
self.uart.register_block().int_ena().modify(|_, w| {
for event in self.events {
match event {
TxEvent::Done => w.tx_done().bit(enable),
TxEvent::FiFoEmpty => w.txfifo_empty().bit(enable),
};
}
w
});
}
}
impl core::future::Future for UartTxFuture {
type Output = ();
fn poll(
mut self: core::pin::Pin<&mut Self>,
cx: &mut core::task::Context<'_>,
) -> core::task::Poll<Self::Output> {
if !self.registered {
self.state.tx_waker.register(cx.waker());
self.enable_listen(true);
self.registered = true;
}
if self.triggered_events() {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
impl Drop for UartTxFuture {
fn drop(&mut self) {
// Although the isr disables the interrupt that occurred directly, we need to
// disable the other interrupts (= the ones that did not occur), as
// soon as this future goes out of scope.
self.enable_listen(false);
}
}
impl Uart<'_, Async> {
/// Asynchronously reads data from the UART receive buffer into the
/// provided buffer.
pub async fn read_async(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.rx.read_async(buf).await
}
/// Asynchronously writes data to the UART transmit buffer.
pub async fn write_async(&mut self, words: &[u8]) -> Result<usize, Error> {
self.tx.write_async(words).await
}
/// Asynchronously flushes the UART transmit buffer.
pub async fn flush_async(&mut self) -> Result<(), Error> {
self.tx.flush_async().await
}
}
impl UartTx<'_, Async> {
/// Asynchronously writes data to the UART transmit buffer in chunks.
///
/// This function sends the contents of the provided buffer `words` over
/// the UART. Data is written in chunks to avoid overflowing the
/// transmit FIFO, and the function waits asynchronously when
/// necessary for space in the buffer to become available.
pub async fn write_async(&mut self, words: &[u8]) -> Result<usize, Error> {
let mut count = 0;
let mut offset: usize = 0;
loop {
let mut next_offset = offset + (UART_FIFO_SIZE - self.tx_fifo_count()) as usize;
if next_offset > words.len() {
next_offset = words.len();
}
for byte in &words[offset..next_offset] {
self.write_byte(*byte).unwrap(); // should never fail
count += 1;
}
if next_offset >= words.len() {
break;
}
offset = next_offset;
UartTxFuture::new(self.uart.reborrow(), TxEvent::FiFoEmpty).await;
}
Ok(count)
}
/// Asynchronously flushes the UART transmit buffer.
///
/// This function ensures that all pending data in the transmit FIFO has
/// been sent over the UART. If the FIFO contains data, it waits
/// for the transmission to complete before returning.
pub async fn flush_async(&mut self) -> Result<(), Error> {
let count = self.tx_fifo_count();
if count > 0 {
UartTxFuture::new(self.uart.reborrow(), TxEvent::Done).await;
}
Ok(())
}
}
impl UartRx<'_, Async> {
/// Read async to buffer slice `buf`.
/// Waits until at least one byte is in the Rx FiFo
/// and one of the following interrupts occurs:
/// - `RXFIFO_FULL`
/// - `RXFIFO_OVF`
/// - `AT_CMD_CHAR_DET` (only if `set_at_cmd` was called)
/// - `RXFIFO_TOUT` (only if `set_rx_timeout` was called)
///
/// The interrupts in question are enabled during the body of this
/// function. The method immediately returns when the interrupt
/// has already occurred before calling this method (e.g. status
/// bit set, but interrupt not enabled)
///
/// # Params
/// - `buf` buffer slice to write the bytes into
///
///
/// # Ok
/// When successful, returns the number of bytes written to buf.
/// If the passed in buffer is of length 0, Ok(0) is returned.
pub async fn read_async(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
if buf.is_empty() {
return Ok(0);
}
loop {
let mut events = RxEvent::FifoFull
| RxEvent::FifoOvf
| RxEvent::FrameError
| RxEvent::GlitchDetected
| RxEvent::ParityError;
let register_block = self.uart.info().register_block();
if register_block.at_cmd_char().read().char_num().bits() > 0 {
events |= RxEvent::CmdCharDetected;
}
cfg_if::cfg_if! {
if #[cfg(any(esp32c6, esp32h2))] {
let reg_en = register_block.tout_conf();
} else {
let reg_en = register_block.conf1();
}
};
if reg_en.read().rx_tout_en().bit_is_set() {
events |= RxEvent::FifoTout;
}
let events_happened = UartRxFuture::new(self.uart.reborrow(), events).await;
// always drain the fifo, if an error has occurred the data is lost
let read_bytes = self.flush_buffer(buf);
// check error events
rx_event_check_for_error(events_happened)?;
// Unfortunately, the uart's rx-timeout counter counts up whenever there is
// data in the fifo, even if the interrupt is disabled and the status bit
// cleared. Since we do not drain the fifo in the interrupt handler, we need to
// reset the counter here, after draining the fifo.
self.register_block()
.int_clr()
.write(|w| w.rxfifo_tout().clear_bit_by_one());
if read_bytes > 0 {
return Ok(read_bytes);
}
}
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl embedded_io_async::Read for Uart<'_, Async> {
/// In contrast to the documentation of embedded_io_async::Read, this
/// method blocks until an uart interrupt occurs.
/// See UartRx::read_async for more details.
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
self.read_async(buf).await
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl embedded_io_async::Read for UartRx<'_, Async> {
/// In contrast to the documentation of embedded_io_async::Read, this
/// method blocks until an uart interrupt occurs.
/// See UartRx::read_async for more details.
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
self.read_async(buf).await
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl embedded_io_async::Write for Uart<'_, Async> {
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.write_async(buf).await
}
async fn flush(&mut self) -> Result<(), Self::Error> {
self.flush_async().await
}
}
#[cfg(any(doc, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
impl embedded_io_async::Write for UartTx<'_, Async> {
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.write_async(buf).await
}
async fn flush(&mut self) -> Result<(), Self::Error> {
self.flush_async().await
}
}
/// Interrupt handler for all UART instances
/// Clears and disables interrupts that have occurred and have their enable
/// bit set. The fact that an interrupt has been disabled is used by the
/// futures to detect that they should indeed resolve after being woken up
pub(super) fn intr_handler(uart: &Info, state: &State) {
let interrupts = uart.register_block().int_st().read();
let interrupt_bits = interrupts.bits(); // = int_raw & int_ena
let rx_wake = interrupts.rxfifo_full().bit_is_set()
|| interrupts.rxfifo_ovf().bit_is_set()
|| interrupts.rxfifo_tout().bit_is_set()
|| interrupts.at_cmd_char_det().bit_is_set()
|| interrupts.glitch_det().bit_is_set()
|| interrupts.frm_err().bit_is_set()
|| interrupts.parity_err().bit_is_set();
let tx_wake = interrupts.tx_done().bit_is_set() || interrupts.txfifo_empty().bit_is_set();
uart.register_block()
.int_clr()
.write(|w| unsafe { w.bits(interrupt_bits) });
uart.register_block()
.int_ena()
.modify(|r, w| unsafe { w.bits(r.bits() & !interrupt_bits) });
if tx_wake {
state.tx_waker.wake();
}
if rx_wake {
state.rx_waker.wake();
}
}
/// Low-power UART
#[cfg(lp_uart)]
#[instability::unstable]
pub mod lp_uart {
use crate::{
gpio::lp_io::{LowPowerInput, LowPowerOutput},
peripherals::{LP_CLKRST, LP_UART},
uart::{Config, DataBits, Parity, StopBits},
};
/// LP-UART driver
///
/// The driver uses XTAL as clock source.
pub struct LpUart {
uart: LP_UART,
}
impl LpUart {
/// Initialize the UART driver using the provided configuration
// TODO: CTS and RTS pins
pub fn new(
uart: LP_UART,
config: Config,
_tx: LowPowerOutput<'_, 5>,
_rx: LowPowerInput<'_, 4>,
) -> Self {
let lp_io = unsafe { crate::peripherals::LP_IO::steal() };
let lp_aon = unsafe { crate::peripherals::LP_AON::steal() };
// FIXME: use GPIO APIs to configure pins
lp_aon
.gpio_mux()
.modify(|r, w| unsafe { w.sel().bits(r.sel().bits() | (1 << 4) | (1 << 5)) });
lp_io.gpio(4).modify(|_, w| unsafe { w.mcu_sel().bits(1) });
lp_io.gpio(5).modify(|_, w| unsafe { w.mcu_sel().bits(1) });
let mut me = Self { uart };
// Set UART mode - do nothing for LP
// Disable UART parity
// 8-bit world
// 1-bit stop bit
me.uart.conf0().modify(|_, w| unsafe {
w.parity().clear_bit();
w.parity_en().clear_bit();
w.bit_num().bits(0x3);
w.stop_bit_num().bits(0x1)
});
// Set tx idle
me.uart
.idle_conf()
.modify(|_, w| unsafe { w.tx_idle_num().bits(0) });
// Disable hw-flow control
me.uart
.hwfc_conf()
.modify(|_, w| w.rx_flow_en().clear_bit());
// Get source clock frequency
// default == SOC_MOD_CLK_RTC_FAST == 2
// LP_CLKRST.lpperi.lp_uart_clk_sel = 0;
unsafe { LP_CLKRST::steal() }
.lpperi()
.modify(|_, w| w.lp_uart_clk_sel().clear_bit());
// Override protocol parameters from the configuration
// uart_hal_set_baudrate(&hal, cfg->uart_proto_cfg.baud_rate, sclk_freq);
me.change_baud_internal(config.baudrate, config.clock_source);
// uart_hal_set_parity(&hal, cfg->uart_proto_cfg.parity);
me.change_parity(config.parity);
// uart_hal_set_data_bit_num(&hal, cfg->uart_proto_cfg.data_bits);
me.change_data_bits(config.data_bits);
// uart_hal_set_stop_bits(&hal, cfg->uart_proto_cfg.stop_bits);
me.change_stop_bits(config.stop_bits);
// uart_hal_set_tx_idle_num(&hal, LP_UART_TX_IDLE_NUM_DEFAULT);
me.change_tx_idle(0); // LP_UART_TX_IDLE_NUM_DEFAULT == 0
// Reset Tx/Rx FIFOs
me.rxfifo_reset();
me.txfifo_reset();
me
}
fn rxfifo_reset(&mut self) {
self.uart.conf0().modify(|_, w| w.rxfifo_rst().set_bit());
self.update();
self.uart.conf0().modify(|_, w| w.rxfifo_rst().clear_bit());
self.update();
}
fn txfifo_reset(&mut self) {
self.uart.conf0().modify(|_, w| w.txfifo_rst().set_bit());
self.update();
self.uart.conf0().modify(|_, w| w.txfifo_rst().clear_bit());
self.update();
}
fn update(&mut self) {
self.uart
.reg_update()
.modify(|_, w| w.reg_update().set_bit());
while self.uart.reg_update().read().reg_update().bit_is_set() {
// wait
}
}
fn change_baud_internal(&mut self, baudrate: u32, clock_source: super::ClockSource) {
// TODO: Currently it's not possible to use XtalD2Clk
let clk = 16_000_000_u32;
let max_div = 0b1111_1111_1111 - 1;
let clk_div = clk.div_ceil(max_div * baudrate);
self.uart.clk_conf().modify(|_, w| unsafe {
w.sclk_div_a().bits(0);
w.sclk_div_b().bits(0);
w.sclk_div_num().bits(clk_div as u8 - 1);
w.sclk_sel().bits(match clock_source {
super::ClockSource::Xtal => 3,
super::ClockSource::RcFast => 2,
super::ClockSource::Apb => panic!("Wrong clock source for LP_UART"),
});
w.sclk_en().set_bit()
});
let clk = clk / clk_div;
let divider = clk / baudrate;
let divider = divider as u16;
self.uart
.clkdiv()
.write(|w| unsafe { w.clkdiv().bits(divider).frag().bits(0) });
self.update();
}
/// Modify UART baud rate and reset TX/RX fifo.
pub fn change_baud(&mut self, baudrate: u32, clock_source: super::ClockSource) {
self.change_baud_internal(baudrate, clock_source);
self.txfifo_reset();
self.rxfifo_reset();
}
fn change_parity(&mut self, parity: Parity) -> &mut Self {
if parity != Parity::None {
self.uart
.conf0()
.modify(|_, w| w.parity().bit((parity as u8 & 0x1) != 0));
}
self.uart.conf0().modify(|_, w| match parity {
Parity::None => w.parity_en().clear_bit(),
Parity::Even => w.parity_en().set_bit().parity().clear_bit(),
Parity::Odd => w.parity_en().set_bit().parity().set_bit(),
});
self
}
fn change_data_bits(&mut self, data_bits: DataBits) -> &mut Self {
self.uart
.conf0()
.modify(|_, w| unsafe { w.bit_num().bits(data_bits as u8) });
self.update();
self
}
fn change_stop_bits(&mut self, stop_bits: StopBits) -> &mut Self {
self.uart
.conf0()
.modify(|_, w| unsafe { w.stop_bit_num().bits(stop_bits as u8) });
self.update();
self
}
fn change_tx_idle(&mut self, idle_num: u16) -> &mut Self {
self.uart
.idle_conf()
.modify(|_, w| unsafe { w.tx_idle_num().bits(idle_num) });
self.update();
self
}
}
}
/// UART Peripheral Instance
#[doc(hidden)]
pub trait Instance: Peripheral<P = Self> + Into<AnyUart> + 'static {
/// Returns the peripheral data and state describing this UART instance.
fn parts(&self) -> (&'static Info, &'static State);
/// Returns the peripheral data describing this UART instance.
#[inline(always)]
fn info(&self) -> &'static Info {
self.parts().0
}
/// Returns the peripheral state for this UART instance.
#[inline(always)]
fn state(&self) -> &'static State {
self.parts().1
}
}
/// Peripheral data describing a particular UART instance.
#[doc(hidden)]
#[non_exhaustive]
pub struct Info {
/// Pointer to the register block for this UART instance.
///
/// Use [Self::register_block] to access the register block.
pub register_block: *const RegisterBlock,
/// The system peripheral marker.
pub peripheral: crate::system::Peripheral,
/// Interrupt handler for the asynchronous operations of this UART instance.
pub async_handler: InterruptHandler,
/// Interrupt for this UART instance.
pub interrupt: Interrupt,
/// TX pin
pub tx_signal: OutputSignal,
/// RX pin
pub rx_signal: InputSignal,
/// CTS (Clear to Send) pin
pub cts_signal: InputSignal,
/// RTS (Request to Send) pin
pub rts_signal: OutputSignal,
}
/// Peripheral state for a UART instance.
#[doc(hidden)]
#[non_exhaustive]
pub struct State {
/// Waker for the asynchronous RX operations.
pub rx_waker: AtomicWaker,
/// Waker for the asynchronous TX operations.
pub tx_waker: AtomicWaker,
/// Stores whether the TX half is configured for async operation.
pub is_rx_async: AtomicBool,
/// Stores whether the RX half is configured for async operation.
pub is_tx_async: AtomicBool,
}
impl Info {
/// Returns the register block for this UART instance.
pub fn register_block(&self) -> &RegisterBlock {
unsafe { &*self.register_block }
}
/// Listen for the given interrupts
fn enable_listen(&self, interrupts: EnumSet<UartInterrupt>, enable: bool) {
let reg_block = self.register_block();
reg_block.int_ena().modify(|_, w| {
for interrupt in interrupts {
match interrupt {
UartInterrupt::AtCmd => w.at_cmd_char_det().bit(enable),
UartInterrupt::TxDone => w.tx_done().bit(enable),
UartInterrupt::RxFifoFull => w.rxfifo_full().bit(enable),
};
}
w
});
}
fn interrupts(&self) -> EnumSet<UartInterrupt> {
let mut res = EnumSet::new();
let reg_block = self.register_block();
let ints = reg_block.int_raw().read();
if ints.at_cmd_char_det().bit_is_set() {
res.insert(UartInterrupt::AtCmd);
}
if ints.tx_done().bit_is_set() {
res.insert(UartInterrupt::TxDone);
}
if ints.rxfifo_full().bit_is_set() {
res.insert(UartInterrupt::RxFifoFull);
}
res
}
fn clear_interrupts(&self, interrupts: EnumSet<UartInterrupt>) {
let reg_block = self.register_block();
reg_block.int_clr().write(|w| {
for interrupt in interrupts {
match interrupt {
UartInterrupt::AtCmd => w.at_cmd_char_det().clear_bit_by_one(),
UartInterrupt::TxDone => w.tx_done().clear_bit_by_one(),
UartInterrupt::RxFifoFull => w.rxfifo_full().clear_bit_by_one(),
};
}
w
});
}
fn set_interrupt_handler(&self, handler: InterruptHandler) {
for core in crate::Cpu::other() {
crate::interrupt::disable(core, self.interrupt);
}
self.enable_listen(EnumSet::all(), false);
self.clear_interrupts(EnumSet::all());
unsafe { crate::interrupt::bind_interrupt(self.interrupt, handler.handler()) };
unwrap!(crate::interrupt::enable(self.interrupt, handler.priority()));
}
fn disable_interrupts(&self) {
crate::interrupt::disable(crate::Cpu::current(), self.interrupt);
}
fn apply_config(&self, config: &Config) -> Result<(), ConfigError> {
self.set_rx_fifo_full_threshold(config.rx_fifo_full_threshold)?;
self.set_rx_timeout(config.rx_timeout, config.symbol_length())?;
self.change_baud(config.baudrate, config.clock_source);
self.change_data_bits(config.data_bits);
self.change_parity(config.parity);
self.change_stop_bits(config.stop_bits);
// Reset Tx/Rx FIFOs
self.rxfifo_reset();
self.txfifo_reset();
Ok(())
}
fn enable_listen_rx(&self, events: EnumSet<RxEvent>, enable: bool) {
self.register_block().int_ena().modify(|_, w| {
for event in events {
match event {
RxEvent::FifoFull => w.rxfifo_full().bit(enable),
RxEvent::CmdCharDetected => w.at_cmd_char_det().bit(enable),
RxEvent::FifoOvf => w.rxfifo_ovf().bit(enable),
RxEvent::FifoTout => w.rxfifo_tout().bit(enable),
RxEvent::GlitchDetected => w.glitch_det().bit(enable),
RxEvent::FrameError => w.frm_err().bit(enable),
RxEvent::ParityError => w.parity_err().bit(enable),
};
}
w
});
}
fn enabled_rx_events(&self, events: impl Into<EnumSet<RxEvent>>) -> EnumSet<RxEvent> {
let events = events.into();
let interrupts_enabled = self.register_block().int_ena().read();
let mut events_triggered = EnumSet::new();
for event in events {
let event_triggered = match event {
RxEvent::FifoFull => interrupts_enabled.rxfifo_full().bit_is_clear(),
RxEvent::CmdCharDetected => interrupts_enabled.at_cmd_char_det().bit_is_clear(),
RxEvent::FifoOvf => interrupts_enabled.rxfifo_ovf().bit_is_clear(),
RxEvent::FifoTout => interrupts_enabled.rxfifo_tout().bit_is_clear(),
RxEvent::GlitchDetected => interrupts_enabled.glitch_det().bit_is_clear(),
RxEvent::FrameError => interrupts_enabled.frm_err().bit_is_clear(),
RxEvent::ParityError => interrupts_enabled.parity_err().bit_is_clear(),
};
if event_triggered {
events_triggered |= event;
}
}
events_triggered
}
fn rx_events(&self, events: impl Into<EnumSet<RxEvent>>) -> EnumSet<RxEvent> {
let events = events.into();
let interrupts_enabled = self.register_block().int_st().read();
let mut events_triggered = EnumSet::new();
for event in events {
let event_triggered = match event {
RxEvent::FifoFull => interrupts_enabled.rxfifo_full().bit_is_set(),
RxEvent::CmdCharDetected => interrupts_enabled.at_cmd_char_det().bit_is_set(),
RxEvent::FifoOvf => interrupts_enabled.rxfifo_ovf().bit_is_set(),
RxEvent::FifoTout => interrupts_enabled.rxfifo_tout().bit_is_set(),
RxEvent::GlitchDetected => interrupts_enabled.glitch_det().bit_is_set(),
RxEvent::FrameError => interrupts_enabled.frm_err().bit_is_set(),
RxEvent::ParityError => interrupts_enabled.parity_err().bit_is_set(),
};
if event_triggered {
events_triggered |= event;
}
}
events_triggered
}
fn clear_rx_events(&self, events: impl Into<EnumSet<RxEvent>>) {
let events = events.into();
self.register_block().int_clr().write(|w| {
for event in events {
match event {
RxEvent::FifoFull => w.rxfifo_full().clear_bit_by_one(),
RxEvent::CmdCharDetected => w.at_cmd_char_det().clear_bit_by_one(),
RxEvent::FifoOvf => w.rxfifo_ovf().clear_bit_by_one(),
RxEvent::FifoTout => w.rxfifo_tout().clear_bit_by_one(),
RxEvent::GlitchDetected => w.glitch_det().clear_bit_by_one(),
RxEvent::FrameError => w.frm_err().clear_bit_by_one(),
RxEvent::ParityError => w.parity_err().clear_bit_by_one(),
};
}
w
});
}
/// Configures the RX-FIFO threshold
///
/// # Errors
/// [`Err(ConfigError::UnsupportedFifoThreshold)`][ConfigError::UnsupportedFifoThreshold] if provided value exceeds maximum value
/// for SOC :
/// - `esp32` **0x7F**
/// - `esp32c6`, `esp32h2` **0xFF**
/// - `esp32c3`, `esp32c2`, `esp32s2` **0x1FF**
/// - `esp32s3` **0x3FF**
fn set_rx_fifo_full_threshold(&self, threshold: u16) -> Result<(), ConfigError> {
cfg_if::cfg_if! {
if #[cfg(esp32)] {
const MAX_THRHD: u16 = 0x7F;
} else if #[cfg(any(esp32c6, esp32h2))] {
const MAX_THRHD: u16 = 0xFF;
} else if #[cfg(any(esp32c3, esp32c2, esp32s2))] {
const MAX_THRHD: u16 = 0x1FF;
} else if #[cfg(esp32s3)] {
const MAX_THRHD: u16 = 0x3FF;
}
}
if threshold > MAX_THRHD {
return Err(ConfigError::UnsupportedFifoThreshold);
}
self.register_block()
.conf1()
.modify(|_, w| unsafe { w.rxfifo_full_thrhd().bits(threshold as _) });
Ok(())
}
/// Configures the Receive Timeout detection setting
///
/// # Arguments
/// `timeout` - the number of symbols ("bytes") to wait for before
/// triggering a timeout. Pass None to disable the timeout.
///
/// # Errors
/// [`Err(ConfigError::UnsupportedTimeout)`][ConfigError::UnsupportedTimeout] if the provided value exceeds
/// the maximum value for SOC :
/// - `esp32`: Symbol size is fixed to 8, do not pass a value > **0x7F**.
/// - `esp32c2`, `esp32c3`, `esp32c6`, `esp32h2`, esp32s2`, esp32s3`: The
/// value you pass times the symbol size must be <= **0x3FF**
// TODO: the above should be a per-chip doc line.
fn set_rx_timeout(&self, timeout: Option<u8>, _symbol_len: u8) -> Result<(), ConfigError> {
cfg_if::cfg_if! {
if #[cfg(esp32)] {
const MAX_THRHD: u8 = 0x7F; // 7 bits
} else {
const MAX_THRHD: u16 = 0x3FF; // 10 bits
}
}
let register_block = self.register_block();
if let Some(timeout) = timeout {
// the esp32 counts directly in number of symbols (symbol len fixed to 8)
#[cfg(esp32)]
let timeout_reg = timeout;
// all other count in bits, so we need to multiply by the symbol len.
#[cfg(not(esp32))]
let timeout_reg = timeout as u16 * _symbol_len as u16;
if timeout_reg > MAX_THRHD {
return Err(ConfigError::UnsupportedTimeout);
}
cfg_if::cfg_if! {
if #[cfg(esp32)] {
let reg_thrhd = register_block.conf1();
} else if #[cfg(any(esp32c6, esp32h2))] {
let reg_thrhd = register_block.tout_conf();
} else {
let reg_thrhd = register_block.mem_conf();
}
}
reg_thrhd.modify(|_, w| unsafe { w.rx_tout_thrhd().bits(timeout_reg) });
}
cfg_if::cfg_if! {
if #[cfg(any(esp32c6, esp32h2))] {
let reg_en = register_block.tout_conf();
} else {
let reg_en = register_block.conf1();
}
}
reg_en.modify(|_, w| w.rx_tout_en().bit(timeout.is_some()));
self.sync_regs();
Ok(())
}
#[cfg(any(esp32c2, esp32c3, esp32s3))]
fn change_baud(&self, baudrate: u32, clock_source: ClockSource) {
let clocks = Clocks::get();
let clk = match clock_source {
ClockSource::Apb => clocks.apb_clock.to_Hz(),
ClockSource::Xtal => clocks.xtal_clock.to_Hz(),
ClockSource::RcFast => crate::soc::constants::RC_FAST_CLK.to_Hz(),
};
if clock_source == ClockSource::RcFast {
unsafe { crate::peripherals::RTC_CNTL::steal() }
.clk_conf()
.modify(|_, w| w.dig_clk8m_en().variant(true));
// esp_rom_delay_us(SOC_DELAY_RC_FAST_DIGI_SWITCH);
crate::rom::ets_delay_us(5);
}
let max_div = 0b1111_1111_1111 - 1;
let clk_div = clk.div_ceil(max_div * baudrate);
self.register_block().clk_conf().write(|w| unsafe {
w.sclk_sel().bits(match clock_source {
ClockSource::Apb => 1,
ClockSource::RcFast => 2,
ClockSource::Xtal => 3,
});
w.sclk_div_a().bits(0);
w.sclk_div_b().bits(0);
w.sclk_div_num().bits(clk_div as u8 - 1);
w.rx_sclk_en().bit(true);
w.tx_sclk_en().bit(true)
});
let divider = (clk << 4) / (baudrate * clk_div);
let divider_integer = (divider >> 4) as u16;
let divider_frag = (divider & 0xf) as u8;
self.register_block()
.clkdiv()
.write(|w| unsafe { w.clkdiv().bits(divider_integer).frag().bits(divider_frag) });
}
fn is_instance(&self, other: impl Instance) -> bool {
self == other.info()
}
fn sync_regs(&self) {
sync_regs(self.register_block());
}
#[cfg(any(esp32c6, esp32h2))]
fn change_baud(&self, baudrate: u32, clock_source: ClockSource) {
let clocks = Clocks::get();
let clk = match clock_source {
ClockSource::Apb => clocks.apb_clock.to_Hz(),
ClockSource::Xtal => clocks.xtal_clock.to_Hz(),
ClockSource::RcFast => crate::soc::constants::RC_FAST_CLK.to_Hz(),
};
let max_div = 0b1111_1111_1111 - 1;
let clk_div = clk.div_ceil(max_div * baudrate);
// UART clocks are configured via PCR
let pcr = unsafe { crate::peripherals::PCR::steal() };
if self.is_instance(unsafe { crate::peripherals::UART0::steal() }) {
pcr.uart0_conf()
.modify(|_, w| w.uart0_rst_en().clear_bit().uart0_clk_en().set_bit());
pcr.uart0_sclk_conf().modify(|_, w| unsafe {
w.uart0_sclk_div_a().bits(0);
w.uart0_sclk_div_b().bits(0);
w.uart0_sclk_div_num().bits(clk_div as u8 - 1);
w.uart0_sclk_sel().bits(match clock_source {
ClockSource::Apb => 1,
ClockSource::RcFast => 2,
ClockSource::Xtal => 3,
});
w.uart0_sclk_en().set_bit()
});
} else {
pcr.uart1_conf()
.modify(|_, w| w.uart1_rst_en().clear_bit().uart1_clk_en().set_bit());
pcr.uart1_sclk_conf().modify(|_, w| unsafe {
w.uart1_sclk_div_a().bits(0);
w.uart1_sclk_div_b().bits(0);
w.uart1_sclk_div_num().bits(clk_div as u8 - 1);
w.uart1_sclk_sel().bits(match clock_source {
ClockSource::Apb => 1,
ClockSource::RcFast => 2,
ClockSource::Xtal => 3,
});
w.uart1_sclk_en().set_bit()
});
}
let clk = clk / clk_div;
let divider = clk / baudrate;
let divider = divider as u16;
self.register_block()
.clkdiv()
.write(|w| unsafe { w.clkdiv().bits(divider).frag().bits(0) });
self.sync_regs();
}
#[cfg(any(esp32, esp32s2))]
fn change_baud(&self, baudrate: u32, clock_source: ClockSource) {
let clk = match clock_source {
ClockSource::Apb => Clocks::get().apb_clock.to_Hz(),
// ESP32(/-S2) TRM, section 3.2.4.2 (6.2.4.2 for S2)
ClockSource::RefTick => crate::soc::constants::REF_TICK.to_Hz(),
};
self.register_block()
.conf0()
.modify(|_, w| w.tick_ref_always_on().bit(clock_source == ClockSource::Apb));
let divider = clk / baudrate;
self.register_block()
.clkdiv()
.write(|w| unsafe { w.clkdiv().bits(divider).frag().bits(0) });
}
fn change_data_bits(&self, data_bits: DataBits) {
self.register_block()
.conf0()
.modify(|_, w| unsafe { w.bit_num().bits(data_bits as u8) });
}
fn change_parity(&self, parity: Parity) {
self.register_block().conf0().modify(|_, w| match parity {
Parity::None => w.parity_en().clear_bit(),
Parity::Even => w.parity_en().set_bit().parity().clear_bit(),
Parity::Odd => w.parity_en().set_bit().parity().set_bit(),
});
}
fn change_stop_bits(&self, stop_bits: StopBits) {
#[cfg(esp32)]
{
// workaround for hardware issue, when UART stop bit set as 2-bit mode.
if stop_bits == StopBits::_2 {
self.register_block()
.rs485_conf()
.modify(|_, w| w.dl1_en().bit(stop_bits == StopBits::_2));
self.register_block()
.conf0()
.modify(|_, w| unsafe { w.stop_bit_num().bits(1) });
}
}
#[cfg(not(esp32))]
self.register_block()
.conf0()
.modify(|_, w| unsafe { w.stop_bit_num().bits(stop_bits as u8) });
}
fn rxfifo_reset(&self) {
fn rxfifo_rst(reg_block: &RegisterBlock, enable: bool) {
reg_block.conf0().modify(|_, w| w.rxfifo_rst().bit(enable));
sync_regs(reg_block);
}
rxfifo_rst(self.register_block(), true);
rxfifo_rst(self.register_block(), false);
}
fn txfifo_reset(&self) {
fn txfifo_rst(reg_block: &RegisterBlock, enable: bool) {
reg_block.conf0().modify(|_, w| w.txfifo_rst().bit(enable));
sync_regs(reg_block);
}
txfifo_rst(self.register_block(), true);
txfifo_rst(self.register_block(), false);
}
}
impl PartialEq for Info {
fn eq(&self, other: &Self) -> bool {
self.register_block == other.register_block
}
}
unsafe impl Sync for Info {}
macro_rules! impl_instance {
($inst:ident, $peri:ident, $txd:ident, $rxd:ident, $cts:ident, $rts:ident) => {
impl Instance for crate::peripherals::$inst {
fn parts(&self) -> (&'static Info, &'static State) {
#[crate::handler]
pub(super) fn irq_handler() {
intr_handler(&PERIPHERAL, &STATE);
}
static STATE: State = State {
tx_waker: AtomicWaker::new(),
rx_waker: AtomicWaker::new(),
is_rx_async: AtomicBool::new(false),
is_tx_async: AtomicBool::new(false),
};
static PERIPHERAL: Info = Info {
register_block: crate::peripherals::$inst::ptr(),
peripheral: crate::system::Peripheral::$peri,
async_handler: irq_handler,
interrupt: Interrupt::$inst,
tx_signal: OutputSignal::$txd,
rx_signal: InputSignal::$rxd,
cts_signal: InputSignal::$cts,
rts_signal: OutputSignal::$rts,
};
(&PERIPHERAL, &STATE)
}
}
};
}
impl_instance!(UART0, Uart0, U0TXD, U0RXD, U0CTS, U0RTS);
impl_instance!(UART1, Uart1, U1TXD, U1RXD, U1CTS, U1RTS);
#[cfg(uart2)]
impl_instance!(UART2, Uart2, U2TXD, U2RXD, U2CTS, U2RTS);
crate::any_peripheral! {
/// Any UART peripheral.
pub peripheral AnyUart {
#[cfg(uart0)]
Uart0(crate::peripherals::UART0),
#[cfg(uart1)]
Uart1(crate::peripherals::UART1),
#[cfg(uart2)]
Uart2(crate::peripherals::UART2),
}
}
impl Instance for AnyUart {
#[inline]
fn parts(&self) -> (&'static Info, &'static State) {
match &self.0 {
#[cfg(uart0)]
AnyUartInner::Uart0(uart) => uart.parts(),
#[cfg(uart1)]
AnyUartInner::Uart1(uart) => uart.parts(),
#[cfg(uart2)]
AnyUartInner::Uart2(uart) => uart.parts(),
}
}
}