esp-hal 1.2.0

Bare-metal HAL for Espressif devices
Documentation
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
//! # 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.
//!
//! 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.
//!
//! [embedded-hal]: embedded_hal
//! [embedded-io]: embedded_io_07
//! [embedded-hal-async]: embedded_hal_async
//! [embedded-io-async]: embedded_io_async_07

crate::unstable_driver! {
    #[cfg(uhci_driver_supported)]
    pub mod uhci;

    #[cfg(lp_uart_driver_supported)]
    pub mod lp_uart;
}

#[cfg_attr(uart_version = "1", path = "clocks/v1.rs")]
#[cfg_attr(soc_has_pcr, path = "clocks/v2_pcr.rs")]
#[cfg_attr(esp32p4, path = "clocks/v2_esp32p4.rs")]
#[cfg_attr(esp32s31, path = "clocks/v2_esp32s31.rs")]
mod clocks;

mod compat;
mod low_level;

use core::{marker::PhantomData, sync::atomic::Ordering};

use embedded_hal_async::delay::DelayNs;
use enumset::{EnumSet, EnumSetType};
pub use low_level::Instance;
use low_level::{
    Info,
    RxEvent,
    State,
    TxEvent,
    UartClockGuard,
    UartRxFuture,
    UartTxFuture,
    enable_register_sync,
    rx_event_check_for_error,
    sync_regs,
};

use crate::{
    Async,
    Blocking,
    DriverMode,
    gpio::{
        InputConfig,
        OutputConfig,
        PinGuard,
        Pull,
        interconnect::{PeripheralInput, PeripheralOutput},
    },
    interrupt::InterruptHandler,
    pac::uart0::RegisterBlock,
    private::DropGuard,
    rtc_cntl::WakeLock,
    system::PeripheralGuard,
};

crate::any_peripheral! {
    /// Any UART peripheral.
    pub peripheral AnyUart<'d> {
        #[cfg(soc_has_uart0)]
        Uart0(crate::peripherals::UART0<'d>),
        #[cfg(soc_has_uart1)]
        Uart1(crate::peripherals::UART1<'d>),
        #[cfg(soc_has_uart2)]
        Uart2(crate::peripherals::UART2<'d>),
        #[cfg(soc_has_uart3)]
        Uart3(crate::peripherals::UART3<'d>),
        #[cfg(soc_has_uart4)]
        Uart4(crate::peripherals::UART4<'d>),
    }
}

impl Instance for AnyUart<'_> {
    #[inline]
    fn parts(&self) -> (&'static Info, &'static State) {
        any::delegate!(self, uart => { uart.parts() })
    }
}

impl AnyUart<'_> {
    pub(super) fn bind_peri_interrupt(&self, handler: InterruptHandler) {
        any::delegate!(self, uart => { uart.bind_peri_interrupt(handler) })
    }

    pub(super) fn disable_peri_interrupt_on_all_cores(&self) {
        any::delegate!(self, uart => { uart.disable_peri_interrupt_on_all_cores() })
    }

    pub(super) fn set_interrupt_handler(&self, handler: InterruptHandler) {
        self.disable_peri_interrupt_on_all_cores();

        self.info().enable_listen(EnumSet::all(), false);
        self.info().clear_interrupts(EnumSet::all());

        self.bind_peri_interrupt(handler);
    }
}

/// UART RX Error
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum RxError {
    /// An RX FIFO overflow happened.
    ///
    /// Occurs when the RX FIFO is full and a new byte is received. The RX FIFO
    /// is then automatically reset by the driver.
    FifoOverflowed,

    /// A glitch was detected on the RX line.
    ///
    /// 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.
    ///
    /// Occurs when the received data does not conform to the expected UART frame
    /// format.
    FrameFormatViolated,

    /// A parity error was detected on the RX line.
    ///
    /// Occurs when the parity bit in the received data does not match the
    /// expected parity configuration.
    ParityMismatch,
}

impl core::error::Error for RxError {}

/// UART RX error conditions that can be reported by read operations.
///
/// Used with [`RxConfig::with_reported_errors`] to choose which hardware RX
/// error conditions should make read operations return an [`RxError`]
#[derive(Debug, EnumSetType)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
#[non_exhaustive]
pub enum RxErrorKind {
    /// An RX FIFO overflow happened.
    FifoOverflowed,
    /// A glitch was detected on the RX line.
    GlitchOccurred,
    /// A framing error was detected on the RX line.
    FrameFormatViolated,
    /// A parity error was detected on the RX line.
    ParityMismatch,
}

impl From<RxErrorKind> for RxError {
    fn from(value: RxErrorKind) -> Self {
        match value {
            RxErrorKind::FifoOverflowed => RxError::FifoOverflowed,
            RxErrorKind::GlitchOccurred => RxError::GlitchOccurred,
            RxErrorKind::FrameFormatViolated => RxError::FrameFormatViolated,
            RxErrorKind::ParityMismatch => RxError::ParityMismatch,
        }
    }
}

impl core::fmt::Display for RxError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            RxError::FifoOverflowed => write!(f, "The RX FIFO overflowed"),
            RxError::GlitchOccurred => write!(f, "A glitch was detected on the RX line"),
            RxError::FrameFormatViolated => {
                write!(f, "A framing error was detected on the RX line")
            }
            RxError::ParityMismatch => write!(f, "A parity error was detected on the RX line"),
        }
    }
}

/// UART TX Error
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum TxError {}

impl core::fmt::Display for TxError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Tx error")
    }
}

impl core::error::Error for TxError {}

#[instability::unstable]
pub use crate::soc::clocks::UartFunctionClockSclk as ClockSource;

/// Number of data bits
///
/// 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,
    /// 6 data bits per frame.
    _6,
    /// 7 data bits per frame.
    _7,
    /// 8 data bits per frame.
    #[default]
    _8,
}

/// 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.
/// 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.5 stop bits.
    _1p5,
    /// 2 stop bits.
    _2,
}

/// Software flow control settings.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum SwFlowControl {
    #[default]
    /// Disables software flow control.
    Disabled,
    /// Enables software flow control with configured parameters.
    Enabled {
        /// Xon flow control byte.
        xon_char: u8,
        /// Xoff flow control byte.
        xoff_char: u8,
        /// If the software flow control is enabled and the data amount in
        /// rxfifo is less than xon_thrd, an xon_char will be sent.
        xon_threshold: u8,
        /// If the software flow control is enabled and the data amount in
        /// rxfifo is more than xoff_thrd, an xoff_char will be sent
        xoff_threshold: u8,
    },
}

/// Configuration for CTS (Clear To Send) flow control.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum CtsConfig {
    /// Enables CTS flow control (TX).
    Enabled,
    #[default]
    /// Disables CTS flow control (TX).
    Disabled,
}

/// Configuration for RTS (Request To Send) flow control.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum RtsConfig {
    /// Enables RTS flow control with a FIFO threshold (RX).
    Enabled(u8),
    #[default]
    /// Disables RTS flow control.
    Disabled,
}

/// Hardware flow control configuration.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub struct HwFlowControl {
    /// CTS configuration.
    pub cts: CtsConfig,
    /// RTS configuration.
    pub rts: RtsConfig,
}

/// Defines how strictly the requested baud rate must be met.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum BaudrateTolerance {
    /// Accepts the closest achievable baud rate without restriction.
    #[default]
    Closest,
    /// In this setting, the deviation of only 1% from the desired baud value is
    /// tolerated.
    Exact,
    /// Allows a certain percentage of deviation.
    ErrorPercent(u8),
}

