esp_hal/gpio/mod.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
//! # General Purpose Input/Output (GPIO)
//!
//! ## Overview
//!
//! Each pin can be used as a general-purpose I/O, or be connected to one or
//! more internal peripheral signals.
#![cfg_attr(
soc_etm,
doc = "The GPIO pins also provide tasks and events via the ETM interconnect system. For more information, see the [etm] module."
)]
#![doc = ""]
//! ## Working with pins
//!
//! After initializing the HAL, you can access the individual pins using the
//! [`crate::Peripherals`] struct. These pins can then be used as general
//! purpose digital IO using pin drivers, or they can be passed to peripherals
//! (such as SPI, UART, I2C, etc.), or can be [`GpioPin::split`]
//! into peripheral signals for advanced use.
//!
//! Pin drivers can be created using [`Flex::new`], [`Input::new`],
//! [`Output::new`] and [`OutputOpenDrain::new`]. If you need the pin drivers to
//! carry the type of the pin, you can use the [`Flex::new_typed`],
//! [`Input::new_typed`], [`Output::new_typed`], and
//! [`OutputOpenDrain::new_typed`] functions.
//!
//! Each pin is a different type initially. Internally, `esp-hal` will often
//! erase their types automatically, but they can also be converted into
//! [`AnyPin`] manually by calling [`Pin::degrade`].
//!
//! The [`Io`] struct can also be used to configure the interrupt handler for
//! GPIO interrupts. For more information, see the
//! [`Io::set_interrupt_handler`].
//!
//! ## GPIO interconnect
//!
//! Sometimes you may want to connect peripherals together without using
//! external hardware. The [`interconnect`] module provides tools to achieve
//! this using GPIO pins.
//!
//! To obtain peripheral signals, use the [`GpioPin::split`] method to split a
//! pin into an input and output signal. Alternatively, you may use
//! [`Flex::split`], [`Flex::into_peripheral_output`],
//! [`Flex::peripheral_input`], and similar methods to split a pin driver into
//! an input and output signal. You can then pass these signals to the
//! peripheral drivers similar to how you would pass a pin.
//!
//! ### GPIO interconnect example
//!
//! See the [Inverting TX and RX Pins] example of the UART documentation.
//!
//! [embedded-hal]: https://docs.rs/embedded-hal/latest/embedded_hal/
//! [Inverting TX and RX Pins]: crate::uart#inverting-rx-and-tx-pins
use portable_atomic::{AtomicPtr, Ordering};
use procmacros::ram;
#[cfg(any(lp_io, rtc_cntl))]
use crate::peripherals::gpio::{handle_rtcio, handle_rtcio_with_resistors};
pub use crate::soc::gpio::*;
use crate::{
interrupt::{self, InterruptHandler, Priority},
peripheral::{Peripheral, PeripheralRef},
peripherals::{
gpio::{handle_gpio_input, handle_gpio_output, AnyPinInner},
Interrupt,
GPIO,
IO_MUX,
},
private::{self, Sealed},
InterruptConfigurable,
DEFAULT_INTERRUPT_HANDLER,
};
pub mod interconnect;
mod placeholder;
pub use placeholder::NoPin;
#[cfg(soc_etm)]
pub mod etm;
#[cfg(lp_io)]
pub mod lp_io;
#[cfg(all(rtc_io, not(esp32)))]
pub mod rtc_io;
/// Convenience constant for `Option::None` pin
static USER_INTERRUPT_HANDLER: CFnPtr = CFnPtr::new();
struct CFnPtr(AtomicPtr<()>);
impl CFnPtr {
pub const fn new() -> Self {
Self(AtomicPtr::new(core::ptr::null_mut()))
}
pub fn store(&self, f: extern "C" fn()) {
self.0.store(f as *mut (), Ordering::Relaxed);
}
pub fn call(&self) {
let ptr = self.0.load(Ordering::Relaxed);
if !ptr.is_null() {
unsafe { (core::mem::transmute::<*mut (), extern "C" fn()>(ptr))() };
}
}
}
/// Event used to trigger interrupts.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Event {
/// Interrupts trigger on rising pin edge.
RisingEdge = 1,
/// Interrupts trigger on falling pin edge.
FallingEdge = 2,
/// Interrupts trigger on either rising or falling pin edges.
AnyEdge = 3,
/// Interrupts trigger on low level
LowLevel = 4,
/// Interrupts trigger on high level
HighLevel = 5,
}
impl From<WakeEvent> for Event {
fn from(value: WakeEvent) -> Self {
match value {
WakeEvent::LowLevel => Event::LowLevel,
WakeEvent::HighLevel => Event::HighLevel,
}
}
}
/// Event used to wake up from light sleep.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum WakeEvent {
/// Wake on low level
LowLevel = 4,
/// Wake on high level
HighLevel = 5,
}
/// Digital input or output level.
///
/// `Level` can be used to control a GPIO output, and it can act as a peripheral
/// signal and be connected to peripheral inputs and outputs.
///
/// When connected to a peripheral
/// input, the peripheral will read the corresponding level from that signal.
///
/// When connected to a peripheral output, the level will be ignored.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Level {
/// Low
Low,
/// High
High,
}
impl Sealed for Level {}
impl core::ops::Not for Level {
type Output = Self;
fn not(self) -> Self {
match self {
Self::Low => Self::High,
Self::High => Self::Low,
}
}
}
impl From<bool> for Level {
fn from(val: bool) -> Self {
match val {
true => Self::High,
false => Self::Low,
}
}
}
impl From<Level> for bool {
fn from(level: Level) -> bool {
match level {
Level::Low => false,
Level::High => true,
}
}
}
/// Pull setting for an input.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Pull {
/// No pull
None,
/// Pull up
Up,
/// Pull down
Down,
}
/// Drive strength (values are approximates)
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DriveStrength {
/// Drive strength of approximately 5mA.
I5mA = 0,
/// Drive strength of approximately 10mA.
I10mA = 1,
/// Drive strength of approximately 20mA.
I20mA = 2,
/// Drive strength of approximately 40mA.
I40mA = 3,
}
/// Alternate functions
///
/// GPIO pins can be configured for various functions, such as GPIO
/// or being directly connected to a peripheral's signal like UART, SPI, etc.
/// The `AlternateFunction` enum allows selecting one of several functions that
/// a pin can perform, rather than using it as a general-purpose input or
/// output.
///
/// The different variants correspond to different functionality depending on
/// the chip and the specific pin. For more information, refer to your chip's
#[doc = crate::trm_markdown_link!("iomuxgpio")]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AlternateFunction {
/// Alternate function 0.
Function0 = 0,
/// Alternate function 1.
Function1 = 1,
/// Alternate function 2.
Function2 = 2,
/// Alternate function 3.
Function3 = 3,
/// Alternate function 4.
Function4 = 4,
/// Alternate function 5.
Function5 = 5,
}
impl TryFrom<usize> for AlternateFunction {
type Error = ();
fn try_from(value: usize) -> Result<Self, Self::Error> {
match value {
0 => Ok(AlternateFunction::Function0),
1 => Ok(AlternateFunction::Function1),
2 => Ok(AlternateFunction::Function2),
3 => Ok(AlternateFunction::Function3),
4 => Ok(AlternateFunction::Function4),
5 => Ok(AlternateFunction::Function5),
_ => Err(()),
}
}
}
/// RTC function
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RtcFunction {
/// RTC mode.
Rtc = 0,
/// Digital mode.
Digital = 1,
}
/// Trait implemented by RTC pins
pub trait RtcPin: Pin {
/// RTC number of the pin
#[cfg(xtensa)]
fn rtc_number(&self) -> u8;
/// Configure the pin
#[cfg(any(xtensa, esp32c6))]
fn rtc_set_config(&mut self, input_enable: bool, mux: bool, func: RtcFunction);
/// Enable or disable PAD_HOLD
fn rtcio_pad_hold(&mut self, enable: bool);
/// # Safety
///
/// The `level` argument needs to be a valid setting for the
/// `rtc_cntl.gpio_wakeup.gpio_pinX_int_type`.
#[cfg(any(esp32c3, esp32c2, esp32c6))]
unsafe fn apply_wakeup(&mut self, wakeup: bool, level: u8);
}
/// Trait implemented by RTC pins which supporting internal pull-up / pull-down
/// resistors.
pub trait RtcPinWithResistors: RtcPin {
/// Enable/disable the internal pull-up resistor
fn rtcio_pullup(&mut self, enable: bool);
/// Enable/disable the internal pull-down resistor
fn rtcio_pulldown(&mut self, enable: bool);
}
/// Common trait implemented by pins
pub trait Pin: Sealed {
/// GPIO number
fn number(&self) -> u8;
#[doc(hidden)]
fn mask(&self) -> u32 {
1 << (self.number() % 32)
}
/// Type-erase (degrade) this pin into an [`AnyPin`].
///
/// This converts pin singletons (`GpioPin<0>`, …), which are all different
/// types, into the same type. It is useful for creating arrays of pins,
/// or avoiding generics.
///
/// ## Example
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// use esp_hal::gpio::{AnyPin, Pin, Output, Level};
/// use esp_hal::delay::Delay;
///
/// fn toggle_pins(pins: [AnyPin; 2], delay: &mut Delay) {
/// let [red, blue] = pins;
/// let mut red = Output::new(red, Level::High);
/// let mut blue = Output::new(blue, Level::Low);
///
/// loop {
/// red.toggle();
/// blue.toggle();
/// delay.delay_millis(500);
/// }
/// }
///
/// let pins: [AnyPin; 2] = [
/// peripherals.GPIO5.degrade(),
/// peripherals.GPIO6.degrade(),
/// ];
///
/// let mut delay = Delay::new();
/// toggle_pins(pins, &mut delay);
/// # }
/// ```
fn degrade(self) -> AnyPin
where
Self: Sized,
{
self.degrade_pin(private::Internal)
}
#[doc(hidden)]
fn degrade_pin(&self, _: private::Internal) -> AnyPin;
/// Enable/disable sleep-mode
#[doc(hidden)]
fn sleep_mode(&mut self, on: bool, _: private::Internal) {
io_mux_reg(self.number()).modify(|_, w| w.slp_sel().bit(on));
}
/// Configure the alternate function
#[doc(hidden)]
fn set_alternate_function(&mut self, alternate: AlternateFunction, _: private::Internal) {
io_mux_reg(self.number()).modify(|_, w| unsafe { w.mcu_sel().bits(alternate as u8) });
}
/// Enable or disable the GPIO pin output buffer.
#[doc(hidden)]
fn enable_output(&self, enable: bool, _: private::Internal) {
self.gpio_bank(private::Internal)
.write_out_en(self.mask(), enable);
}
/// Enable input for the pin
#[doc(hidden)]
fn enable_input(&mut self, on: bool, _: private::Internal) {
io_mux_reg(self.number()).modify(|_, w| w.fun_ie().bit(on));
}
#[doc(hidden)]
fn output_signals(&self, _: private::Internal) -> &[(AlternateFunction, OutputSignal)];
#[doc(hidden)]
fn input_signals(&self, _: private::Internal) -> &[(AlternateFunction, InputSignal)];
#[doc(hidden)]
fn gpio_bank(&self, _: private::Internal) -> GpioRegisterAccess;
#[doc(hidden)]
fn pull_direction(&self, pull: Pull, _: private::Internal) {
let pull_up = pull == Pull::Up;
let pull_down = pull == Pull::Down;
#[cfg(esp32)]
crate::soc::gpio::errata36(self.degrade_pin(private::Internal), pull_up, pull_down);
io_mux_reg(self.number()).modify(|_, w| {
w.fun_wpd().bit(pull_down);
w.fun_wpu().bit(pull_up)
});
}
}
/// Trait implemented by pins which can be used as inputs.
pub trait InputPin: Pin + Into<AnyPin> + 'static {
/// Init as input with the given pull-up/pull-down
#[doc(hidden)]
fn init_input(&self, pull: Pull, _: private::Internal) {
self.pull_direction(pull, private::Internal);
#[cfg(usb_device)]
disable_usb_pads(self.number());
io_mux_reg(self.number()).modify(|_, w| unsafe {
w.mcu_sel().bits(GPIO_FUNCTION as u8);
w.fun_ie().set_bit();
w.slp_sel().clear_bit()
});
}
/// The current state of the input
#[doc(hidden)]
fn is_input_high(&self, _: private::Internal) -> bool {
self.gpio_bank(private::Internal).read_input() & self.mask() != 0
}
}
/// Trait implemented by pins which can be used as outputs.
pub trait OutputPin: Pin + Into<AnyPin> + 'static {
/// Set up as output
#[doc(hidden)]
fn init_output(
&mut self,
alternate: AlternateFunction,
open_drain: bool,
input_enable: Option<bool>,
_: private::Internal,
) {
self.enable_output(true, private::Internal);
let gpio = unsafe { GPIO::steal() };
gpio.pin(self.number() as usize)
.modify(|_, w| w.pad_driver().bit(open_drain));
gpio.func_out_sel_cfg(self.number() as usize)
.modify(|_, w| unsafe { w.out_sel().bits(OutputSignal::GPIO as OutputSignalType) });
#[cfg(any(esp32c3, esp32s3))]
disable_usb_pads(self.number());
io_mux_reg(self.number()).modify(|_, w| unsafe {
w.mcu_sel().bits(alternate as u8);
if let Some(input_enable) = input_enable {
w.fun_ie().bit(input_enable);
}
w.fun_drv().bits(DriveStrength::I20mA as u8);
w.slp_sel().clear_bit()
});
}
/// Configure open-drain mode
#[doc(hidden)]
fn set_to_open_drain_output(&mut self, _: private::Internal) {
self.init_output(GPIO_FUNCTION, true, Some(true), private::Internal);
}
/// Configure output mode
#[doc(hidden)]
fn set_to_push_pull_output(&mut self, _: private::Internal) {
self.init_output(GPIO_FUNCTION, false, None, private::Internal);
}
/// Set the pin's level to high or low
#[doc(hidden)]
fn set_output_high(&mut self, high: bool, _: private::Internal) {
self.gpio_bank(private::Internal)
.write_output(self.mask(), high);
}
/// Configure the [DriveStrength] of the pin
#[doc(hidden)]
fn set_drive_strength(&mut self, strength: DriveStrength, _: private::Internal) {
io_mux_reg(self.number()).modify(|_, w| unsafe { w.fun_drv().bits(strength as u8) });
}
/// Enable/disable open-drain mode
#[doc(hidden)]
fn enable_open_drain(&mut self, on: bool, _: private::Internal) {
unsafe { GPIO::steal() }
.pin(self.number() as usize)
.modify(|_, w| w.pad_driver().bit(on));
}
/// Configure internal pull-up resistor in sleep mode
#[doc(hidden)]
fn internal_pull_up_in_sleep_mode(&mut self, on: bool, _: private::Internal) {
io_mux_reg(self.number()).modify(|_, w| w.mcu_wpu().bit(on));
}
/// Configure internal pull-down resistor in sleep mode
#[doc(hidden)]
fn internal_pull_down_in_sleep_mode(&mut self, on: bool, _: private::Internal) {
io_mux_reg(self.number()).modify(|_, w| w.mcu_wpd().bit(on));
}
/// Is the output set to high
#[doc(hidden)]
fn is_set_high(&self, _: private::Internal) -> bool {
self.gpio_bank(private::Internal).read_output() & self.mask() != 0
}
}
/// Trait implemented by pins which can be used as analog pins
pub trait AnalogPin: Pin {
/// Configure the pin for analog operation
#[doc(hidden)]
fn set_analog(&self, _: private::Internal);
}
/// Trait implemented by pins which can be used as Touchpad pins
pub trait TouchPin: Pin {
/// Configure the pin for analog operation
#[doc(hidden)]
fn set_touch(&self, _: private::Internal);
/// Reads the pin's touch measurement register
#[doc(hidden)]
fn touch_measurement(&self, _: private::Internal) -> u16;
/// Maps the pin nr to the touch pad nr
#[doc(hidden)]
fn touch_nr(&self, _: private::Internal) -> u8;
/// Set a pins touch threshold for interrupts.
#[doc(hidden)]
fn set_threshold(&self, threshold: u16, _: private::Internal);
}
#[doc(hidden)]
#[derive(Clone, Copy)]
pub enum GpioRegisterAccess {
Bank0,
#[cfg(any(esp32, esp32s2, esp32s3))]
Bank1,
}
impl From<usize> for GpioRegisterAccess {
fn from(_gpio_num: usize) -> Self {
#[cfg(any(esp32, esp32s2, esp32s3))]
if _gpio_num >= 32 {
return GpioRegisterAccess::Bank1;
}
GpioRegisterAccess::Bank0
}
}
impl GpioRegisterAccess {
fn write_out_en(self, word: u32, enable: bool) {
if enable {
self.write_out_en_set(word);
} else {
self.write_out_en_clear(word);
}
}
fn write_out_en_clear(self, word: u32) {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::write_out_en_clear(word),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::write_out_en_clear(word),
}
}
fn write_out_en_set(self, word: u32) {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::write_out_en_set(word),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::write_out_en_set(word),
}
}
fn read_input(self) -> u32 {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::read_input(),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::read_input(),
}
}
fn read_output(self) -> u32 {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::read_output(),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::read_output(),
}
}
fn read_interrupt_status(self) -> u32 {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::read_interrupt_status(),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::read_interrupt_status(),
}
}
fn write_interrupt_status_clear(self, word: u32) {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::write_interrupt_status_clear(word),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::write_interrupt_status_clear(word),
}
}
fn write_output(self, word: u32, set: bool) {
if set {
self.write_output_set(word);
} else {
self.write_output_clear(word);
}
}
fn write_output_set(self, word: u32) {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::write_output_set(word),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::write_output_set(word),
}
}
fn write_output_clear(self, word: u32) {
match self {
Self::Bank0 => Bank0GpioRegisterAccess::write_output_clear(word),
#[cfg(any(esp32, esp32s2, esp32s3))]
Self::Bank1 => Bank1GpioRegisterAccess::write_output_clear(word),
}
}
}
struct Bank0GpioRegisterAccess;
impl Bank0GpioRegisterAccess {
fn write_out_en_clear(word: u32) {
unsafe { GPIO::steal() }
.enable_w1tc()
.write(|w| unsafe { w.bits(word) });
}
fn write_out_en_set(word: u32) {
unsafe { GPIO::steal() }
.enable_w1ts()
.write(|w| unsafe { w.bits(word) });
}
fn read_input() -> u32 {
unsafe { GPIO::steal() }.in_().read().bits()
}
fn read_output() -> u32 {
unsafe { GPIO::steal() }.out().read().bits()
}
fn read_interrupt_status() -> u32 {
unsafe { GPIO::steal() }.status().read().bits()
}
fn write_interrupt_status_clear(word: u32) {
unsafe { GPIO::steal() }
.status_w1tc()
.write(|w| unsafe { w.bits(word) });
}
fn write_output_set(word: u32) {
unsafe { GPIO::steal() }
.out_w1ts()
.write(|w| unsafe { w.bits(word) });
}
fn write_output_clear(word: u32) {
unsafe { GPIO::steal() }
.out_w1tc()
.write(|w| unsafe { w.bits(word) });
}
}
#[cfg(any(esp32, esp32s2, esp32s3))]
struct Bank1GpioRegisterAccess;
#[cfg(any(esp32, esp32s2, esp32s3))]
impl Bank1GpioRegisterAccess {
fn write_out_en_clear(word: u32) {
unsafe { GPIO::steal() }
.enable1_w1tc()
.write(|w| unsafe { w.bits(word) });
}
fn write_out_en_set(word: u32) {
unsafe { GPIO::steal() }
.enable1_w1ts()
.write(|w| unsafe { w.bits(word) });
}
fn read_input() -> u32 {
unsafe { GPIO::steal() }.in1().read().bits()
}
fn read_output() -> u32 {
unsafe { GPIO::steal() }.out1().read().bits()
}
fn read_interrupt_status() -> u32 {
unsafe { GPIO::steal() }.status1().read().bits()
}
fn write_interrupt_status_clear(word: u32) {
unsafe { GPIO::steal() }
.status1_w1tc()
.write(|w| unsafe { w.bits(word) });
}
fn write_output_set(word: u32) {
unsafe { GPIO::steal() }
.out1_w1ts()
.write(|w| unsafe { w.bits(word) });
}
fn write_output_clear(word: u32) {
unsafe { GPIO::steal() }
.out1_w1tc()
.write(|w| unsafe { w.bits(word) });
}
}
/// GPIO pin
pub struct GpioPin<const GPIONUM: u8>;
/// Type-erased GPIO pin
pub struct AnyPin(pub(crate) AnyPinInner);
impl<const GPIONUM: u8> GpioPin<GPIONUM>
where
Self: Pin,
{
/// Create a pin out of thin air.
///
/// # Safety
///
/// Ensure that only one instance of a pin exists at one time.
pub unsafe fn steal() -> Self {
Self
}
/// Split the pin into an input and output signal.
///
/// Peripheral signals allow connecting peripherals together without using
/// external hardware.
pub fn split(self) -> (interconnect::InputSignal, interconnect::OutputSignal) {
(
interconnect::InputSignal::new(self.degrade_pin(private::Internal)),
interconnect::OutputSignal::new(self.degrade_pin(private::Internal)),
)
}
}
/// Workaround to make D+ and D- work on the ESP32-C3 and ESP32-S3, which by
/// default are assigned to the `USB_SERIAL_JTAG` peripheral.
#[cfg(usb_device)]
fn disable_usb_pads(gpionum: u8) {
cfg_if::cfg_if! {
if #[cfg(esp32c3)] {
let pins = [18, 19];
} else if #[cfg(esp32c6)] {
let pins = [12, 13];
} else if #[cfg(esp32h2)] {
let pins = [26, 27];
} else if #[cfg(esp32s3)] {
let pins = [19, 20];
} else {
compile_error!("Please define USB pins for this chip");
}
}
if pins.contains(&gpionum) {
unsafe { crate::peripherals::USB_DEVICE::steal() }
.conf0()
.modify(|_, w| {
w.usb_pad_enable().clear_bit();
w.dm_pullup().clear_bit();
w.dm_pulldown().clear_bit();
w.dp_pullup().clear_bit();
w.dp_pulldown().clear_bit()
});
}
}
impl<const GPIONUM: u8> Peripheral for GpioPin<GPIONUM>
where
Self: Pin,
{
type P = GpioPin<GPIONUM>;
unsafe fn clone_unchecked(&self) -> Self::P {
core::ptr::read(self as *const _)
}
}
impl<const GPIONUM: u8> private::Sealed for GpioPin<GPIONUM> {}
pub(crate) fn bind_default_interrupt_handler() {
// We first check if a handler is set in the vector table.
if let Some(handler) = interrupt::bound_handler(Interrupt::GPIO) {
let handler = handler as *const unsafe extern "C" fn();
// We only allow binding the default handler if nothing else is bound.
// This prevents silently overwriting RTIC's interrupt handler, if using GPIO.
if !core::ptr::eq(handler, DEFAULT_INTERRUPT_HANDLER.handler() as _) {
// The user has configured an interrupt handler they wish to use.
info!("Not using default GPIO interrupt handler: already bound in vector table");
return;
}
}
// The vector table doesn't contain a custom entry.Still, the
// peripheral interrupt may already be bound to something else.
if interrupt::bound_cpu_interrupt_for(crate::Cpu::current(), Interrupt::GPIO).is_some() {
info!("Not using default GPIO interrupt handler: peripheral interrupt already in use");
return;
}
unsafe { interrupt::bind_interrupt(Interrupt::GPIO, default_gpio_interrupt_handler) };
// By default, we use lowest priority
unwrap!(interrupt::enable(Interrupt::GPIO, Priority::min()));
}
/// General Purpose Input/Output driver
pub struct Io {
_io_mux: IO_MUX,
}
impl Io {
/// Initialize the I/O driver.
pub fn new(_io_mux: IO_MUX) -> Self {
Io { _io_mux }
}
/// Set the interrupt priority for GPIO interrupts.
pub fn set_interrupt_priority(&self, prio: Priority) {
unwrap!(interrupt::enable(Interrupt::GPIO, prio));
}
}
impl crate::private::Sealed for Io {}
impl InterruptConfigurable for Io {
/// Install the given interrupt handler replacing any previously set
/// handler.
///
/// ⚠️ Be careful when using this together with the async API:
///
/// - The async driver will disable any interrupts whose status is not
/// cleared by the user handler.
/// - Clearing the interrupt status in the user handler will prevent the
/// async driver from detecting the interrupt, silently disabling the
/// corresponding pin's async API.
/// - You will not be notified if you make a mistake.
fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
for core in crate::Cpu::other() {
crate::interrupt::disable(core, Interrupt::GPIO);
}
self.set_interrupt_priority(handler.priority());
unsafe { interrupt::bind_interrupt(Interrupt::GPIO, user_gpio_interrupt_handler) };
USER_INTERRUPT_HANDLER.store(handler.handler());
}
}
#[ram]
extern "C" fn user_gpio_interrupt_handler() {
USER_INTERRUPT_HANDLER.call();
default_gpio_interrupt_handler();
}
#[ram]
extern "C" fn default_gpio_interrupt_handler() {
handle_pin_interrupts(on_pin_irq);
}
#[ram]
fn on_pin_irq(pin_nr: u8) {
// FIXME: async handlers signal completion by disabling the interrupt, but this
// conflicts with user handlers.
set_int_enable(pin_nr, 0, 0, false);
asynch::PIN_WAKERS[pin_nr as usize].wake(); // wake task
}
#[doc(hidden)]
#[macro_export]
macro_rules! if_output_pin {
// Base case: not an Output pin, substitute the else branch
({ $($then:tt)* } else { $($else:tt)* }) => { $($else)* };
// First is an Output pin, skip checking and substitute the then branch
(Output $(, $other:ident)* { $($then:tt)* } else { $($else:tt)* }) => { $($then)* };
// First is not an Output pin, check the rest
($not:ident $(, $other:ident)* { $($then:tt)* } else { $($else:tt)* }) => {
$crate::if_output_pin!($($other),* { $($then)* } else { $($else)* })
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! if_rtcio_pin {
// Base case: not an RtcIo pin, substitute the else branch
({ $($then:tt)* } else { $($else:tt)* }) => { $($else)* };
// First is an RtcIo pin, skip checking and substitute the then branch
(RtcIo $(, $other:ident)* { $($then:tt)* } else { $($else:tt)* }) => { $($then)* };
(RtcIoInput $(, $other:ident)* { $($then:tt)* } else { $($else:tt)* }) => { $($then)* };
// First is not an RtcIo pin, check the rest
($not:ident $(, $other:ident)* { $($then:tt)* } else { $($else:tt)* }) => {
$crate::if_rtcio_pin!($($other),* { $($then)* } else { $($else)* })
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! io_type {
(Input, $gpionum:literal) => {
impl $crate::gpio::InputPin for $crate::gpio::GpioPin<$gpionum> {}
};
(Output, $gpionum:literal) => {
impl $crate::gpio::OutputPin for $crate::gpio::GpioPin<$gpionum> {}
};
(Analog, $gpionum:literal) => {
// FIXME: the implementation shouldn't be in the GPIO module
#[cfg(any(esp32c2, esp32c3, esp32c6, esp32h2))]
impl $crate::gpio::AnalogPin for $crate::gpio::GpioPin<$gpionum> {
/// Configures the pin for analog mode.
fn set_analog(&self, _: $crate::private::Internal) {
use $crate::peripherals::GPIO;
$crate::gpio::io_mux_reg($gpionum).modify(|_, w| unsafe {
w.mcu_sel().bits(1);
w.fun_ie().clear_bit();
w.fun_wpu().clear_bit();
w.fun_wpd().clear_bit()
});
unsafe { GPIO::steal() }
.enable_w1tc()
.write(|w| unsafe { w.bits(1 << $gpionum) });
}
}
};
($other:ident, $gpionum:literal) => {
// TODO
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! gpio {
(
$(
($gpionum:literal, [$($type:tt),*]
$(
( $( $af_input_num:literal => $af_input_signal:ident )* )
( $( $af_output_num:literal => $af_output_signal:ident )* )
)?
)
)+
) => {
paste::paste! {
$(
$(
$crate::io_type!($type, $gpionum);
)*
impl $crate::gpio::Pin for $crate::gpio::GpioPin<$gpionum> {
fn number(&self) -> u8 {
$gpionum
}
fn degrade_pin(&self, _: $crate::private::Internal) -> $crate::gpio::AnyPin {
$crate::gpio::AnyPin(AnyPinInner::[< Gpio $gpionum >](unsafe { Self::steal() }))
}
fn gpio_bank(&self, _: $crate::private::Internal) -> $crate::gpio::GpioRegisterAccess {
$crate::gpio::GpioRegisterAccess::from($gpionum)
}
fn output_signals(&self, _: $crate::private::Internal) -> &[($crate::gpio::AlternateFunction, $crate::gpio::OutputSignal)] {
&[
$(
$(
(
$crate::gpio::AlternateFunction::[< Function $af_output_num >],
$crate::gpio::OutputSignal::$af_output_signal
),
)*
)?
]
}
fn input_signals(&self, _: $crate::private::Internal) -> &[($crate::gpio::AlternateFunction, $crate::gpio::InputSignal)] {
&[
$(
$(
(
$crate::gpio::AlternateFunction::[< Function $af_input_num >],
$crate::gpio::InputSignal::$af_input_signal
),
)*
)?
]
}
}
impl From<$crate::gpio::GpioPin<$gpionum>> for $crate::gpio::AnyPin {
fn from(pin: $crate::gpio::GpioPin<$gpionum>) -> Self {
$crate::gpio::Pin::degrade(pin)
}
}
)+
pub(crate) enum AnyPinInner {
$(
[<Gpio $gpionum >]($crate::gpio::GpioPin<$gpionum>),
)+
}
impl $crate::peripheral::Peripheral for $crate::gpio::AnyPin {
type P = $crate::gpio::AnyPin;
unsafe fn clone_unchecked(&self) -> Self {
match self.0 {
$(AnyPinInner::[<Gpio $gpionum >](_) => {
Self(AnyPinInner::[< Gpio $gpionum >](unsafe { $crate::gpio::GpioPin::steal() }))
})+
}
}
}
// These macros call the code block on the actually contained GPIO pin.
#[doc(hidden)]
macro_rules! handle_gpio_output {
($this:expr, $inner:ident, $code:tt) => {
match $this {
$(
AnyPinInner::[<Gpio $gpionum >]($inner) => $crate::if_output_pin!($($type),* {
$code
} else {{
let _ = $inner;
panic!("Unsupported")
}}),
)+
}
}
}
#[doc(hidden)]
macro_rules! handle_gpio_input {
($this:expr, $inner:ident, $code:tt) => {
match $this {
$(
AnyPinInner::[<Gpio $gpionum >]($inner) => $code
)+
}
}
}
pub(crate) use handle_gpio_output;
pub(crate) use handle_gpio_input;
cfg_if::cfg_if! {
if #[cfg(any(lp_io, rtc_cntl))] {
#[doc(hidden)]
macro_rules! handle_rtcio {
($this:expr, $inner:ident, $code:tt) => {
match $this {
$(
AnyPinInner::[<Gpio $gpionum >]($inner) => $crate::if_rtcio_pin!($($type),* {
$code
} else {{
let _ = $inner;
panic!("Unsupported")
}}),
)+
}
}
}
#[doc(hidden)]
macro_rules! handle_rtcio_with_resistors {
($this:expr, $inner:ident, $code:tt) => {
match $this {
$(
AnyPinInner::[<Gpio $gpionum >]($inner) => $crate::if_rtcio_pin!($($type),* {
$crate::if_output_pin!($($type),* {
$code
} else {{
let _ = $inner;
panic!("Unsupported")
}})
} else {{
let _ = $inner;
panic!("Unsupported")
}}),
)+
}
}
}
pub(crate) use handle_rtcio;
pub(crate) use handle_rtcio_with_resistors;
}
}
}
};
}
/// Push-pull digital output.
///
/// This driver configures the GPIO pin to be a push-pull output driver.
/// Push-pull means that the driver actively sets the output voltage level
/// for both high and low logical [`Level`]s.
pub struct Output<'d, P = AnyPin> {
pin: Flex<'d, P>,
}
impl<P> private::Sealed for Output<'_, P> {}
impl<'d, P> Peripheral for Output<'d, P> {
type P = Flex<'d, P>;
unsafe fn clone_unchecked(&self) -> Self::P {
self.pin.clone_unchecked()
}
}
impl<'d> Output<'d> {
/// Creates a new, type-erased GPIO output driver.
///
/// The `initial_output` parameter sets the initial output level of the pin.
///
/// ## Example
///
/// The following example configures `GPIO5` to pulse a LED once. The
/// example assumes that the LED is connected such that it is on when
/// the pin is low.
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// use esp_hal::gpio::{Level, Output};
/// use esp_hal::delay::Delay;
///
/// fn blink_once(led: &mut Output<'_>, delay: &mut Delay) {
/// led.set_low();
/// delay.delay_millis(500);
/// led.set_high();
/// }
///
/// let mut led = Output::new(peripherals.GPIO5, Level::High);
/// let mut delay = Delay::new();
///
/// blink_once(&mut led, &mut delay);
/// # }
/// ```
#[inline]
pub fn new(pin: impl Peripheral<P = impl OutputPin> + 'd, initial_output: Level) -> Self {
Self::new_typed(pin.map_into(), initial_output)
}
}
impl<'d, P> Output<'d, P>
where
P: OutputPin,
{
/// Creates a new, typed GPIO output driver.
///
/// The `initial_output` parameter sets the initial output level of the pin.
///
/// This constructor is useful when you want to limit which GPIO pin can be
/// used for a particular function.
///
/// ## Example
///
/// The following example configures `GPIO5` to pulse a LED once. The
/// example assumes that the LED is connected such that it is on when
/// the pin is low.
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// use esp_hal::gpio::{GpioPin, Level, Output};
/// use esp_hal::delay::Delay;
///
/// fn blink_once(led: &mut Output<'_, GpioPin<5>>, delay: &mut Delay) {
/// led.set_low();
/// delay.delay_millis(500);
/// led.set_high();
/// }
///
/// let mut led = Output::new_typed(peripherals.GPIO5, Level::High);
/// let mut delay = Delay::new();
///
/// blink_once(&mut led, &mut delay);
/// # }
/// ```
#[inline]
pub fn new_typed(pin: impl Peripheral<P = P> + 'd, initial_output: Level) -> Self {
let mut pin = Flex::new_typed(pin);
pin.set_level(initial_output);
pin.set_as_output();
Self { pin }
}
/// Split the pin into an input and output signal.
///
/// Peripheral signals allow connecting peripherals together without using
/// external hardware.
pub fn split(self) -> (interconnect::InputSignal, interconnect::OutputSignal) {
self.pin.split()
}
/// Returns a peripheral [input][interconnect::InputSignal] connected to
/// this pin.
///
/// The input signal can be passed to peripherals in place of an input pin.
#[inline]
pub fn peripheral_input(&self) -> interconnect::InputSignal {
self.pin.peripheral_input()
}
/// Turns the pin object into a peripheral
/// [output][interconnect::OutputSignal].
///
/// The output signal can be passed to peripherals in place of an output
/// pin.
#[inline]
pub fn into_peripheral_output(self) -> interconnect::OutputSignal {
self.pin.into_peripheral_output()
}
/// Set the output as high.
#[inline]
pub fn set_high(&mut self) {
self.set_level(Level::High)
}
/// Set the output as low.
#[inline]
pub fn set_low(&mut self) {
self.set_level(Level::Low)
}
/// Set the output level.
#[inline]
pub fn set_level(&mut self, level: Level) {
self.pin.set_level(level)
}
/// Is the output pin set as high?
#[inline]
pub fn is_set_high(&self) -> bool {
self.output_level() == Level::High
}
/// Is the output pin set as low?
#[inline]
pub fn is_set_low(&self) -> bool {
self.output_level() == Level::Low
}
/// What level output is set to
#[inline]
pub fn output_level(&self) -> Level {
self.pin.output_level()
}
/// Toggle pin output
#[inline]
pub fn toggle(&mut self) {
self.pin.toggle();
}
/// Configure the [DriveStrength] of the pin
#[inline]
pub fn set_drive_strength(&mut self, strength: DriveStrength) {
self.pin.set_drive_strength(strength);
}
}
/// Digital input.
///
/// This driver configures the GPIO pin to be an input. Input drivers read the
/// voltage of their pins and convert it to a logical [`Level`].
pub struct Input<'d, P = AnyPin> {
pin: Flex<'d, P>,
}
impl<P> private::Sealed for Input<'_, P> {}
impl<'d, P> Peripheral for Input<'d, P> {
type P = Flex<'d, P>;
unsafe fn clone_unchecked(&self) -> Self::P {
self.pin.clone_unchecked()
}
}
impl<'d> Input<'d> {
/// Creates a new, type-erased GPIO input.
///
/// The `pull` parameter configures internal pull-up or pull-down
/// resistors.
///
/// ## Example
///
/// The following example configures `GPIO5` to read a button press. The
/// example assumes that the button is connected such that the pin is low
/// when the button is pressed.
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// use esp_hal::gpio::{Level, Input, Pull};
/// use esp_hal::delay::Delay;
///
/// fn print_when_pressed(button: &mut Input<'_>, delay: &mut Delay) {
/// let mut was_pressed = false;
/// loop {
/// let is_pressed = button.is_low();
/// if is_pressed && !was_pressed {
/// println!("Button pressed!");
/// }
/// was_pressed = is_pressed;
/// delay.delay_millis(100);
/// }
/// }
///
/// let mut button = Input::new(
/// peripherals.GPIO5,
/// Pull::Up,
/// );
/// let mut delay = Delay::new();
///
/// print_when_pressed(&mut button, &mut delay);
/// # }
/// ```
#[inline]
pub fn new(pin: impl Peripheral<P = impl InputPin> + 'd, pull: Pull) -> Self {
Self::new_typed(pin.map_into(), pull)
}
}
impl<'d, P> Input<'d, P>
where
P: InputPin,
{
/// Creates a new, typed GPIO input.
///
/// The `pull` parameter configures internal pull-up or pull-down
/// resistors.
///
/// This constructor is useful when you want to limit which GPIO pin can be
/// used for a particular function.
///
/// ## Example
///
/// The following example configures `GPIO5` to read a button press. The
/// example assumes that the button is connected such that the pin is low
/// when the button is pressed.
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// use esp_hal::gpio::{GpioPin, Level, Input, Pull};
/// use esp_hal::delay::Delay;
///
/// fn print_when_pressed(
/// button: &mut Input<'_, GpioPin<5>>,
/// delay: &mut Delay,
/// ) {
/// let mut was_pressed = false;
/// loop {
/// let is_pressed = button.is_low();
/// if is_pressed && !was_pressed {
/// println!("Button pressed!");
/// }
/// was_pressed = is_pressed;
/// delay.delay_millis(100);
/// }
/// }
///
/// let mut button = Input::new_typed(
/// peripherals.GPIO5,
/// Pull::Up,
/// );
/// let mut delay = Delay::new();
///
/// print_when_pressed(&mut button, &mut delay);
/// # }
/// ```
#[inline]
pub fn new_typed(pin: impl Peripheral<P = P> + 'd, pull: Pull) -> Self {
let mut pin = Flex::new_typed(pin);
pin.set_as_input(pull);
Self { pin }
}
/// Returns a peripheral [input][interconnect::InputSignal] connected to
/// this pin.
///
/// The input signal can be passed to peripherals in place of an input pin.
#[inline]
pub fn peripheral_input(&self) -> interconnect::InputSignal {
self.pin.peripheral_input()
}
/// Get whether the pin input level is high.
#[inline]
pub fn is_high(&self) -> bool {
self.level() == Level::High
}
/// Get whether the pin input level is low.
#[inline]
pub fn is_low(&self) -> bool {
self.level() == Level::Low
}
/// Get the current pin input level.
#[inline]
pub fn level(&self) -> Level {
self.pin.level()
}
/// Listen for interrupts
#[inline]
pub fn listen(&mut self, event: Event) {
self.pin.listen(event);
}
/// Stop listening for interrupts
#[inline]
pub fn unlisten(&mut self) {
self.pin.unlisten();
}
/// Clear the interrupt status bit for this Pin
#[inline]
pub fn clear_interrupt(&mut self) {
self.pin.clear_interrupt();
}
/// Checks if the interrupt status bit for this Pin is set
#[inline]
pub fn is_interrupt_set(&self) -> bool {
self.pin.is_interrupt_set()
}
/// Enable as a wake-up source.
///
/// This will unlisten for interrupts
#[inline]
pub fn wakeup_enable(&mut self, enable: bool, event: WakeEvent) {
self.pin.wakeup_enable(enable, event);
}
}
impl<P> Input<'_, P>
where
P: InputPin + OutputPin,
{
/// Split the pin into an input and output signal.
///
/// Peripheral signals allow connecting peripherals together without using
/// external hardware.
pub fn split(self) -> (interconnect::InputSignal, interconnect::OutputSignal) {
self.pin.split()
}
/// Turns the pin object into a peripheral
/// [output][interconnect::OutputSignal].
///
/// The output signal can be passed to peripherals in place of an output
/// pin.
#[inline]
pub fn into_peripheral_output(self) -> interconnect::OutputSignal {
self.pin.into_peripheral_output()
}
}
/// Open drain digital output.
///
/// This driver configures the GPIO pin to be an open drain output driver.
/// Open drain means that the driver actively pulls the output voltage level low
/// for the low logical [`Level`], but leaves the high level floating, which is
/// then determined by external hardware, or internal pull-up/pull-down
/// resistors.
pub struct OutputOpenDrain<'d, P = AnyPin> {
pin: Flex<'d, P>,
}
impl<P> private::Sealed for OutputOpenDrain<'_, P> {}
impl<'d, P> Peripheral for OutputOpenDrain<'d, P> {
type P = Flex<'d, P>;
unsafe fn clone_unchecked(&self) -> Self::P {
self.pin.clone_unchecked()
}
}
impl<'d> OutputOpenDrain<'d> {
/// Creates a new, type-erased GPIO output driver.
///
/// The `initial_output` parameter sets the initial output level of the pin.
/// The `pull` parameter configures internal pull-up or pull-down
/// resistors.
///
/// ## Example
///
/// The following example configures `GPIO5` to pulse a LED once. The
/// example assumes that the LED is connected such that it is on when
/// the pin is low.
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// use esp_hal::gpio::{Level, OutputOpenDrain, Pull};
/// use esp_hal::delay::Delay;
///
/// fn blink_once(led: &mut OutputOpenDrain<'_>, delay: &mut Delay) {
/// led.set_low();
/// delay.delay_millis(500);
/// led.set_high();
/// }
///
/// let mut led = OutputOpenDrain::new(
/// peripherals.GPIO5,
/// Level::High,
/// Pull::Up,
/// );
/// let mut delay = Delay::new();
///
/// blink_once(&mut led, &mut delay);
/// # }
/// ```
#[inline]
pub fn new(
pin: impl Peripheral<P = impl InputPin + OutputPin> + 'd,
initial_output: Level,
pull: Pull,
) -> Self {
Self::new_typed(pin.map_into(), initial_output, pull)
}
}
impl<'d, P> OutputOpenDrain<'d, P>
where
P: InputPin + OutputPin,
{
/// Creates a new, typed GPIO output driver.
///
/// The `initial_output` parameter sets the initial output level of the pin.
/// The `pull` parameter configures internal pull-up or pull-down
/// resistors.
///
/// ## Example
///
/// The following example configures `GPIO5` to pulse a LED once. The
/// example assumes that the LED is connected such that it is on when
/// the pin is low.
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// use esp_hal::gpio::{GpioPin, Level, OutputOpenDrain, Pull};
/// use esp_hal::delay::Delay;
///
/// fn blink_once(
/// led: &mut OutputOpenDrain<'_, GpioPin<5>>,
/// delay: &mut Delay,
/// ) {
/// led.set_low();
/// delay.delay_millis(500);
/// led.set_high();
/// }
///
/// let mut led = OutputOpenDrain::new_typed(
/// peripherals.GPIO5,
/// Level::High,
/// Pull::Up,
/// );
/// let mut delay = Delay::new();
///
/// blink_once(&mut led, &mut delay);
/// # }
/// ```
#[inline]
pub fn new_typed(pin: impl Peripheral<P = P> + 'd, initial_output: Level, pull: Pull) -> Self {
let mut pin = Flex::new_typed(pin);
pin.set_level(initial_output);
pin.set_as_open_drain(pull);
Self { pin }
}
/// Split the pin into an input and output signal.
///
/// Peripheral signals allow connecting peripherals together without using
/// external hardware.
pub fn split(self) -> (interconnect::InputSignal, interconnect::OutputSignal) {
self.pin.split()
}
/// Returns a peripheral [input][interconnect::InputSignal] connected to
/// this pin.
///
/// The input signal can be passed to peripherals in place of an input pin.
#[inline]
pub fn peripheral_input(&self) -> interconnect::InputSignal {
self.pin.peripheral_input()
}
/// Turns the pin object into a peripheral
/// [output][interconnect::OutputSignal].
///
/// The output signal can be passed to peripherals in place of an output
/// pin.
#[inline]
pub fn into_peripheral_output(self) -> interconnect::OutputSignal {
self.pin.into_peripheral_output()
}
/// Get whether the pin input level is high.
#[inline]
pub fn is_high(&self) -> bool {
self.level() == Level::High
}
/// Get whether the pin input level is low.
#[inline]
pub fn is_low(&self) -> bool {
self.level() == Level::Low
}
/// Get the current pin input level.
#[inline]
pub fn level(&self) -> Level {
self.pin.level()
}
/// Listen for interrupts
#[inline]
pub fn listen(&mut self, event: Event) {
self.pin.listen(event);
}
/// Clear the interrupt status bit for this Pin
#[inline]
pub fn clear_interrupt(&mut self) {
self.pin.clear_interrupt();
}
/// Set the output as high.
#[inline]
pub fn set_high(&mut self) {
self.set_level(Level::High);
}
/// Set the output as low.
#[inline]
pub fn set_low(&mut self) {
self.set_level(Level::Low);
}
/// Set the output level.
#[inline]
pub fn set_level(&mut self, level: Level) {
self.pin.set_level(level);
}
/// Is the output pin set as high?
#[inline]
pub fn is_set_high(&self) -> bool {
self.output_level() == Level::High
}
/// Is the output pin set as low?
#[inline]
pub fn is_set_low(&self) -> bool {
self.output_level() == Level::Low
}
/// What level output is set to
#[inline]
pub fn output_level(&self) -> Level {
self.pin.output_level()
}
/// Toggle pin output
#[inline]
pub fn toggle(&mut self) {
self.pin.toggle()
}
/// Configure the [DriveStrength] of the pin
pub fn set_drive_strength(&mut self, strength: DriveStrength) {
self.pin.set_drive_strength(strength);
}
}
/// Flexible pin driver.
///
/// This driver allows changing the pin mode between input and output.
pub struct Flex<'d, P = AnyPin> {
pin: PeripheralRef<'d, P>,
}
impl<P> private::Sealed for Flex<'_, P> {}
impl<P> Peripheral for Flex<'_, P> {
type P = Self;
unsafe fn clone_unchecked(&self) -> Self::P {
Self {
pin: PeripheralRef::new(core::ptr::read(&*self.pin as *const P)),
}
}
}
impl<'d> Flex<'d> {
/// Create flexible pin driver for a [Pin].
/// No mode change happens.
#[inline]
pub fn new(pin: impl Peripheral<P = impl Into<AnyPin>> + 'd) -> Self {
Self::new_typed(pin.map_into())
}
}
impl<'d, P> Flex<'d, P>
where
P: Pin,
{
/// Create flexible pin driver for a [Pin].
/// No mode change happens.
#[inline]
pub fn new_typed(pin: impl Peripheral<P = P> + 'd) -> Self {
crate::into_ref!(pin);
Self { pin }
}
/// Returns a peripheral [input][interconnect::InputSignal] connected to
/// this pin.
///
/// The input signal can be passed to peripherals in place of an input pin.
#[inline]
pub fn peripheral_input(&self) -> interconnect::InputSignal {
self.pin.degrade_pin(private::Internal).split().0
}
}
impl<P> Flex<'_, P>
where
P: InputPin,
{
/// Set the GPIO to input mode.
pub fn set_as_input(&mut self, pull: Pull) {
self.pin.init_input(pull, private::Internal);
self.pin.enable_output(false, private::Internal);
}
/// Get whether the pin input level is high.
#[inline]
pub fn is_high(&self) -> bool {
self.level() == Level::High
}
/// Get whether the pin input level is low.
#[inline]
pub fn is_low(&self) -> bool {
self.level() == Level::Low
}
/// Get the current pin input level.
#[inline]
pub fn level(&self) -> Level {
self.pin.is_input_high(private::Internal).into()
}
fn listen_with_options(
&self,
event: Event,
int_enable: bool,
nmi_enable: bool,
wake_up_from_light_sleep: bool,
) {
if wake_up_from_light_sleep {
match event {
Event::AnyEdge | Event::RisingEdge | Event::FallingEdge => {
panic!("Edge triggering is not supported for wake-up from light sleep");
}
_ => {}
}
}
set_int_enable(
self.pin.number(),
gpio_intr_enable(int_enable, nmi_enable),
event as u8,
wake_up_from_light_sleep,
)
}
/// Listen for interrupts
#[inline]
pub fn listen(&mut self, event: Event) {
self.listen_with_options(event, true, false, false)
}
/// Stop listening for interrupts
pub fn unlisten(&mut self) {
set_int_enable(self.pin.number(), 0, 0, false);
}
/// Clear the interrupt status bit for this Pin
#[inline]
pub fn clear_interrupt(&mut self) {
self.pin
.gpio_bank(private::Internal)
.write_interrupt_status_clear(1 << (self.pin.number() % 32));
}
/// Checks if the interrupt status bit for this Pin is set
#[inline]
pub fn is_interrupt_set(&self) -> bool {
self.pin
.gpio_bank(private::Internal)
.read_interrupt_status()
& 1 << (self.pin.number() % 32)
!= 0
}
/// Enable as a wake-up source.
///
/// This will unlisten for interrupts
#[inline]
pub fn wakeup_enable(&mut self, enable: bool, event: WakeEvent) {
self.listen_with_options(event.into(), false, false, enable);
}
}
impl<P> Flex<'_, P>
where
P: OutputPin,
{
/// Set the GPIO to output mode.
pub fn set_as_output(&mut self) {
self.pin.set_to_push_pull_output(private::Internal);
}
/// Set the output as high.
#[inline]
pub fn set_high(&mut self) {
self.set_level(Level::High)
}
/// Set the output as low.
#[inline]
pub fn set_low(&mut self) {
self.set_level(Level::Low)
}
/// Set the output level.
#[inline]
pub fn set_level(&mut self, level: Level) {
self.pin.set_output_high(level.into(), private::Internal);
}
/// Is the output pin set as high?
#[inline]
pub fn is_set_high(&self) -> bool {
self.output_level() == Level::High
}
/// Is the output pin set as low?
#[inline]
pub fn is_set_low(&self) -> bool {
self.output_level() == Level::Low
}
/// What level output is set to
#[inline]
pub fn output_level(&self) -> Level {
self.pin.is_set_high(private::Internal).into()
}
/// Toggle pin output
#[inline]
pub fn toggle(&mut self) {
let level = !self.output_level();
self.set_level(level);
}
/// Configure the [DriveStrength] of the pin
#[inline]
pub fn set_drive_strength(&mut self, strength: DriveStrength) {
self.pin.set_drive_strength(strength, private::Internal);
}
/// Set the GPIO to open-drain mode.
pub fn set_as_open_drain(&mut self, pull: Pull) {
self.pin.set_to_open_drain_output(private::Internal);
self.pin.pull_direction(pull, private::Internal);
}
/// Split the pin into an input and output signal.
///
/// Peripheral signals allow connecting peripherals together without using
/// external hardware.
pub fn split(self) -> (interconnect::InputSignal, interconnect::OutputSignal) {
self.pin.degrade_pin(private::Internal).split()
}
/// Turns the pin object into a peripheral
/// [output][interconnect::OutputSignal].
///
/// The output signal can be passed to peripherals in place of an output
/// pin.
#[inline]
pub fn into_peripheral_output(self) -> interconnect::OutputSignal {
self.split().1
}
}
// Unfortunate implementation details responsible for:
// - making pin drivers work with the peripheral signal system
// - making the pin drivers work with the sleep API
impl<P: Pin> Pin for Flex<'_, P> {
delegate::delegate! {
to self.pin {
fn number(&self) -> u8;
fn degrade_pin(&self, _internal: private::Internal) -> AnyPin;
fn output_signals(&self, _internal: private::Internal) -> &[(AlternateFunction, OutputSignal)];
fn input_signals(&self, _internal: private::Internal) -> &[(AlternateFunction, InputSignal)];
fn gpio_bank(&self, _internal: private::Internal) -> GpioRegisterAccess;
}
}
}
impl<P: RtcPin> RtcPin for Flex<'_, P> {
delegate::delegate! {
to self.pin {
#[cfg(xtensa)]
fn rtc_number(&self) -> u8;
#[cfg(any(xtensa, esp32c6))]
fn rtc_set_config(&mut self, input_enable: bool, mux: bool, func: RtcFunction);
fn rtcio_pad_hold(&mut self, enable: bool);
#[cfg(any(esp32c3, esp32c2, esp32c6))]
unsafe fn apply_wakeup(&mut self, wakeup: bool, level: u8);
}
}
}
impl<P: RtcPinWithResistors> RtcPinWithResistors for Flex<'_, P> {
delegate::delegate! {
to self.pin {
fn rtcio_pullup(&mut self, enable: bool);
fn rtcio_pulldown(&mut self, enable: bool);
}
}
}
pub(crate) mod internal {
use super::*;
impl private::Sealed for AnyPin {}
impl AnyPin {
/// Split the pin into an input and output signal.
///
/// Peripheral signals allow connecting peripherals together without
/// using external hardware.
#[inline]
pub fn split(self) -> (interconnect::InputSignal, interconnect::OutputSignal) {
handle_gpio_input!(self.0, target, { target.split() })
}
}
impl Pin for AnyPin {
fn number(&self) -> u8 {
handle_gpio_input!(&self.0, target, { Pin::number(target) })
}
fn degrade_pin(&self, _: private::Internal) -> AnyPin {
unsafe { self.clone_unchecked() }
}
fn sleep_mode(&mut self, on: bool, _: private::Internal) {
handle_gpio_input!(&mut self.0, target, {
Pin::sleep_mode(target, on, private::Internal)
})
}
fn set_alternate_function(&mut self, alternate: AlternateFunction, _: private::Internal) {
handle_gpio_input!(&mut self.0, target, {
Pin::set_alternate_function(target, alternate, private::Internal)
})
}
fn output_signals(&self, _: private::Internal) -> &[(AlternateFunction, OutputSignal)] {
handle_gpio_output!(&self.0, target, {
Pin::output_signals(target, private::Internal)
})
}
fn input_signals(&self, _: private::Internal) -> &[(AlternateFunction, InputSignal)] {
handle_gpio_input!(&self.0, target, {
Pin::input_signals(target, private::Internal)
})
}
fn gpio_bank(&self, _: private::Internal) -> GpioRegisterAccess {
handle_gpio_input!(&self.0, target, {
Pin::gpio_bank(target, private::Internal)
})
}
}
impl InputPin for AnyPin {}
// Need to forward these one by one because not all pins support all functions.
impl OutputPin for AnyPin {
fn init_output(
&mut self,
alternate: AlternateFunction,
open_drain: bool,
input_enable: Option<bool>,
_: private::Internal,
) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::init_output(
target,
alternate,
open_drain,
input_enable,
private::Internal,
)
})
}
fn set_to_open_drain_output(&mut self, _: private::Internal) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::set_to_open_drain_output(target, private::Internal)
})
}
fn set_to_push_pull_output(&mut self, _: private::Internal) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::set_to_push_pull_output(target, private::Internal)
})
}
fn set_output_high(&mut self, high: bool, _: private::Internal) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::set_output_high(target, high, private::Internal)
})
}
fn set_drive_strength(&mut self, strength: DriveStrength, _: private::Internal) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::set_drive_strength(target, strength, private::Internal)
})
}
fn enable_open_drain(&mut self, on: bool, _: private::Internal) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::enable_open_drain(target, on, private::Internal)
})
}
fn internal_pull_up_in_sleep_mode(&mut self, on: bool, _: private::Internal) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::internal_pull_up_in_sleep_mode(target, on, private::Internal)
})
}
fn internal_pull_down_in_sleep_mode(&mut self, on: bool, _: private::Internal) {
handle_gpio_output!(&mut self.0, target, {
OutputPin::internal_pull_down_in_sleep_mode(target, on, private::Internal)
})
}
fn is_set_high(&self, _: private::Internal) -> bool {
handle_gpio_output!(&self.0, target, {
OutputPin::is_set_high(target, private::Internal)
})
}
}
#[cfg(any(xtensa, esp32c2, esp32c3, esp32c6))]
impl RtcPin for AnyPin {
#[cfg(xtensa)]
#[allow(unused_braces)] // False positive :/
fn rtc_number(&self) -> u8 {
handle_rtcio!(&self.0, target, { RtcPin::rtc_number(target) })
}
#[cfg(any(xtensa, esp32c6))]
fn rtc_set_config(&mut self, input_enable: bool, mux: bool, func: RtcFunction) {
handle_rtcio!(&mut self.0, target, {
RtcPin::rtc_set_config(target, input_enable, mux, func)
})
}
fn rtcio_pad_hold(&mut self, enable: bool) {
handle_rtcio!(&mut self.0, target, {
RtcPin::rtcio_pad_hold(target, enable)
})
}
#[cfg(any(esp32c2, esp32c3, esp32c6))]
unsafe fn apply_wakeup(&mut self, wakeup: bool, level: u8) {
handle_rtcio!(&mut self.0, target, {
RtcPin::apply_wakeup(target, wakeup, level)
})
}
}
#[cfg(any(esp32c2, esp32c3, esp32c6, xtensa))]
impl RtcPinWithResistors for AnyPin {
fn rtcio_pullup(&mut self, enable: bool) {
handle_rtcio_with_resistors!(&mut self.0, target, {
RtcPinWithResistors::rtcio_pullup(target, enable)
})
}
fn rtcio_pulldown(&mut self, enable: bool) {
handle_rtcio_with_resistors!(&mut self.0, target, {
RtcPinWithResistors::rtcio_pulldown(target, enable)
})
}
}
}
fn is_listening(pin_num: u8) -> bool {
let bits = unsafe { GPIO::steal() }
.pin(pin_num as usize)
.read()
.int_ena()
.bits();
bits != 0
}
fn set_int_enable(gpio_num: u8, int_ena: u8, int_type: u8, wake_up_from_light_sleep: bool) {
unsafe { GPIO::steal() }
.pin(gpio_num as usize)
.modify(|_, w| unsafe {
w.int_ena().bits(int_ena);
w.int_type().bits(int_type);
w.wakeup_enable().bit(wake_up_from_light_sleep)
});
}
#[ram]
fn handle_pin_interrupts(handle: impl Fn(u8)) {
let intrs_bank0 = InterruptStatusRegisterAccess::Bank0.interrupt_status_read();
#[cfg(any(esp32, esp32s2, esp32s3))]
let intrs_bank1 = InterruptStatusRegisterAccess::Bank1.interrupt_status_read();
let mut intr_bits = intrs_bank0;
while intr_bits != 0 {
let pin_nr = intr_bits.trailing_zeros();
handle(pin_nr as u8);
intr_bits -= 1 << pin_nr;
}
// clear interrupt bits
Bank0GpioRegisterAccess::write_interrupt_status_clear(intrs_bank0);
#[cfg(any(esp32, esp32s2, esp32s3))]
{
let mut intr_bits = intrs_bank1;
while intr_bits != 0 {
let pin_nr = intr_bits.trailing_zeros();
handle(pin_nr as u8 + 32);
intr_bits -= 1 << pin_nr;
}
Bank1GpioRegisterAccess::write_interrupt_status_clear(intrs_bank1);
}
}
mod asynch {
use core::task::{Context, Poll};
use embassy_sync::waitqueue::AtomicWaker;
use super::*;
#[ram]
pub(super) static PIN_WAKERS: [AtomicWaker; NUM_PINS] =
[const { AtomicWaker::new() }; NUM_PINS];
impl<P> Flex<'_, P>
where
P: InputPin,
{
async fn wait_for(&mut self, event: Event) {
self.listen(event);
PinFuture::new(self.pin.number()).await
}
/// Wait until the pin is high. If it is already high, return
/// immediately.
pub async fn wait_for_high(&mut self) {
self.wait_for(Event::HighLevel).await
}
/// Wait until the pin is low. If it is already low, return immediately.
pub async fn wait_for_low(&mut self) {
self.wait_for(Event::LowLevel).await
}
/// Wait for the pin to undergo a transition from low to high.
pub async fn wait_for_rising_edge(&mut self) {
self.wait_for(Event::RisingEdge).await
}
/// Wait for the pin to undergo a transition from high to low.
pub async fn wait_for_falling_edge(&mut self) {
self.wait_for(Event::FallingEdge).await
}
/// Wait for the pin to undergo any transition, i.e low to high OR high
/// to low.
pub async fn wait_for_any_edge(&mut self) {
self.wait_for(Event::AnyEdge).await
}
}
impl<P> Input<'_, P>
where
P: InputPin,
{
/// Wait until the pin is high. If it is already high, return
/// immediately.
pub async fn wait_for_high(&mut self) {
self.pin.wait_for_high().await
}
/// Wait until the pin is low. If it is already low, return immediately.
pub async fn wait_for_low(&mut self) {
self.pin.wait_for_low().await
}
/// Wait for the pin to undergo a transition from low to high.
pub async fn wait_for_rising_edge(&mut self) {
self.pin.wait_for_rising_edge().await
}
/// Wait for the pin to undergo a transition from high to low.
pub async fn wait_for_falling_edge(&mut self) {
self.pin.wait_for_falling_edge().await
}
/// Wait for the pin to undergo any transition, i.e low to high OR high
/// to low.
pub async fn wait_for_any_edge(&mut self) {
self.pin.wait_for_any_edge().await
}
}
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct PinFuture {
pin_num: u8,
}
impl PinFuture {
fn new(pin_num: u8) -> Self {
Self { pin_num }
}
}
impl core::future::Future for PinFuture {
type Output = ();
fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
PIN_WAKERS[self.pin_num as usize].register(cx.waker());
// if pin is no longer listening its been triggered
// therefore the future has resolved
if !is_listening(self.pin_num) {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
}
mod embedded_hal_02_impls {
use embedded_hal_02::digital::v2 as digital;
use super::*;
impl<P> digital::InputPin for Input<'_, P>
where
P: InputPin,
{
type Error = core::convert::Infallible;
fn is_high(&self) -> Result<bool, Self::Error> {
Ok(self.pin.is_high())
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(self.pin.is_low())
}
}
impl<P> digital::OutputPin for Output<'_, P>
where
P: OutputPin,
{
type Error = core::convert::Infallible;
fn set_high(&mut self) -> Result<(), Self::Error> {
self.pin.set_high();
Ok(())
}
fn set_low(&mut self) -> Result<(), Self::Error> {
self.pin.set_low();
Ok(())
}
}
impl<P> digital::StatefulOutputPin for Output<'_, P>
where
P: OutputPin,
{
fn is_set_high(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_high())
}
fn is_set_low(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_low())
}
}
impl<P> digital::ToggleableOutputPin for Output<'_, P>
where
P: OutputPin,
{
type Error = core::convert::Infallible;
fn toggle(&mut self) -> Result<(), Self::Error> {
self.toggle();
Ok(())
}
}
impl<P> digital::InputPin for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
type Error = core::convert::Infallible;
fn is_high(&self) -> Result<bool, Self::Error> {
Ok(self.pin.is_high())
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(self.pin.is_low())
}
}
impl<P> digital::OutputPin for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
type Error = core::convert::Infallible;
fn set_high(&mut self) -> Result<(), Self::Error> {
self.set_high();
Ok(())
}
fn set_low(&mut self) -> Result<(), Self::Error> {
self.set_low();
Ok(())
}
}
impl<P> digital::StatefulOutputPin for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
fn is_set_high(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_high())
}
fn is_set_low(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_low())
}
}
impl<P> digital::ToggleableOutputPin for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
type Error = core::convert::Infallible;
fn toggle(&mut self) -> Result<(), Self::Error> {
self.toggle();
Ok(())
}
}
impl<P> digital::InputPin for Flex<'_, P>
where
P: InputPin + OutputPin,
{
type Error = core::convert::Infallible;
fn is_high(&self) -> Result<bool, Self::Error> {
Ok(self.is_high())
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(self.is_low())
}
}
impl<P> digital::OutputPin for Flex<'_, P>
where
P: InputPin + OutputPin,
{
type Error = core::convert::Infallible;
fn set_high(&mut self) -> Result<(), Self::Error> {
self.pin.set_output_high(true, private::Internal);
Ok(())
}
fn set_low(&mut self) -> Result<(), Self::Error> {
self.pin.set_output_high(false, private::Internal);
Ok(())
}
}
impl<P> digital::StatefulOutputPin for Flex<'_, P>
where
P: InputPin + OutputPin,
{
fn is_set_high(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_high())
}
fn is_set_low(&self) -> Result<bool, Self::Error> {
Ok(self.is_set_low())
}
}
impl<P> digital::ToggleableOutputPin for Flex<'_, P>
where
P: InputPin + OutputPin,
{
type Error = core::convert::Infallible;
fn toggle(&mut self) -> Result<(), Self::Error> {
self.toggle();
Ok(())
}
}
}
mod embedded_hal_impls {
use embedded_hal::digital;
use super::*;
impl<P> digital::ErrorType for Input<'_, P>
where
P: InputPin,
{
type Error = core::convert::Infallible;
}
impl<P> digital::InputPin for Input<'_, P>
where
P: InputPin,
{
fn is_high(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_high(self))
}
fn is_low(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_low(self))
}
}
impl<P> digital::ErrorType for Output<'_, P>
where
P: OutputPin,
{
type Error = core::convert::Infallible;
}
impl<P> digital::OutputPin for Output<'_, P>
where
P: OutputPin,
{
fn set_low(&mut self) -> Result<(), Self::Error> {
Self::set_low(self);
Ok(())
}
fn set_high(&mut self) -> Result<(), Self::Error> {
Self::set_high(self);
Ok(())
}
}
impl<P> digital::StatefulOutputPin for Output<'_, P>
where
P: OutputPin,
{
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_set_high(self))
}
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_set_low(self))
}
}
impl<P> digital::InputPin for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
fn is_high(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_high(self))
}
fn is_low(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_low(self))
}
}
impl<P> digital::ErrorType for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
type Error = core::convert::Infallible;
}
impl<P> digital::OutputPin for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
fn set_low(&mut self) -> Result<(), Self::Error> {
Self::set_low(self);
Ok(())
}
fn set_high(&mut self) -> Result<(), Self::Error> {
Self::set_high(self);
Ok(())
}
}
impl<P> digital::StatefulOutputPin for OutputOpenDrain<'_, P>
where
P: InputPin + OutputPin,
{
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_set_high(self))
}
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_set_low(self))
}
}
impl<P> digital::InputPin for Flex<'_, P>
where
P: InputPin,
{
fn is_high(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_high(self))
}
fn is_low(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_low(self))
}
}
impl<P> digital::ErrorType for Flex<'_, P> {
type Error = core::convert::Infallible;
}
impl<P> digital::OutputPin for Flex<'_, P>
where
P: OutputPin,
{
fn set_low(&mut self) -> Result<(), Self::Error> {
Self::set_low(self);
Ok(())
}
fn set_high(&mut self) -> Result<(), Self::Error> {
Self::set_high(self);
Ok(())
}
}
impl<P> digital::StatefulOutputPin for Flex<'_, P>
where
P: OutputPin,
{
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_set_high(self))
}
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
Ok(Self::is_set_low(self))
}
}
}
mod embedded_hal_async_impls {
use embedded_hal_async::digital::Wait;
use super::*;
impl<P> Wait for Flex<'_, P>
where
P: InputPin,
{
async fn wait_for_high(&mut self) -> Result<(), Self::Error> {
Self::wait_for_high(self).await;
Ok(())
}
async fn wait_for_low(&mut self) -> Result<(), Self::Error> {
Self::wait_for_low(self).await;
Ok(())
}
async fn wait_for_rising_edge(&mut self) -> Result<(), Self::Error> {
Self::wait_for_rising_edge(self).await;
Ok(())
}
async fn wait_for_falling_edge(&mut self) -> Result<(), Self::Error> {
Self::wait_for_falling_edge(self).await;
Ok(())
}
async fn wait_for_any_edge(&mut self) -> Result<(), Self::Error> {
Self::wait_for_any_edge(self).await;
Ok(())
}
}
impl<P> Wait for Input<'_, P>
where
P: InputPin,
{
async fn wait_for_high(&mut self) -> Result<(), Self::Error> {
Self::wait_for_high(self).await;
Ok(())
}
async fn wait_for_low(&mut self) -> Result<(), Self::Error> {
Self::wait_for_low(self).await;
Ok(())
}
async fn wait_for_rising_edge(&mut self) -> Result<(), Self::Error> {
Self::wait_for_rising_edge(self).await;
Ok(())
}
async fn wait_for_falling_edge(&mut self) -> Result<(), Self::Error> {
Self::wait_for_falling_edge(self).await;
Ok(())
}
async fn wait_for_any_edge(&mut self) -> Result<(), Self::Error> {
Self::wait_for_any_edge(self).await;
Ok(())
}
}
}