/// 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).
    baudrate: u32,
    /// Determines how close to the desired baud rate value the driver should
    /// set the baud rate.
    #[builder_lite(unstable)]
    baudrate_tolerance: BaudrateTolerance,
    /// Number of data bits in each frame (5, 6, 7, or 8 bits).
    data_bits: DataBits,
    /// Parity setting (None, Even, or Odd).
    parity: Parity,
    /// Number of stop bits in each frame (1, 1.5, or 2 bits).
    stop_bits: StopBits,
    /// Software flow control.
    #[builder_lite(unstable)]
    sw_flow_ctrl: SwFlowControl,
    /// Hardware flow control.
    #[builder_lite(unstable)]
    hw_flow_ctrl: HwFlowControl,
    /// Clock source used by the UART peripheral.
    #[builder_lite(unstable)]
    clock_source: ClockSource,
    /// UART Receive part configuration.
    rx: RxConfig,
    /// UART Transmit part configuration.
    tx: TxConfig,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            rx: RxConfig::default(),
            tx: TxConfig::default(),
            baudrate: 115_200,
            baudrate_tolerance: BaudrateTolerance::default(),
            data_bits: Default::default(),
            parity: Default::default(),
            stop_bits: Default::default(),
            sw_flow_ctrl: Default::default(),
            hw_flow_ctrl: Default::default(),
            clock_source: Default::default(),
        }
    }
}

impl Config {
    fn validate(&self) -> Result<(), ConfigError> {
        if let BaudrateTolerance::ErrorPercent(percentage) = self.baudrate_tolerance {
            assert!(percentage > 0 && percentage <= 100);
        }

        // Max supported baud rate is 5Mbaud
        if self.baudrate == 0 || self.baudrate > 5_000_000 {
            return Err(ConfigError::BaudrateNotSupported);
        }
        Ok(())
    }
}

/// UART Receive part configuration.
#[derive(Debug, Clone, Copy, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct RxConfig {
    /// Threshold level at which the RX FIFO is considered full.
    fifo_full_threshold: u16,
    /// Optional timeout value for RX operations.
    timeout: Option<u8>,
    /// RX error conditions that read operations should report.
    ///
    /// Error conditions not present in this set are cleared and ignored by
    /// UART read operations.
    #[builder_lite(unstable, into)]
    reported_errors: EnumSet<RxErrorKind>,
    /// Whether received bytes with UART errors are discarded by the hardware.
    ///
    /// When set to `true` (the default), bytes with UART errors (for example
    /// parity or framing errors) are not stored in the RX FIFO. Set this to
    /// `false` to keep those bytes in the RX FIFO. Use
    /// [`Self::with_reported_errors`] to control whether those error
    /// conditions make read operations fail.
    #[builder_lite(unstable)]
    discard_erroneous_bytes: bool,
}

impl Default for RxConfig {
    fn default() -> RxConfig {
        RxConfig {
            // see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L61>
            fifo_full_threshold: 120,
            // see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L63>
            timeout: Some(10),
            reported_errors: EnumSet::all(),
            discard_erroneous_bytes: true,
        }
    }
}

/// UART Transmit part configuration.
#[derive(Debug, Clone, Copy, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct TxConfig {
    /// Threshold level at which the TX FIFO is considered empty.
    fifo_empty_threshold: u16,
}

impl Default for TxConfig {
    fn default() -> TxConfig {
        TxConfig {
            // see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L59>
            fifo_empty_threshold: 10,
        }
    }
}

/// 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.
    pre_idle_count: Option<u16>,
    /// Optional idle time after the AT command detection ends, in clock
    /// cycles.
    post_idle_count: Option<u16>,
    /// Optional timeout between bytes in the AT command, in clock
    /// cycles.
    gap_timeout: Option<u16>,
    /// The byte (character) that triggers the AT command detection.
    cmd_char: u8,
    /// Optional number of bytes to detect as part of the AT command.
    char_num: u8,
}

impl Default for AtCmdConfig {
    fn default() -> Self {
        Self {
            pre_idle_count: None,
            post_idle_count: None,
            gap_timeout: None,
            cmd_char: b'+',
            char_num: 1,
        }
    }
}

/// The number of edges that the hardware counts before the threshold register starts.
#[cfg(sleep_driver_supported)]
const WAKEUP_EDGE_OFFSET: u16 = cfg_select! {
    esp32 => 2,
    esp32p4 => 6,
    _ => 3,
};

/// The smallest number of rising edges that the hardware can wake on.
#[cfg(sleep_driver_supported)]
const MIN_WAKEUP_EDGES: u16 = cfg_select! {
    // With a threshold of zero, esp32 wakes again and again.
    esp32 => WAKEUP_EDGE_OFFSET + 1,
    _ => WAKEUP_EDGE_OFFSET,
};

/// The largest number of rising edges that the hardware can count in its 10-bit field.
#[cfg(sleep_driver_supported)]
const MAX_WAKEUP_EDGES: u16 = WAKEUP_EDGE_OFFSET + 0x3FF;

/// Configures how the UART wakes the chip from light sleep.
///
/// See [`UartRx::enable_wakeup`].
#[cfg(sleep_driver_supported)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
#[non_exhaustive]
pub struct WakeupConfig {
    /// The number of rising edges on the RX line that wakes the chip.
    ///
    /// The hardware counts edges, and not bytes, so the number of bytes that the chip needs
    /// depends on the data of the sender. Each byte gives one rising edge at its stop bit, and
    /// one more edge for each change from 0 to 1 in the data. The number of edges is therefore
    /// the smallest possible number of bytes. The default is the smallest value that the
    /// hardware accepts.
    ///
    /// The permitted range on this chip is
    #[cfg_attr(esp32, doc = "`3..=1025`.")]
    #[cfg_attr(esp32p4, doc = "`6..=1029`.")]
    #[cfg_attr(not(any(esp32, esp32p4)), doc = "`3..=1026`.")]
    rising_edges: u16,
}

#[cfg(sleep_driver_supported)]
impl Default for WakeupConfig {
    fn default() -> Self {
        Self {
            rising_edges: MIN_WAKEUP_EDGES,
        }
    }
}

/// A wakeup configuration error.
#[cfg(sleep_driver_supported)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
#[non_exhaustive]
pub enum WakeConfigError {
    /// This UART instance cannot wake the chip.
    NotAWakeupSource,

    /// The hardware cannot count the requested number of rising edges.
    EdgeCountUnsupported,
}

#[cfg(sleep_driver_supported)]
#[instability::unstable]
impl core::error::Error for WakeConfigError {}

#[cfg(sleep_driver_supported)]
#[instability::unstable]
impl core::fmt::Display for WakeConfigError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            WakeConfigError::NotAWakeupSource => {
                write!(f, "This UART instance cannot wake the chip")
            }
            WakeConfigError::EdgeCountUnsupported => {
                write!(
                    f,
                    "The requested number of rising edges is not supported, it must be {MIN_WAKEUP_EDGES}..={MAX_WAKEUP_EDGES}"
                )
            }
        }
    }
}

struct UartBuilder<'d, Dm: DriverMode> {
    uart: AnyUart<'d>,
    phantom: PhantomData<Dm>,
}

impl<'d, Dm> UartBuilder<'d, Dm>
where
    Dm: DriverMode,
{
    fn new(uart: impl Instance + 'd) -> Self {
        let uart = uart.degrade();

        // Make sure inputs are well-defined.
        // Connect RX to an idle high level.
        uart.info().rx_signal.connect_to(&crate::gpio::Level::High);
        uart.info().cts_signal.connect_to(&crate::gpio::Level::Low);

        Self {
            uart,
            phantom: PhantomData,
        }
    }

    fn init(self, config: Config) -> Result<Uart<'d, Dm>, ConfigError> {
        let rx_guard = PeripheralGuard::new(self.uart.info().peripheral);
        let tx_guard = PeripheralGuard::new(self.uart.info().peripheral);

        let peri_clock_guard = UartClockGuard::new(unsafe { self.uart.clone_unchecked() });

        let rts_pin = PinGuard::new_unconnected();
        let tx_pin = PinGuard::new_unconnected();

        let mut serial = Uart {
            rx: UartRx {
                uart: unsafe { self.uart.clone_unchecked() },
                phantom: PhantomData,
                guard: rx_guard,
                peri_clock_guard: peri_clock_guard.clone(),
                // Receiving data continuously, the peripheral can't let the system sleep.
                _wake_lock: WakeLock::new(),
                reported_errors: config.rx.reported_errors,
            },
            tx: UartTx {
                uart: self.uart,
                phantom: PhantomData,
                guard: tx_guard,
                peri_clock_guard,
                rts_pin,
                tx_pin,
                baudrate: config.baudrate,
            },
        };
        serial.init(config)?;

        Ok(serial)
    }
}

#[procmacros::doc_replace]
/// UART (Full-duplex)
///
/// # Examples
///
/// ```rust, no_run
/// # {before_snippet}
/// use esp_hal::uart::{Config, Uart};
/// let mut uart = Uart::new(peripherals.UART0, Config::default())?
///     .with_rx(peripherals.GPIO1)
///     .with_tx(peripherals.GPIO2);
///
/// uart.write(b"Hello world!")?;
/// # {after_snippet}
/// ```
pub struct Uart<'d, Dm: DriverMode> {
    rx: UartRx<'d, Dm>,
    tx: UartTx<'d, Dm>,
}

/// UART (Transmit)
#[instability::unstable]
pub struct UartTx<'d, Dm: DriverMode> {
    uart: AnyUart<'d>,
    phantom: PhantomData<Dm>,
    guard: PeripheralGuard,
    peri_clock_guard: UartClockGuard<'d>,
    rts_pin: PinGuard,
    tx_pin: PinGuard,
    baudrate: u32,
}

/// UART (Receive)
#[instability::unstable]
pub struct UartRx<'d, Dm: DriverMode> {
    uart: AnyUart<'d>,
    phantom: PhantomData<Dm>,
    guard: PeripheralGuard,
    peri_clock_guard: UartClockGuard<'d>,
    // Receiving data continuously, the peripheral can't let the system sleep.
    _wake_lock: WakeLock,
    reported_errors: EnumSet<RxErrorKind>,
}

/// A configuration error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum ConfigError {
    /// The requested baud rate is not achievable.
    #[cfg(feature = "unstable")]
    #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
    BaudrateNotAchievable,

    /// The requested baud rate is not supported.
    ///
    /// Returned when:
    ///  * the baud rate exceeds 5MBaud or is equal to zero.
    ///  * an exact baud rate or a deviation tolerance is specified, and the driver cannot reach
    ///    that speed.
    BaudrateNotSupported,

    /// The requested timeout exceeds the maximum value (.
    #[cfg_attr(esp32, doc = "127")]
    #[cfg_attr(not(esp32), doc = "1023")]
    /// ).
    TimeoutTooLong,

    /// The requested RX FIFO threshold exceeds the maximum value (127 bytes).
    RxFifoThresholdNotSupported,

    /// The requested TX FIFO threshold exceeds the maximum value (127 bytes).
    TxFifoThresholdNotSupported,
}

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 {
            #[cfg(feature = "unstable")]
            ConfigError::BaudrateNotAchievable => {
                write!(f, "The requested baud rate is not achievable")
            }
            ConfigError::BaudrateNotSupported => {
                write!(f, "The requested baud rate is not supported")
            }
            ConfigError::TimeoutTooLong => write!(f, "The requested timeout is not supported"),
            ConfigError::RxFifoThresholdNotSupported => {
                write!(f, "The requested RX FIFO threshold is not supported")
            }
            ConfigError::TxFifoThresholdNotSupported => {
                write!(f, "The requested TX FIFO threshold is not supported")
            }
        }
    }
}

impl<'d> UartTx<'d, Blocking> {
    #[procmacros::doc_replace(
        "note" => {
            cfg(esp32) => "**esp32-specific ⚠️**: `UART2` is not recommended for use.",
            _ => ""
        }
    )]
    /// Creates a new UART TX instance in [`Blocking`] mode.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, UartTx};
    /// let tx = UartTx::new(peripherals.UART0, Config::default())?.with_tx(peripherals.GPIO1);
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when the configuration is not supported by the hardware
    #[instability::unstable]
    pub fn new(uart: 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.
    #[instability::unstable]
    pub fn into_async(self) -> UartTx<'d, Async> {
        if !self.uart.state().is_rx_async.load(Ordering::Acquire) {
            self.uart
                .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,
            peri_clock_guard: self.peri_clock_guard,
            rts_pin: self.rts_pin,
            tx_pin: self.tx_pin,
            baudrate: self.baudrate,
        }
    }
}

impl<'d> UartTx<'d, Async> {
    /// Reconfigures the driver to operate in [`Blocking`] mode.
    #[instability::unstable]
    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.disable_peri_interrupt_on_all_cores();
        }

        UartTx {
            uart: self.uart,
            phantom: PhantomData,
            guard: self.guard,
            peri_clock_guard: self.peri_clock_guard,
            rts_pin: self.rts_pin,
            tx_pin: self.tx_pin,
            baudrate: self.baudrate,
        }
    }

    /// Writes data into the TX buffer.
    ///
    /// Writes the provided buffer `bytes` into the UART transmit buffer. If the
    /// buffer is full, waits asynchronously for space in the buffer to become
    /// available.
    ///
    /// Returns the number of bytes written into the buffer. This may be less
    /// than the length of the buffer.
    ///
    /// Upon an error, returns immediately and the contents of the internal FIFO
    /// are not modified.
    ///
    /// # Cancellation Safety
    ///
    /// Cancellation safe.
    pub async fn write_async(&mut self, bytes: &[u8]) -> Result<usize, TxError> {
        // We need to loop in case the TX empty interrupt was fired but not cleared
        // before, but the FIFO itself was filled up by a previous write.
        let space = loop {
            let tx_fifo_count = self.uart.info().tx_fifo_count();
            let space = Info::UART_FIFO_SIZE - tx_fifo_count;
            if space != 0 {
                break space;
            }
            UartTxFuture::new(self.uart.reborrow(), TxEvent::FiFoEmpty).await;
        };

        let free = (space as usize).min(bytes.len());

        for &byte in &bytes[..free] {
            self.uart
                .info()
                .regs()
                .fifo()
                .write(|w| unsafe { w.rxfifo_rd_byte().bits(byte) });
        }

        Ok(free)
    }

    /// Asynchronously flushes the UART transmit buffer.
    ///
    /// Ensures that all pending data in the transmit FIFO has been sent over the
    /// UART. If the FIFO contains data, waits for the transmission to complete
    /// before returning.
    ///
    /// # Cancellation Safety
    ///
    /// Cancellation safe.
    pub async fn flush_async(&mut self) -> Result<(), TxError> {
        // Nothing is guaranteed to clear the Done status, so let's loop here in case Tx
        // was Done before the last write operation that pushed data into the
        // FIFO.
        while self.uart.info().tx_fifo_count() > 0 {
            UartTxFuture::new(self.uart.reborrow(), TxEvent::Done).await;
        }

        self.flush_last_byte();

        Ok(())
    }

    /// Sends a break signal for a specified duration in bit time.
    ///
    /// Duration is in bits, the time it takes to transfer one bit at the
    /// current baud rate.
    ///
    /// Restores the original TX line state after the break signal is sent, even if
    /// the future is cancelled.
    #[instability::unstable]
    pub async fn send_break_async<D: DelayNs>(&mut self, delay: &mut D, bits: u32) {
        // Calculate total delay in microseconds
        let total_delay_us = (bits as u64 * 1_000_000) / self.baudrate as u64;
        let delay_us = (total_delay_us as u32).max(1);

        let break_guard = self.start_break();

        delay.delay_us(delay_us).await;

        core::mem::drop(break_guard);
    }
}

impl<'d, Dm> UartTx<'d, Dm>
where
    Dm: DriverMode,
{
    /// Configures RTS pin.
    #[instability::unstable]
    pub fn with_rts(mut self, rts: impl PeripheralOutput<'d>) -> Self {
        let rts = rts.into();

        rts.apply_output_config(&OutputConfig::default());
        rts.set_output_enable(true);

        self.rts_pin = rts.connect_with_guard(self.uart.info().rts_signal);

        self
    }

    /// Assigns the TX pin for UART instance.
    ///
    /// Sets the specified pin to push-pull output and connects it to the UART
    /// TX signal.
    ///
    /// Disconnects the previous pin that was assigned with `with_tx`.
    #[instability::unstable]
    pub fn with_tx(mut self, tx: impl PeripheralOutput<'d>) -> Self {
        let tx = tx.into();

        // Make sure we don't cause an unexpected low pulse on the pin.
        tx.set_output_high(true);
        tx.apply_output_config(&OutputConfig::default());
        tx.set_output_enable(true);

        self.tx_pin = tx.connect_with_guard(self.uart.info().tx_signal);

        self
    }

    /// Changes the configuration.
    ///
    /// Do not call this function while a transmission is in progress. The function discards
    /// the data that the transmitter did not send yet, and the TX line goes low for a short
    /// time. A receiver reports that pulse as an error. Call [`Self::flush`] first, to let
    /// the transmitter send the remaining data.
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when the configuration is not supported by the hardware
    #[instability::unstable]
    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
        self.uart
            .info()
            .set_tx_fifo_empty_threshold(config.tx.fifo_empty_threshold)?;
        self.uart.info().txfifo_reset();
        Ok(())
    }

    /// Returns whether the UART buffer is ready to accept more data.
    ///
    /// If this function returns `true`, [`Self::write`] will not block.
    #[instability::unstable]
    pub fn write_ready(&self) -> bool {
        self.uart.info().tx_fifo_count() < Info::UART_FIFO_SIZE
    }

    /// Writes bytes.
    ///
    /// Writes data to the internal TX FIFO of the UART peripheral. The data is
    /// then transmitted over the UART TX line.
    ///
    /// Returns the number of bytes written to the FIFO. This may be less than the
    /// length of the provided data. Returns 0 only if the provided data is empty.
    ///
    /// # Errors
    ///
    /// [`TxError`] when an error occurred during the write operation
    #[instability::unstable]
    pub fn write(&mut self, data: &[u8]) -> Result<usize, TxError> {
        self.uart.info().write(data)
    }

    fn write_all(&mut self, mut data: &[u8]) -> Result<(), TxError> {
        while !data.is_empty() {
            let bytes_written = self.write(data)?;
            data = &data[bytes_written..];
        }
        Ok(())
    }

    /// Flushes the transmit buffer.
    ///
    /// Blocks until all data in the TX FIFO has been transmitted.
    #[instability::unstable]
    pub fn flush(&mut self) -> Result<(), TxError> {
        while self.uart.info().tx_fifo_count() > 0 {}
        self.flush_last_byte();
        Ok(())
    }

    fn flush_last_byte(&mut self) {
        // This function handles an edge case that happens when the TX FIFO count
        // changes to 0. The FSM is in the Idle state for a short while after
        // the last byte is moved out of the FIFO. It is unclear how long this
        // takes, but 10us seems to be a good enough duration to wait, for both
        // fast and slow baud rates.
        crate::rom::ets_delay_us(10);
        while !self.is_tx_idle() {}
    }

    /// Sends a break signal for a specified duration in bit time.
    ///
    /// Duration is in bits, the time it takes to transfer one bit at the
    /// current baud rate. The delay during the break is just busy-waiting.
    #[instability::unstable]
    pub fn send_break(&mut self, bits: u32) {
        // Calculate total delay in microseconds
        let total_delay_us = (bits as u64 * 1_000_000) / self.baudrate as u64;
        let delay_us = (total_delay_us as u32).max(1);

        let break_guard = self.start_break();

        crate::rom::ets_delay_us(delay_us);

        core::mem::drop(break_guard);
    }

    fn start_break(&mut self) -> impl Drop + '_ {
        // Read the current TX inversion state
        let original_conf0 = self.uart.info().regs().conf0().read();
        let original_txd_inv = original_conf0.txd_inv().bit();

        // Invert the TX line (toggle the current state)
        self.uart
            .info()
            .regs()
            .conf0()
            .modify(|_, w| w.txd_inv().bit(!original_txd_inv));

        sync_regs(self.uart.info().regs());

        // Restore the original register state when dropped.
        DropGuard::new(self, move |this| {
            this.uart
                .info()
                .regs()
                .conf0()
                .write(|w| unsafe { w.bits(original_conf0.bits()) });
            sync_regs(this.uart.info().regs());
        })
    }

    /// Returns whether the TX line is idle for this UART instance.
    ///
    /// The transmit line is idle when no data is currently being transmitted.
    fn is_tx_idle(&self) -> bool {
        self.uart.info().is_tx_idle()
    }

    /// Disables all TX-related interrupts for this UART instance.
    ///
    /// 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.regs().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.regs().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 regs(&self) -> &RegisterBlock {
        self.uart.info().regs()
    }
}

impl<'d> UartRx<'d, Blocking> {
    #[procmacros::doc_replace(
        "note" => {
            cfg(esp32) => "**esp32-specific ⚠️**: `UART2` is not recommended for use.",
            _ => ""
        }
    )]
    /// Creates a new UART RX instance in [`Blocking`] mode.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, UartRx};
    /// let rx = UartRx::new(peripherals.UART0, Config::default())?.with_rx(peripherals.GPIO2);
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when the configuration is not supported by the hardware
    #[instability::unstable]
    pub fn new(uart: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
        let (uart_rx, _) = UartBuilder::new(uart).init(config)?.split();

        Ok(uart_rx)
    }

    /// Waits for a break condition to be detected.
    ///
    /// Polls the break-detection interrupt status and returns once the receiver
    /// has detected a break condition. After detection, the break status is
    /// automatically cleared.
    #[instability::unstable]
    pub fn wait_for_break(&mut self) {
        while !self.is_break_detected() {
            // wait
        }

        self.clear_break_detected();
    }

    /// Waits for a break condition to be detected with a timeout.
    ///
    /// Polls the break-detection interrupt status until a break is detected or
    /// the specified timeout expires. Returns whether a break was detected
    /// before the timeout expired. After successful detection, the break
    /// status is automatically cleared.
    ///
    /// ## Arguments
    /// * `timeout` - Maximum time to wait for a break condition
    #[instability::unstable]
    pub fn wait_for_break_with_timeout(&mut self, timeout: crate::time::Duration) -> bool {
        let start = crate::time::Instant::now();

        while !self.is_break_detected() {
            if crate::time::Instant::now() - start >= timeout {
                return false;
            }
        }

        self.clear_break_detected();
        true
    }

    /// Reconfigures the driver to operate in [`Async`] mode.
    #[instability::unstable]
    pub fn into_async(self) -> UartRx<'d, Async> {
        if !self.uart.state().is_tx_async.load(Ordering::Acquire) {
            self.uart
                .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,
            peri_clock_guard: self.peri_clock_guard,
            _wake_lock: self._wake_lock,
            reported_errors: self.reported_errors,
        }
    }
}

impl<'d> UartRx<'d, Async> {
    /// Reconfigures the driver to operate in [`Blocking`] mode.
    #[instability::unstable]
    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.disable_peri_interrupt_on_all_cores();
        }

        UartRx {
            uart: self.uart,
            phantom: PhantomData,
            guard: self.guard,
            peri_clock_guard: self.peri_clock_guard,
            _wake_lock: self._wake_lock,
            reported_errors: self.reported_errors,
        }
    }

    async fn wait_for_buffered_data(
        &mut self,
        minimum: usize,
        max_threshold: usize,
        listen_for_timeout: bool,
    ) -> Result<(), RxError> {
        let current_threshold = self.uart.info().rx_fifo_full_threshold();

        // User preference takes priority.
        let max_threshold = max_threshold.min(current_threshold as usize) as u16;
        let minimum = minimum.min(Info::RX_FIFO_MAX_THRHD as usize) as u16;

        // The effective threshold must be >= minimum. We ensure this by lowering the minimum number
        // of returnable bytes.
        let minimum = minimum.min(max_threshold);

        // loop to prevent returning 0 bytes
        while self.uart.info().rx_fifo_count() < minimum {
            // We're ignoring the user configuration here to ensure that this is not waiting
            // for more data than the buffer. We'll restore the original value after the
            // future resolved.
            let info = self.uart.info();
            unwrap!(info.set_rx_fifo_full_threshold(max_threshold));
            let _guard = DropGuard::new((), |_| {
                unwrap!(info.set_rx_fifo_full_threshold(current_threshold));
            });

            // Wait for space or event
            let mut events = RxEvent::FifoFull
                | RxEvent::FifoOvf
                | RxEvent::FrameError
                | RxEvent::GlitchDetected
                | RxEvent::ParityError;

            if self.regs().at_cmd_char().read().char_num().bits() > 0 {
                events |= RxEvent::CmdCharDetected;
            }

            if listen_for_timeout && self.uart.info().rx_timeout_enabled() {
                events |= RxEvent::FifoTout;
            }

            let events = UartRxFuture::new(self.uart.reborrow(), events).await;

            if events.contains(RxEvent::FifoOvf) {
                self.uart.info().rxfifo_reset();
            }
            rx_event_check_for_error(events, self.reported_errors)?;
        }

        Ok(())
    }

    /// Reads data asynchronously.
    ///
    /// Reads data from the UART receive buffer into the provided buffer. If the
    /// buffer is empty, waits asynchronously for data to become available, or for
    /// an error to occur.
    ///
    /// Returns the number of bytes read into the buffer. This may be less than
    /// the length of the buffer.
    ///
    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
    /// wait for more data than the buffer can hold.
    ///
    /// Upon an error, returns immediately and the contents of the internal FIFO
    /// are not modified.
    ///
    /// # Cancellation Safety
    ///
    /// Cancellation safe.
    pub async fn read_async(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
        if buf.is_empty() {
            return Ok(0);
        }

        self.wait_for_buffered_data(1, buf.len(), true).await?;

        self.read_buffered(buf)
    }

    /// Fills buffer asynchronously.
    ///
    /// Reads data into the provided buffer. If the internal FIFO does not contain
    /// enough data, waits asynchronously for data to become available, or for an
    /// error to occur.
    ///
    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
    /// wait for more data than the buffer can hold.
    ///
    /// # Cancellation Safety
    ///
    /// **Not** cancellation safe. If the future is dropped before it resolves, or
    /// if an error occurs during the read operation, previously read data may be
    /// lost.
    pub async fn read_exact_async(&mut self, mut buf: &mut [u8]) -> Result<(), RxError> {
        if buf.is_empty() {
            return Ok(());
        }

        // Drain the buffer first, there's no point in waiting for data we've already received.
        let read = self.read_buffered(buf)?;
        buf = &mut buf[read..];

        while !buf.is_empty() {
            // No point in listening for timeouts, as we're waiting for an exact amount of
            // data. On ESP32 and S2, the timeout interrupt can't be cleared unless the FIFO
            // is empty, so listening could cause an infinite loop here.
            self.wait_for_buffered_data(buf.len(), buf.len(), false)
                .await?;

            let read = self.read_buffered(buf)?;
            buf = &mut buf[read..];
        }

        Ok(())
    }

    /// Waits for a break condition to be detected asynchronously.
    ///
    /// This is an async function that will await until a break condition is
    /// detected on the RX line. After detection, the break interrupt flag is
    /// automatically cleared.
    #[instability::unstable]
    pub async fn wait_for_break_async(&mut self) {
        UartRxFuture::new(self.uart.reborrow(), RxEvent::BreakDetected).await;
    }
}

impl<'d, Dm> UartRx<'d, Dm>
where
    Dm: DriverMode,
{
    fn regs(&self) -> &RegisterBlock {
        self.uart.info().regs()
    }

    /// Assigns the CTS pin for UART instance.
    ///
    /// Sets the specified pin to input and connects it to the UART CTS signal.
    #[instability::unstable]
    pub fn with_cts(self, cts: impl PeripheralInput<'d>) -> Self {
        let cts = cts.into();

        cts.apply_input_config(&InputConfig::default());
        cts.set_input_enable(true);

        self.uart.info().cts_signal.connect_to(&cts);

        self
    }

    /// Assigns the RX pin for UART instance.
    ///
    /// Sets the specified pin to input and connects it to the UART RX signal.
    ///
    /// When listening for the output of the UART peripheral, configure the driver
    /// side (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.
    #[instability::unstable]
    pub fn with_rx(self, rx: impl PeripheralInput<'d>) -> Self {
        let rx = rx.into();

        rx.apply_input_config(&InputConfig::default().with_pull(Pull::Up));
        rx.set_input_enable(true);

        self.uart.info().rx_signal.connect_to(&rx);

        self
    }

    /// Returns whether a break condition has been detected.
    ///
    /// The returned status is sticky and remains set until
    /// [`Self::clear_break_detected`] is called, or until one of the
    /// `wait_for_break` methods observes and clears it.
    #[instability::unstable]
    pub fn is_break_detected(&self) -> bool {
        self.uart.info().check_rx_break_detected()
    }

    /// Clears the break-detection status.
    #[instability::unstable]
    pub fn clear_break_detected(&mut self) {
        self.uart.info().clear_rx_break_detected();
    }

    /// Changes the configuration.
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when the configuration is not supported by the hardware
    #[instability::unstable]
    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
        self.uart
            .info()
            .set_rx_fifo_full_threshold(config.rx.fifo_full_threshold)?;
        self.uart
            .info()
            .set_rx_timeout(config.rx.timeout, self.uart.info().current_symbol_length())?;
        self.uart
            .info()
            .set_discard_erroneous_bytes(config.rx.discard_erroneous_bytes);
        self.reported_errors = config.rx.reported_errors;

        self.uart.info().rxfifo_reset();
        Ok(())
    }

    /// Lets activity on the RX line wake the chip from light sleep.
    ///
    /// The chip wakes when it counts the number of rising edges that
    /// [`WakeupConfig::with_rising_edges`] gives. Deep sleep powers the UART down, so this source
    /// ends a light sleep only.
    ///
    /// The chip loses the bytes that cause the wake. It also loses the bytes that arrive during the
    /// wake, and at a typical baud rate that wake is long enough to lose several bytes. A sender
    /// must therefore first send data that the receiver can lose, and then send the data again.
    /// The first data after the wake also clears the internal wakeup indication. Without that
    /// write, the next wake occurs two edges early.
    ///
    /// The peripheral counts the edges itself, so a light sleep keeps the high-performance
    /// peripherals powered instead of powering them down. This increases the sleep current.
    ///
    /// The configuration stays after the driver is dropped, so that the UART continues to wake the
    /// chip while no driver owns it. Call [`Self::disable_wakeup`] to remove it.
    ///
    /// # Errors
    ///
    /// [`WakeConfigError::NotAWakeupSource`] when this UART instance cannot wake the chip,
    /// and [`WakeConfigError::EdgeCountUnsupported`] when the hardware cannot count the requested
    /// number of edges.
    #[cfg(sleep_driver_supported)]
    #[instability::unstable]
    pub fn enable_wakeup(&mut self, config: &WakeupConfig) -> Result<(), WakeConfigError> {
        self.uart.info().enable_wakeup(config)
    }

    /// Stops the UART from waking the chip.
    #[cfg(sleep_driver_supported)]
    #[instability::unstable]
    pub fn disable_wakeup(&mut self) {
        self.uart.info().disable_wakeup();
    }

    /// Reads and clears RX error conditions set by received data.
    ///
    /// Only errors enabled in [`RxConfig::with_reported_errors`] are returned;
    /// disabled errors are cleared and ignored.
    ///
    /// If a FIFO overflow is detected, the RX FIFO is reset.
    #[instability::unstable]
    pub fn check_for_errors(&mut self) -> Result<(), RxError> {
        self.uart.info().check_for_errors(self.reported_errors)
    }

    /// Returns whether the UART buffer has data.
    ///
    /// If this function returns `true`, [`Self::read`] will not block.
    #[instability::unstable]
    pub fn read_ready(&self) -> bool {
        self.uart.info().rx_fifo_count() > 0
    }

    /// Reads bytes.
    ///
    /// The UART hardware continuously receives bytes and stores them in the RX
    /// FIFO. Reads the bytes from the RX FIFO and returns them in the provided
    /// buffer. If the hardware buffer is empty, blocks until data is available.
    /// [`Self::read_ready`] can be used to check if data is available without
    /// blocking.
    ///
    /// Returns the number of bytes read into the buffer. This may be less than
    /// the length of the buffer. Returns 0 only if the provided buffer is empty.
    ///
    /// # Errors
    ///
    /// [`RxError`] when a reported error occurred since
    /// the last call to [`Self::check_for_errors`], [`Self::read_buffered`], or
    /// this function.
    ///
    /// If the error occurred before this function was called, the contents of
    /// the FIFO are not modified.
    #[instability::unstable]
    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
        self.uart.info().read(buf, self.reported_errors)
    }

    /// Reads already received bytes.
    ///
    /// Reads the already received bytes from the FIFO into the provided buffer.
    /// Does not wait for the FIFO to actually contain any bytes.
    ///
    /// Returns the number of bytes read into the buffer. This may be less than
    /// the length of the buffer, and it may also be 0.
    ///
    /// # Errors
    ///
    /// [`RxError`] when a reported error occurred since
    /// the last call to [`Self::check_for_errors`], [`Self::read`], or this
    /// function.
    ///
    /// If the error occurred before this function was called, the contents of
    /// the FIFO are not modified.
    #[instability::unstable]
    pub fn read_buffered(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
        self.uart.info().read_buffered(buf, self.reported_errors)
    }

    /// Disables all RX-related interrupts for this UART instance.
    ///
    /// Clears and disables the `receive FIFO full` interrupt, `receive FIFO
    /// overflow`, `receive FIFO timeout`, and `AT command byte detection`
    /// interrupts.
    fn disable_rx_interrupts(&self) {
        self.regs().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.regs().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()
        });
    }
}

impl<'d> Uart<'d, Blocking> {
    #[procmacros::doc_replace(
        "note" => {
            cfg(esp32) => "**esp32-specific ⚠️**: `UART2` is not recommended for use.",
            _ => ""
        }
    )]
    /// Creates a new UART instance in [`Blocking`] mode.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_rx(peripherals.GPIO1)
    ///     .with_tx(peripherals.GPIO2);
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when the configuration is not supported by the hardware
    pub fn new(uart: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
        UartBuilder::new(uart).init(config)
    }

    /// Reconfigures the driver to operate in [`Async`] mode.
    ///
    /// See the [`Async`] documentation for an example on how to use this
    /// method.
    pub fn into_async(self) -> Uart<'d, Async> {
        Uart {
            rx: self.rx.into_async(),
            tx: self.tx.into_async(),
        }
    }

    #[cfg_attr(
        not(multi_core),
        doc = "Registers an interrupt handler for the peripheral."
    )]
    #[cfg_attr(
        multi_core,
        doc = "Registers an interrupt handler for the peripheral on the current core."
    )]
    #[doc = ""]
    /// Replaces any previously registered interrupt handlers.
    ///
    /// The default/unhandled interrupt handler can be restored with
    /// [crate::interrupt::DEFAULT_INTERRUPT_HANDLER]
    #[instability::unstable]
    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
        // `self.tx.uart` and `self.rx.uart` are the same
        self.tx.uart.set_interrupt_handler(handler);
    }

    #[procmacros::doc_replace]
    /// Listens for the given interrupts.
    ///
    /// # Examples
    ///
    /// **Note**: In practice a proper serial terminal should be used
    /// to connect to the board (espflash will not work)
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::{
    ///     delay::Delay,
    ///     uart::{AtCmdConfig, Config, RxConfig, Uart, UartInterrupt},
    /// };
    /// # let delay = Delay::new();
    /// # let config = Config::default().with_rx(
    /// #    RxConfig::default().with_fifo_full_threshold(30)
    /// # );
    /// # let mut uart = Uart::new(
    /// #    peripherals.UART0,
    /// #    config)?;
    /// uart.set_interrupt_handler(interrupt_handler);
    ///
    /// critical_section::with(|cs| {
    ///     uart.set_at_cmd(AtCmdConfig::default().with_cmd_char(b'#'));
    ///     uart.listen(UartInterrupt::AtCmd | UartInterrupt::RxFifoFull);
    ///
    ///     SERIAL.borrow_ref_mut(cs).replace(uart);
    /// });
    ///
    /// loop {
    ///     println!("Send `#` character or >=30 characters");
    ///     delay.delay(Duration::from_secs(1));
    /// }
    /// # }
    ///
    /// 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 core::fmt::Write;
    ///
    /// use esp_hal::uart::UartInterrupt;
    /// #[esp_hal::handler]
    /// fn interrupt_handler() {
    ///     critical_section::with(|cs| {
    ///         let mut serial = SERIAL.borrow_ref_mut(cs);
    ///         if let Some(serial) = serial.as_mut() {
    ///             let mut buf = [0u8; 64];
    ///             if let Ok(cnt) = serial.read_buffered(&mut buf) {
    ///                 println!("Read {} bytes", cnt);
    ///             }
    ///
    ///             let pending_interrupts = serial.interrupts();
    ///             println!(
    ///                 "Interrupt AT-CMD: {} RX-FIFO-FULL: {}",
    ///                 pending_interrupts.contains(UartInterrupt::AtCmd),
    ///                 pending_interrupts.contains(UartInterrupt::RxFifoFull),
    ///             );
    ///
    ///             serial.clear_interrupts(UartInterrupt::AtCmd | UartInterrupt::RxFifoFull);
    ///         }
    ///     });
    /// }
    /// ```
    #[instability::unstable]
    pub fn listen(&mut self, interrupts: impl Into<EnumSet<UartInterrupt>>) {
        self.tx.uart.info().enable_listen(interrupts.into(), true)
    }

    /// Unlistens from the given interrupts.
    #[instability::unstable]
    pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<UartInterrupt>>) {
        self.tx.uart.info().enable_listen(interrupts.into(), false)
    }

    /// Returns the 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)
    }

    /// Waits for a break condition to be detected.
    ///
    /// This is a blocking function that will continuously check for a break condition.
    /// After detection, the break interrupt flag is automatically cleared.
    #[instability::unstable]
    pub fn wait_for_break(&mut self) {
        self.rx.wait_for_break()
    }

    /// Waits for a break condition to be detected with a timeout.
    ///
    /// This is a blocking function that will check for a break condition up to
    /// the specified timeout. Returns whether a break was detected before the
    /// timeout expired. After successful detection, the break interrupt flag
    /// is automatically cleared.
    ///
    /// ## Arguments
    /// * `timeout` - Maximum time to wait for a break condition
    #[instability::unstable]
    pub fn wait_for_break_with_timeout(&mut self, timeout: crate::time::Duration) -> bool {
        self.rx.wait_for_break_with_timeout(timeout)
    }
}

impl<'d> Uart<'d, Async> {
    /// Reconfigures the driver to operate in [`Blocking`] mode.
    ///
    /// See the [`Blocking`] documentation for an example on how to use this
    /// method.
    pub fn into_blocking(self) -> Uart<'d, Blocking> {
        Uart {
            rx: self.rx.into_blocking(),
            tx: self.tx.into_blocking(),
        }
    }

    #[procmacros::doc_replace]
    /// Writes data into the TX buffer.
    ///
    /// Writes the provided buffer `bytes` into the UART transmit buffer. If the
    /// buffer is full, waits asynchronously for space in the buffer to become
    /// available.
    ///
    /// Returns the number of bytes written into the buffer. This may be less
    /// than the length of the buffer.
    ///
    /// Upon an error, returns immediately and the contents of the internal FIFO
    /// are not modified.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_rx(peripherals.GPIO1)
    ///     .with_tx(peripherals.GPIO2)
    ///     .into_async();
    ///
    /// const MESSAGE: &[u8] = b"Hello, world!";
    /// uart.write_async(&MESSAGE).await?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Cancellation Safety
    ///
    /// Cancellation safe.
    pub async fn write_async(&mut self, words: &[u8]) -> Result<usize, TxError> {
        self.tx.write_async(words).await
    }

    #[procmacros::doc_replace]
    /// Asynchronously flushes the UART transmit buffer.
    ///
    /// Ensures that all pending data in the transmit FIFO has been sent over the
    /// UART. If the FIFO contains data, waits for the transmission to complete
    /// before returning.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_rx(peripherals.GPIO1)
    ///     .with_tx(peripherals.GPIO2)
    ///     .into_async();
    ///
    /// const MESSAGE: &[u8] = b"Hello, world!";
    /// uart.write_async(&MESSAGE).await?;
    /// uart.flush_async().await?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Cancellation Safety
    ///
    /// Cancellation safe.
    pub async fn flush_async(&mut self) -> Result<(), TxError> {
        self.tx.flush_async().await
    }

    #[procmacros::doc_replace]
    /// Reads data asynchronously.
    ///
    /// Reads data from the UART receive buffer into the provided buffer. If the
    /// buffer is empty, waits asynchronously for data to become available, or for
    /// an error to occur.
    ///
    /// Returns the number of bytes read into the buffer. This may be less than
    /// the length of the buffer.
    ///
    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
    /// wait for more data than the buffer can hold.
    ///
    /// Upon an error, returns immediately and the contents of the internal FIFO
    /// are not modified.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_rx(peripherals.GPIO1)
    ///     .with_tx(peripherals.GPIO2)
    ///     .into_async();
    ///
    /// const MESSAGE: &[u8] = b"Hello, world!";
    /// uart.write_async(&MESSAGE).await?;
    /// uart.flush_async().await?;
    ///
    /// let mut buf = [0u8; MESSAGE.len()];
    /// uart.read_async(&mut buf[..]).await?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Cancellation Safety
    ///
    /// Cancellation safe.
    pub async fn read_async(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
        self.rx.read_async(buf).await
    }

    /// Fills buffer asynchronously.
    ///
    /// Reads data from the UART receive buffer into the provided buffer. If the
    /// buffer is empty, waits asynchronously for data to become available, or for
    /// an error to occur.
    ///
    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
    /// wait for more data than the buffer can hold.
    ///
    /// # Cancellation Safety
    ///
    /// **Not** cancellation safe. If the future is dropped before it resolves, or
    /// if an error occurs during the read operation, previously read data may be
    /// lost.
    #[instability::unstable]
    pub async fn read_exact_async(&mut self, buf: &mut [u8]) -> Result<(), RxError> {
        self.rx.read_exact_async(buf).await
    }

    /// Waits for a break condition to be detected asynchronously.
    ///
    /// This is an async function that will await until a break condition is
    /// detected on the RX line. After detection, the break interrupt flag is
    /// automatically cleared.
    #[instability::unstable]
    pub async fn wait_for_break_async(&mut self) {
        self.rx.wait_for_break_async().await
    }

    /// Sends a break signal for a specified duration in bit time.
    ///
    /// Duration is in bits, the time it takes to transfer one bit at the
    /// current baud rate.
    ///
    /// Restores the original TX line state after the break signal is sent, even if
    /// the future is cancelled.
    #[instability::unstable]
    pub async fn send_break_async<D: DelayNs>(&mut self, delay: &mut D, bits: u32) {
        self.tx.send_break_async(delay, bits).await
    }
}

/// 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 receiver has detected the configured
    /// [`Uart::set_at_cmd`] byte.
    AtCmd,

    /// The transmitter has finished sending out all data from the FIFO.
    TxDone,

    /// Break condition has been detected.
    /// Triggered when the receiver detects a NULL character (i.e. logic 0 for
    /// one NULL character transmission) after stop bits.
    RxBreakDetected,

    /// The receiver has received more data than what
    /// [`RxConfig::fifo_full_threshold`] specifies.
    RxFifoFull,

    /// The receiver has not received any data for the time
    /// [`RxConfig::with_timeout`] specifies.
    RxTimeout,
}

impl<'d, Dm> Uart<'d, Dm>
where
    Dm: DriverMode,
{
    #[procmacros::doc_replace]
    /// Assigns the RX pin for UART instance.
    ///
    /// Sets the specified pin to input and connects it to the UART RX signal.
    ///
    /// When listening for the output of the UART peripheral, configure the driver
    /// side (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.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let uart = Uart::new(peripherals.UART0, Config::default())?.with_rx(peripherals.GPIO1);
    ///
    /// # {after_snippet}
    /// ```
    pub fn with_rx(mut self, rx: impl PeripheralInput<'d>) -> Self {
        self.rx = self.rx.with_rx(rx);
        self
    }

    #[procmacros::doc_replace]
    /// Assigns the TX pin for UART instance.
    ///
    /// Sets the specified pin to push-pull output and connects it to the UART
    /// TX signal.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let uart = Uart::new(peripherals.UART0, Config::default())?.with_tx(peripherals.GPIO2);
    ///
    /// # {after_snippet}
    /// ```
    pub fn with_tx(mut self, tx: impl PeripheralOutput<'d>) -> Self {
        self.tx = self.tx.with_tx(tx);
        self
    }

    #[procmacros::doc_replace]
    /// Configures CTS pin.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_rx(peripherals.GPIO1)
    ///     .with_cts(peripherals.GPIO3);
    ///
    /// # {after_snippet}
    /// ```
    pub fn with_cts(mut self, cts: impl PeripheralInput<'d>) -> Self {
        self.rx = self.rx.with_cts(cts);
        self
    }

    #[procmacros::doc_replace]
    /// Configures RTS pin.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_tx(peripherals.GPIO2)
    ///     .with_rts(peripherals.GPIO3);
    ///
    /// # {after_snippet}
    /// ```
    pub fn with_rts(mut self, rts: impl PeripheralOutput<'d>) -> Self {
        self.tx = self.tx.with_rts(rts);
        self
    }

    fn regs(&self) -> &RegisterBlock {
        // `self.tx.uart` and `self.rx.uart` are the same
        self.tx.uart.info().regs()
    }

    #[procmacros::doc_replace]
    /// Returns whether the UART TX buffer is ready to accept more data.
    ///
    /// If this function returns `true`, [`Self::write`] and [`Self::write_async`]
    /// will not block. Otherwise, the functions will not return until the buffer is
    /// ready.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
    ///
    /// if uart.write_ready() {
    ///     // Because write_ready has returned true, the following call will immediately
    ///     // copy some bytes into the FIFO and return a non-zero value.
    ///     let written = uart.write(b"Hello")?;
    ///     // ... handle written bytes
    /// } else {
    ///     // Calling write would have blocked, but here we can do something useful
    ///     // instead of waiting for the buffer to become ready.
    /// }
    /// # {after_snippet}
    /// ```
    pub fn write_ready(&self) -> bool {
        self.tx.write_ready()
    }

    #[procmacros::doc_replace]
    /// Writes bytes.
    ///
    /// Writes data to the internal TX FIFO of the UART peripheral. The data is
    /// then transmitted over the UART TX line.
    ///
    /// Returns the number of bytes written to the FIFO. This may be less than the
    /// length of the provided data. Returns 0 only if the provided data is empty.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
    ///
    /// const MESSAGE: &[u8] = b"Hello, world!";
    /// uart.write(&MESSAGE)?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`TxError`] when an error occurred during the write operation
    pub fn write(&mut self, data: &[u8]) -> Result<usize, TxError> {
        self.tx.write(data)
    }

    #[procmacros::doc_replace]
    /// Flushes the transmit buffer of the UART.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
    ///
    /// const MESSAGE: &[u8] = b"Hello, world!";
    /// uart.write(&MESSAGE)?;
    /// uart.flush()?;
    /// # {after_snippet}
    /// ```
    pub fn flush(&mut self) -> Result<(), TxError> {
        self.tx.flush()
    }

    /// Sends a break signal for a specified duration.
    #[instability::unstable]
    pub fn send_break(&mut self, bits: u32) {
        self.tx.send_break(bits)
    }

    #[procmacros::doc_replace]
    /// Returns whether the UART receive buffer has at least one byte of data.
    ///
    /// If this function returns `true`, [`Self::read`] and [`Self::read_async`]
    /// will not block. Otherwise, they will not return until data is available.
    ///
    /// Data that does not get stored due to an error will be lost and does not count
    /// towards the number of bytes in the receive buffer.
    // TODO: once we add support for UART_ERR_WR_MASK it needs to be documented here.
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
    ///
    /// while !uart.read_ready() {
    ///     // Do something else while waiting for data to be available.
    /// }
    ///
    /// let mut buf = [0u8; 32];
    /// uart.read(&mut buf[..])?;
    ///
    /// # {after_snippet}
    /// ```
    pub fn read_ready(&self) -> bool {
        self.rx.read_ready()
    }

    /// Returns whether a break condition has been detected.
    ///
    /// The returned status is sticky and remains set until
    /// [`Self::clear_break_detected`] is called, or until one of the
    /// `wait_for_break` methods observes and clears it.
    #[instability::unstable]
    pub fn is_break_detected(&self) -> bool {
        self.rx.is_break_detected()
    }

    /// Clears the break-detection status.
    #[instability::unstable]
    pub fn clear_break_detected(&mut self) {
        self.rx.clear_break_detected();
    }

    #[procmacros::doc_replace]
    /// Reads received bytes.
    ///
    /// The UART hardware continuously receives bytes and stores them in the RX
    /// FIFO. Reads the bytes from the RX FIFO and returns them in the provided
    /// buffer. If the hardware buffer is empty, blocks until data is available.
    /// [`Self::read_ready`] can be used to check if data is available without
    /// blocking.
    ///
    /// Returns the number of bytes read into the buffer. This may be less than
    /// the length of the buffer. Returns 0 only if the provided buffer is empty.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
    ///
    /// const MESSAGE: &[u8] = b"Hello, world!";
    /// uart.write(&MESSAGE)?;
    /// uart.flush()?;
    ///
    /// let mut buf = [0u8; MESSAGE.len()];
    /// uart.read(&mut buf[..])?;
    ///
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`RxError`] when a reported error occurred since
    /// the last check for errors.
    ///
    /// If the error occurred before this function was called, the contents of
    /// the FIFO are not modified.
    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
        self.rx.read(buf)
    }

    #[procmacros::doc_replace]
    /// Changes the configuration.
    ///
    /// Do not call this function while a transmission is in progress. The function discards
    /// the data that the transmitter did not send yet, and the TX line goes low for a short
    /// time. A receiver reports that pulse as an error. Call [`Self::flush`] first, to let
    /// the transmitter send the remaining data.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
    ///
    /// uart.apply_config(&Config::default().with_baudrate(19_200))?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when the configuration is not supported by the hardware
    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
        // Must apply the common settings first, as `rx.apply_config` reads back symbol
        // size.
        self.rx.uart.info().apply_config(config)?;

        self.rx.apply_config(config)?;
        self.tx.apply_config(config)?;
        Ok(())
    }

    /// Lets activity on the RX line wake the chip from light sleep.
    ///
    /// See [`UartRx::enable_wakeup`].
    ///
    /// # Errors
    ///
    /// [`WakeConfigError::NotAWakeupSource`] when this UART instance cannot wake the chip,
    /// and [`WakeConfigError::EdgeCountUnsupported`] when the hardware cannot count the requested
    /// number of edges.
    #[cfg(sleep_driver_supported)]
    #[instability::unstable]
    pub fn enable_wakeup(&mut self, config: &WakeupConfig) -> Result<(), WakeConfigError> {
        self.rx.enable_wakeup(config)
    }

    /// Stops the UART from waking the chip.
    #[cfg(sleep_driver_supported)]
    #[instability::unstable]
    pub fn disable_wakeup(&mut self) {
        self.rx.disable_wakeup();
    }

    #[procmacros::doc_replace]
    /// Splits the UART into a transmitter and receiver.
    ///
    /// This is particularly useful when having two tasks correlating to
    /// transmitting and receiving.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_rx(peripherals.GPIO1)
    ///     .with_tx(peripherals.GPIO2);
    ///
    /// // The UART can be split into separate Transmit and Receive components:
    /// let (mut rx, mut tx) = uart.split();
    ///
    /// // Each component can be used individually to interact with the UART:
    /// tx.write(&[42u8])?;
    /// let mut byte = [0u8; 1];
    /// rx.read(&mut byte);
    /// # {after_snippet}
    /// ```
    #[instability::unstable]
    pub fn split(self) -> (UartRx<'d, Dm>, UartTx<'d, Dm>) {
        (self.rx, self.tx)
    }

    #[procmacros::doc_replace]
    /// Borrows the UART as separate transmitter and receiver halves.
    ///
    /// Unlike [`split`], this method does not consume the UART. The returned
    /// transmitter and receiver are borrowed from the original UART, which can
    /// be used again after those borrows end.
    ///
    /// This is particularly useful when running separate transmit and receive
    /// futures concurrently.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::uart::{Config, Uart};
    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
    ///     .with_rx(peripherals.GPIO1)
    ///     .with_tx(peripherals.GPIO2);
    ///
    /// loop {
    ///     // The UART can be split into separate Transmit and Receive components:
    ///     let (rx, tx) = uart.split_mut();
    ///
    ///     // Each component can be used individually to interact with the UART:
    ///     tx.write(&[42u8])?;
    ///     let mut byte = [0u8; 1];
    ///     rx.read(&mut byte);
    /// }
    /// # {after_snippet}
    /// ```
    #[instability::unstable]
    pub fn split_mut(&mut self) -> (&mut UartRx<'d, Dm>, &mut UartTx<'d, Dm>) {
        (&mut self.rx, &mut self.tx)
    }

    /// Reads and clears RX error conditions set by received data.
    ///
    /// Only errors enabled in [`RxConfig::with_reported_errors`] are returned;
    /// disabled errors are cleared and ignored.
    #[instability::unstable]
    pub fn check_for_rx_errors(&mut self) -> Result<(), RxError> {
        self.rx.check_for_errors()
    }

    /// Reads already received bytes.
    ///
    /// Reads the already received bytes from the FIFO into the provided buffer.
    /// Does not wait for the FIFO to actually contain any bytes.
    ///
    /// Returns the number of bytes read into the buffer. This may be less than
    /// the length of the buffer, and it may also be 0.
    ///
    /// # Errors
    ///
    /// [`RxError`] when a reported error occurred since
    /// the last check for errors.
    ///
    /// If the error occurred before this function was called, the contents of
    /// the FIFO are not modified.
    #[instability::unstable]
    pub fn read_buffered(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
        self.rx.read_buffered(buf)
    }

    /// Configures the AT-CMD detection settings.
    #[instability::unstable]
    pub fn set_at_cmd(&mut self, config: AtCmdConfig) {
        #[cfg(uart_has_sclk_enable)]
        self.rx.uart.info().set_at_cmd_clock_enabled(false);

        self.regs().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 {
            self.regs()
                .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 {
            self.regs()
                .at_cmd_postcnt()
                .write(|w| unsafe { w.post_idle_num().bits(post_idle_count as _) });
        }

        if let Some(gap_timeout) = config.gap_timeout {
            self.regs()
                .at_cmd_gaptout()
                .write(|w| unsafe { w.rx_gap_tout().bits(gap_timeout as _) });
        }

        #[cfg(uart_has_sclk_enable)]
        self.rx.uart.info().set_at_cmd_clock_enabled(true);

        sync_regs(self.regs());
    }

    #[inline(always)]
    fn init(&mut self, config: Config) -> Result<(), ConfigError> {
        self.rx.disable_rx_interrupts();
        self.tx.disable_tx_interrupts();

        enable_register_sync(self.regs());

        // Applying config also resets Tx/Rx FIFOs
        self.apply_config(&config)?;

        // Don't wait after transmissions by default,
        // so that bytes written to TX FIFO are always immediately transmitted.
        self.regs()
            .idle_conf()
            .modify(|_, w| unsafe { w.tx_idle_num().bits(0) });
        // `idle_conf` is a sync register.
        sync_regs(self.regs());

        crate::rom::ets_delay_us(15);

        // Make sure we are starting in a "clean state" - previous operations might have
        // run into error conditions
        self.regs().int_clr().write(|w| unsafe { w.bits(u32::MAX) });

        Ok(())
    }
}

/// UART Tx or Rx Error.
#[instability::unstable]
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum IoError {
    /// UART TX error.
    Tx(TxError),
    /// UART RX error.
    Rx(RxError),
}

#[instability::unstable]
impl core::error::Error for IoError {}

#[instability::unstable]
impl core::fmt::Display for IoError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            IoError::Tx(e) => e.fmt(f),
            IoError::Rx(e) => e.fmt(f),
        }
    }
}

#[instability::unstable]
impl From<RxError> for IoError {
    fn from(e: RxError) -> Self {
        IoError::Rx(e)
    }
}

#[instability::unstable]
impl From<TxError> for IoError {
    fn from(e: TxError) -> Self {
        IoError::Tx(e)
    }
}