esp_hal/i2c/master/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
//! # Inter-Integrated Circuit (I2C) - Master mode
//!
//! ## Overview
//!
//! In this mode, the I2C acts as master and initiates the I2C communication by
//! generating a START condition. Note that only one master is allowed to occupy
//! the bus to access one slave at the same time.
//!
//! ## Configuration
//!
//! Each I2C Master controller is individually configurable, and the usual
//! setting such as frequency, timeout, and SDA/SCL pins can easily be
//! configured.
//!
//! ## Usage
//!
//! The I2C driver implements a number of third-party traits, with the
//! intention of making the HAL inter-compatible with various device drivers
//! from the community, including the [embedded-hal].
//!
//! [embedded-hal]: embedded_hal
use core::marker::PhantomData;
#[cfg(not(esp32))]
use core::{
pin::Pin,
task::{Context, Poll},
};
use embedded_hal::i2c::Operation as EhalOperation;
use enumset::{EnumSet, EnumSetType};
use crate::{
asynch::AtomicWaker,
clock::Clocks,
gpio::{
interconnect::{OutputConnection, PeripheralOutput},
InputSignal,
OutputSignal,
PinGuard,
Pull,
},
interrupt::InterruptHandler,
pac::i2c0::{RegisterBlock, COMD},
peripheral::{Peripheral, PeripheralRef},
peripherals::Interrupt,
private,
system::{PeripheralClockControl, PeripheralGuard},
time::Rate,
Async,
Blocking,
DriverMode,
};
cfg_if::cfg_if! {
if #[cfg(esp32s2)] {
const I2C_LL_INTR_MASK: u32 = 0x1ffff;
} else {
const I2C_LL_INTR_MASK: u32 = 0x3ffff;
}
}
// Chunk writes/reads by this size
#[cfg(any(esp32, esp32s2))]
const I2C_CHUNK_SIZE: usize = 32;
#[cfg(not(any(esp32, esp32s2)))]
const I2C_CHUNK_SIZE: usize = 254;
// on ESP32 there is a chance to get trapped in `wait_for_completion` forever
const MAX_ITERATIONS: u32 = 1_000_000;
/// Representation of I2C address.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum I2cAddress {
/// 7-bit address mode type.
///
/// Note that 7-bit addresses defined by drivers should be specified in
/// **right-aligned** form, e.g. in the range `0x00..=0x7F`.
///
/// For example, a device that has the seven bit address of `0b011_0010`,
/// and therefore is addressed on the wire using:
///
/// * `0b0110010_0` or `0x64` for *writes*
/// * `0b0110010_1` or `0x65` for *reads*
SevenBit(u8),
}
impl From<u8> for I2cAddress {
fn from(value: u8) -> Self {
I2cAddress::SevenBit(value)
}
}
/// I2C SCL timeout period.
///
/// When the level of SCL remains unchanged for more than `timeout` bus
/// clock cycles, the bus goes to idle state.
///
/// Default value is `BusCycles(10)`.
#[doc = ""]
#[cfg_attr(
not(esp32),
doc = "Note that the effective timeout may be longer than the value configured here."
)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, strum::Display)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
// TODO: when supporting interrupts, document that SCL = high also triggers an
// interrupt.
pub enum BusTimeout {
/// Use the maximum timeout value.
Maximum,
/// Disable timeout control.
#[cfg(not(any(esp32, esp32s2)))]
Disabled,
/// Timeout in bus clock cycles.
BusCycles(u32),
}
impl BusTimeout {
fn cycles(&self) -> u32 {
match self {
#[cfg(esp32)]
BusTimeout::Maximum => 0xF_FFFF,
#[cfg(esp32s2)]
BusTimeout::Maximum => 0xFF_FFFF,
#[cfg(not(any(esp32, esp32s2)))]
BusTimeout::Maximum => 0x1F,
#[cfg(not(any(esp32, esp32s2)))]
BusTimeout::Disabled => 1,
BusTimeout::BusCycles(cycles) => *cycles,
}
}
#[cfg(not(esp32))]
fn is_set(&self) -> bool {
matches!(self, BusTimeout::BusCycles(_) | BusTimeout::Maximum)
}
}
/// I2C-specific transmission errors
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Error {
/// The transmission exceeded the FIFO size.
FifoExceeded,
/// The acknowledgment check failed.
AcknowledgeCheckFailed(AcknowledgeCheckFailedReason),
/// A timeout occurred during transmission.
Timeout,
/// The arbitration for the bus was lost.
ArbitrationLost,
/// The execution of the I2C command was incomplete.
ExecutionIncomplete,
/// The number of commands issued exceeded the limit.
CommandNumberExceeded,
/// Zero length read or write operation.
ZeroLengthInvalid,
}
/// I2C no acknowledge error reason.
///
/// Consider this as a hint and make sure to always handle all cases.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum AcknowledgeCheckFailedReason {
/// The device did not acknowledge its address. The device may be missing.
Address,
/// The device did not acknowledge the data. It may not be ready to process
/// requests at the moment.
Data,
/// Either the device did not acknowledge its address or the data, but it is
/// unknown which.
Unknown,
}
impl core::fmt::Display for AcknowledgeCheckFailedReason {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
AcknowledgeCheckFailedReason::Address => write!(f, "Address"),
AcknowledgeCheckFailedReason::Data => write!(f, "Data"),
AcknowledgeCheckFailedReason::Unknown => write!(f, "Unknown"),
}
}
}
impl From<&AcknowledgeCheckFailedReason> for embedded_hal::i2c::NoAcknowledgeSource {
fn from(value: &AcknowledgeCheckFailedReason) -> Self {
match value {
AcknowledgeCheckFailedReason::Address => {
embedded_hal::i2c::NoAcknowledgeSource::Address
}
AcknowledgeCheckFailedReason::Data => embedded_hal::i2c::NoAcknowledgeSource::Data,
AcknowledgeCheckFailedReason::Unknown => {
embedded_hal::i2c::NoAcknowledgeSource::Unknown
}
}
}
}
impl core::error::Error for Error {}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::FifoExceeded => write!(f, "The transmission exceeded the FIFO size"),
Error::AcknowledgeCheckFailed(reason) => {
write!(f, "The acknowledgment check failed. Reason: {}", reason)
}
Error::Timeout => write!(f, "A timeout occurred during transmission"),
Error::ArbitrationLost => write!(f, "The arbitration for the bus was lost"),
Error::ExecutionIncomplete => {
write!(f, "The execution of the I2C command was incomplete")
}
Error::CommandNumberExceeded => {
write!(f, "The number of commands issued exceeded the limit")
}
Error::ZeroLengthInvalid => write!(f, "Zero length read or write operation"),
}
}
}
/// I2C-specific configuration errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum ConfigError {
/// Provided bus frequency is invalid for the current configuration.
FrequencyInvalid,
/// Provided timeout is invalid for the current configuration.
TimeoutInvalid,
}
impl core::error::Error for ConfigError {}
impl core::fmt::Display for ConfigError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ConfigError::FrequencyInvalid => write!(
f,
"Provided bus frequency is invalid for the current configuration"
),
ConfigError::TimeoutInvalid => write!(
f,
"Provided timeout is invalid for the current configuration"
),
}
}
}
// This enum is used to keep track of the last/next operation that was/will be
// performed in an embedded-hal(-async) I2c::transaction. It is used to
// determine whether a START condition should be issued at the start of the
// current operation and whether a read needs an ack or a nack for the final
// byte.
#[derive(PartialEq)]
enum OpKind {
Write,
Read,
}
/// I2C operation.
///
/// Several operations can be combined as part of a transaction.
#[derive(Debug, PartialEq, Eq, Hash, strum::Display)]
pub enum Operation<'a> {
/// Write data from the provided buffer.
Write(&'a [u8]),
/// Read data into the provided buffer.
Read(&'a mut [u8]),
}
impl<'a, 'b> From<&'a mut embedded_hal::i2c::Operation<'b>> for Operation<'a> {
fn from(value: &'a mut embedded_hal::i2c::Operation<'b>) -> Self {
match value {
embedded_hal::i2c::Operation::Write(buffer) => Operation::Write(buffer),
embedded_hal::i2c::Operation::Read(buffer) => Operation::Read(buffer),
}
}
}
impl<'a, 'b> From<&'a mut Operation<'b>> for Operation<'a> {
fn from(value: &'a mut Operation<'b>) -> Self {
match value {
Operation::Write(buffer) => Operation::Write(buffer),
Operation::Read(buffer) => Operation::Read(buffer),
}
}
}
impl Operation<'_> {
fn is_write(&self) -> bool {
matches!(self, Operation::Write(_))
}
fn kind(&self) -> OpKind {
match self {
Operation::Write(_) => OpKind::Write,
Operation::Read(_) => OpKind::Read,
}
}
fn is_empty(&self) -> bool {
match self {
Operation::Write(buffer) => buffer.is_empty(),
Operation::Read(buffer) => buffer.is_empty(),
}
}
}
impl embedded_hal::i2c::Error for Error {
fn kind(&self) -> embedded_hal::i2c::ErrorKind {
use embedded_hal::i2c::ErrorKind;
match self {
Self::FifoExceeded => ErrorKind::Overrun,
Self::ArbitrationLost => ErrorKind::ArbitrationLoss,
Self::AcknowledgeCheckFailed(reason) => ErrorKind::NoAcknowledge(reason.into()),
_ => ErrorKind::Other,
}
}
}
/// A generic I2C Command
#[cfg_attr(feature = "debug", derive(Debug))]
enum Command {
Start,
Stop,
End,
Write {
/// This bit is to set an expected ACK value for the transmitter.
ack_exp: Ack,
/// Enables checking the ACK value received against the ack_exp value.
ack_check_en: bool,
/// Length of data (in bytes) to be written. The maximum length is 255,
/// while the minimum is 1.
length: u8,
},
Read {
/// Indicates whether the receiver will send an ACK after this byte has
/// been received.
ack_value: Ack,
/// Length of data (in bytes) to be read. The maximum length is 255,
/// while the minimum is 1.
length: u8,
},
}
enum OperationType {
Write = 0,
Read = 1,
}
#[derive(Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
enum Ack {
Ack = 0,
Nack = 1,
}
impl From<u32> for Ack {
fn from(ack: u32) -> Self {
match ack {
0 => Ack::Ack,
1 => Ack::Nack,
_ => unreachable!(),
}
}
}
impl From<Ack> for u32 {
fn from(ack: Ack) -> u32 {
ack as u32
}
}
/// I2C driver configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct Config {
/// The I2C clock frequency.
frequency: Rate,
/// I2C SCL timeout period.
timeout: BusTimeout,
}
impl Default for Config {
fn default() -> Self {
Config {
frequency: Rate::from_khz(100),
timeout: BusTimeout::BusCycles(10),
}
}
}
/// I2C driver
///
/// ### I2C initialization and communication with the device
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::i2c::master::{Config, I2c};
/// # const DEVICE_ADDR: u8 = 0x77;
/// let mut i2c = I2c::new(
/// peripherals.I2C0,
/// Config::default(),
/// )?
/// .with_sda(peripherals.GPIO1)
/// .with_scl(peripherals.GPIO2);
///
/// let mut data = [0u8; 22];
/// i2c.write_read(DEVICE_ADDR, &[0xaa], &mut data)?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct I2c<'d, Dm: DriverMode> {
i2c: PeripheralRef<'d, AnyI2c>,
phantom: PhantomData<Dm>,
config: Config,
guard: PeripheralGuard,
sda_pin: PinGuard,
scl_pin: PinGuard,
}
#[instability::unstable]
impl<Dm: DriverMode> embassy_embedded_hal::SetConfig for I2c<'_, Dm> {
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
impl<Dm: DriverMode> embedded_hal::i2c::ErrorType for I2c<'_, Dm> {
type Error = Error;
}
impl<Dm: DriverMode> embedded_hal::i2c::I2c for I2c<'_, Dm> {
fn transaction(
&mut self,
address: u8,
operations: &mut [embedded_hal::i2c::Operation<'_>],
) -> Result<(), Self::Error> {
self.transaction_impl(
I2cAddress::SevenBit(address),
operations.iter_mut().map(Operation::from),
)
.inspect_err(|_| self.internal_recover())
}
}
impl<'d, Dm> I2c<'d, Dm>
where
Dm: DriverMode,
{
fn driver(&self) -> Driver<'_> {
Driver {
info: self.i2c.info(),
state: self.i2c.state(),
}
}
fn internal_recover(&self) {
PeripheralClockControl::disable(self.driver().info.peripheral);
PeripheralClockControl::enable(self.driver().info.peripheral);
PeripheralClockControl::reset(self.driver().info.peripheral);
// We know the configuration is valid, we can ignore the result.
_ = self.driver().setup(&self.config);
}
/// Applies a new configuration.
///
/// # Errors
///
/// A [`ConfigError`] variant will be returned if bus frequency or timeout
/// passed in config is invalid.
pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.driver().setup(config)?;
self.config = *config;
Ok(())
}
fn transaction_impl<'a>(
&mut self,
address: I2cAddress,
operations: impl Iterator<Item = Operation<'a>>,
) -> Result<(), Error> {
let mut last_op: Option<OpKind> = None;
// filter out 0 length read operations
let mut op_iter = operations
.filter(|op| op.is_write() || !op.is_empty())
.peekable();
while let Some(op) = op_iter.next() {
let next_op = op_iter.peek().map(|v| v.kind());
let kind = op.kind();
match op {
Operation::Write(buffer) => {
// execute a write operation:
// - issue START/RSTART if op is different from previous
// - issue STOP if op is the last one
self.driver().write_blocking(
address,
buffer,
!matches!(last_op, Some(OpKind::Write)),
next_op.is_none(),
)?;
}
Operation::Read(buffer) => {
// execute a read operation:
// - issue START/RSTART if op is different from previous
// - issue STOP if op is the last one
// - will_continue is true if there is another read operation next
self.driver().read_blocking(
address,
buffer,
!matches!(last_op, Some(OpKind::Read)),
next_op.is_none(),
matches!(next_op, Some(OpKind::Read)),
)?;
}
}
last_op = Some(kind);
}
Ok(())
}
/// Connect a pin to the I2C SDA signal.
///
/// This will replace previous pin assignments for this signal.
pub fn with_sda(mut self, sda: impl Peripheral<P = impl PeripheralOutput> + 'd) -> Self {
let info = self.driver().info;
let input = info.sda_input;
let output = info.sda_output;
Self::connect_pin(sda, input, output, &mut self.sda_pin);
self
}
/// Connect a pin to the I2C SCL signal.
///
/// This will replace previous pin assignments for this signal.
pub fn with_scl(mut self, scl: impl Peripheral<P = impl PeripheralOutput> + 'd) -> Self {
let info = self.driver().info;
let input = info.scl_input;
let output = info.scl_output;
Self::connect_pin(scl, input, output, &mut self.scl_pin);
self
}
fn connect_pin(
pin: impl Peripheral<P = impl PeripheralOutput> + 'd,
input: InputSignal,
output: OutputSignal,
guard: &mut PinGuard,
) {
crate::into_mapped_ref!(pin);
// avoid the pin going low during configuration
pin.set_output_high(true);
pin.set_to_open_drain_output();
pin.enable_input(true);
pin.pull_direction(Pull::Up);
input.connect_to(pin.reborrow());
*guard = OutputConnection::connect_with_guard(pin, output);
}
/// Writes bytes to slave with address `address`
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::i2c::master::{Config, I2c};
/// # let mut i2c = I2c::new(
/// # peripherals.I2C0,
/// # Config::default(),
/// # )?;
/// # const DEVICE_ADDR: u8 = 0x77;
/// i2c.write(DEVICE_ADDR, &[0xaa])?;
/// # Ok(())
/// # }
/// ```
pub fn write<A: Into<I2cAddress>>(&mut self, address: A, buffer: &[u8]) -> Result<(), Error> {
self.driver()
.write_blocking(address.into(), buffer, true, true)
.inspect_err(|_| self.internal_recover())
}
/// Reads enough bytes from slave with `address` to fill `buffer`
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::i2c::master::{Config, I2c};
/// # let mut i2c = I2c::new(
/// # peripherals.I2C0,
/// # Config::default(),
/// # )?;
/// # const DEVICE_ADDR: u8 = 0x77;
/// let mut data = [0u8; 22];
/// i2c.read(DEVICE_ADDR, &mut data)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// The corresponding error variant from [`Error`] will be returned if the passed buffer has zero length.
pub fn read<A: Into<I2cAddress>>(
&mut self,
address: A,
buffer: &mut [u8],
) -> Result<(), Error> {
self.driver()
.read_blocking(address.into(), buffer, true, true, false)
.inspect_err(|_| self.internal_recover())
}
/// Writes bytes to slave with address `address` and then reads enough bytes
/// to fill `buffer` *in a single transaction*
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::i2c::master::{Config, I2c};
/// # let mut i2c = I2c::new(
/// # peripherals.I2C0,
/// # Config::default(),
/// # )?;
/// # const DEVICE_ADDR: u8 = 0x77;
/// let mut data = [0u8; 22];
/// i2c.write_read(DEVICE_ADDR, &[0xaa], &mut data)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// The corresponding error variant from [`Error`] will be returned if the passed buffer has zero length.
pub fn write_read<A: Into<I2cAddress>>(
&mut self,
address: A,
write_buffer: &[u8],
read_buffer: &mut [u8],
) -> Result<(), Error> {
let address = address.into();
self.driver()
.write_blocking(address, write_buffer, true, read_buffer.is_empty())
.inspect_err(|_| self.internal_recover())?;
self.driver()
.read_blocking(address, read_buffer, true, true, false)
.inspect_err(|_| self.internal_recover())?;
Ok(())
}
/// Execute the provided operations on the I2C bus.
///
/// Transaction contract:
/// - Before executing the first operation an ST is sent automatically. This
/// is followed by SAD+R/W as appropriate.
/// - Data from adjacent operations of the same type are sent after each
/// other without an SP or SR.
/// - Between adjacent operations of a different type an SR and SAD+R/W is
/// sent.
/// - After executing the last operation an SP is sent automatically.
/// - If the last operation is a `Read` the master does not send an
/// acknowledge for the last byte.
///
/// - `ST` = start condition
/// - `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0
/// to indicate writing
/// - `SR` = repeated start condition
/// - `SP` = stop condition
///
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::i2c::master::{Config, I2c, Operation};
/// # let mut i2c = I2c::new(
/// # peripherals.I2C0,
/// # Config::default(),
/// # )?;
/// # const DEVICE_ADDR: u8 = 0x77;
/// let mut data = [0u8; 22];
/// i2c.transaction(
/// DEVICE_ADDR,
/// &mut [Operation::Write(&[0xaa]), Operation::Read(&mut data)]
/// )?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// The corresponding error variant from [`Error`] will be returned if the buffer passed to an [`Operation`] has zero length.
pub fn transaction<'a, A: Into<I2cAddress>>(
&mut self,
address: A,
operations: impl IntoIterator<Item = &'a mut Operation<'a>>,
) -> Result<(), Error> {
self.transaction_impl(address.into(), operations.into_iter().map(Operation::from))
.inspect_err(|_| self.internal_recover())
}
}
impl<'d> I2c<'d, Blocking> {
/// Create a new I2C instance.
///
/// # Errors
///
/// A [`ConfigError`] variant will be returned if bus frequency or timeout
/// passed in config is invalid.
pub fn new(
i2c: impl Peripheral<P = impl Instance> + 'd,
config: Config,
) -> Result<Self, ConfigError> {
crate::into_mapped_ref!(i2c);
let guard = PeripheralGuard::new(i2c.info().peripheral);
let sda_pin = PinGuard::new_unconnected(i2c.info().sda_output);
let scl_pin = PinGuard::new_unconnected(i2c.info().scl_output);
let i2c = I2c {
i2c,
phantom: PhantomData,
config,
guard,
sda_pin,
scl_pin,
};
i2c.driver().setup(&i2c.config)?;
Ok(i2c)
}
#[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 = ""]
/// Note that this will replace any previously registered interrupt
/// handlers.
///
/// You can restore the default/unhandled interrupt handler by using
/// [crate::DEFAULT_INTERRUPT_HANDLER]
///
/// # Panics
///
/// Panics if passed interrupt handler is invalid (e.g. has priority
/// `None`)
#[instability::unstable]
pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
self.i2c.info().set_interrupt_handler(handler);
}
/// Listen for the given interrupts
#[instability::unstable]
pub fn listen(&mut self, interrupts: impl Into<EnumSet<Event>>) {
self.i2c.info().enable_listen(interrupts.into(), true)
}
/// Unlisten the given interrupts
#[instability::unstable]
pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<Event>>) {
self.i2c.info().enable_listen(interrupts.into(), false)
}
/// Gets asserted interrupts
#[instability::unstable]
pub fn interrupts(&mut self) -> EnumSet<Event> {
self.i2c.info().interrupts()
}
/// Resets asserted interrupts
#[instability::unstable]
pub fn clear_interrupts(&mut self, interrupts: EnumSet<Event>) {
self.i2c.info().clear_interrupts(interrupts)
}
/// Configures the I2C peripheral to operate in asynchronous mode.
pub fn into_async(mut self) -> I2c<'d, Async> {
self.set_interrupt_handler(self.driver().info.async_handler);
I2c {
i2c: self.i2c,
phantom: PhantomData,
config: self.config,
guard: self.guard,
sda_pin: self.sda_pin,
scl_pin: self.scl_pin,
}
}
}
impl private::Sealed for I2c<'_, Blocking> {}
#[instability::unstable]
impl crate::interrupt::InterruptConfigurable for I2c<'_, Blocking> {
fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
self.i2c.info().set_interrupt_handler(handler);
}
}
#[cfg_attr(esp32, allow(dead_code))]
#[derive(Debug, EnumSetType)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
#[instability::unstable]
pub enum Event {
/// Triggered when op_code of the master indicates an END command and an END
/// condition is detected.
EndDetect,
/// Triggered when the I2C controller detects a STOP bit.
TxComplete,
/// Triggered when the TX FIFO watermark check is enabled and the TX fifo
/// falls below the configured watermark.
#[cfg(not(any(esp32, esp32s2)))]
TxFifoWatermark,
}
#[cfg(not(esp32))]
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct I2cFuture<'a> {
event: Event,
info: &'a Info,
state: &'a State,
}
#[cfg(not(esp32))]
impl<'a> I2cFuture<'a> {
pub fn new(event: Event, info: &'a Info, state: &'a State) -> Self {
info.regs().int_ena().modify(|_, w| {
let w = match event {
Event::EndDetect => w.end_detect().set_bit(),
Event::TxComplete => w.trans_complete().set_bit(),
#[cfg(not(any(esp32, esp32s2)))]
Event::TxFifoWatermark => w.txfifo_wm().set_bit(),
};
w.arbitration_lost().set_bit();
w.time_out().set_bit();
w.nack().set_bit();
w
});
Self { event, state, info }
}
fn event_bit_is_clear(&self) -> bool {
let r = self.info.regs().int_ena().read();
match self.event {
Event::EndDetect => r.end_detect().bit_is_clear(),
Event::TxComplete => r.trans_complete().bit_is_clear(),
#[cfg(not(any(esp32, esp32s2)))]
Event::TxFifoWatermark => r.txfifo_wm().bit_is_clear(),
}
}
fn check_error(&self) -> Result<(), Error> {
let r = self.info.regs().int_raw().read();
if r.arbitration_lost().bit_is_set() {
return Err(Error::ArbitrationLost);
}
if r.time_out().bit_is_set() {
return Err(Error::Timeout);
}
if r.nack().bit_is_set() {
return Err(Error::AcknowledgeCheckFailed(estimate_ack_failed_reason(
self.info.regs(),
)));
}
#[cfg(not(esp32))]
if r.trans_complete().bit_is_set() && self.info.regs().sr().read().resp_rec().bit_is_clear()
{
return Err(Error::AcknowledgeCheckFailed(
AcknowledgeCheckFailedReason::Data,
));
}
Ok(())
}
}
#[cfg(not(esp32))]
impl core::future::Future for I2cFuture<'_> {
type Output = Result<(), Error>;
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
self.state.waker.register(ctx.waker());
let error = self.check_error();
if error.is_err() {
return Poll::Ready(error);
}
if self.event_bit_is_clear() {
Poll::Ready(Ok(()))
} else {
Poll::Pending
}
}
}
impl<'d> I2c<'d, Async> {
/// Configure the I2C peripheral to operate in blocking mode.
pub fn into_blocking(self) -> I2c<'d, Blocking> {
self.i2c.info().disable_interrupts();
I2c {
i2c: self.i2c,
phantom: PhantomData,
config: self.config,
guard: self.guard,
sda_pin: self.sda_pin,
scl_pin: self.scl_pin,
}
}
/// Writes bytes to slave with address `address`
pub async fn write_async<A: Into<I2cAddress>>(
&mut self,
address: A,
buffer: &[u8],
) -> Result<(), Error> {
self.driver()
.write(address.into(), buffer, true, true)
.await
.inspect_err(|_| self.internal_recover())
}
/// Reads enough bytes from slave with `address` to fill `buffer`
///
/// # Errors
///
/// The corresponding error variant from [`Error`] will be returned if the
/// passed buffer has zero length.
pub async fn read_async<A: Into<I2cAddress>>(
&mut self,
address: A,
buffer: &mut [u8],
) -> Result<(), Error> {
self.driver()
.read(address.into(), buffer, true, true, false)
.await
.inspect_err(|_| self.internal_recover())
}
/// Writes bytes to slave with address `address` and then reads enough
/// bytes to fill `buffer` *in a single transaction*
///
/// # Errors
///
/// The corresponding error variant from [`Error`] will be returned if the
/// passed buffer has zero length.
pub async fn write_read_async<A: Into<I2cAddress>>(
&mut self,
address: A,
write_buffer: &[u8],
read_buffer: &mut [u8],
) -> Result<(), Error> {
let address = address.into();
self.driver()
.write(address, write_buffer, true, read_buffer.is_empty())
.await
.inspect_err(|_| self.internal_recover())?;
self.driver()
.read(address, read_buffer, true, true, false)
.await
.inspect_err(|_| self.internal_recover())?;
Ok(())
}
/// Execute the provided operations on the I2C bus as a single
/// transaction.
///
/// Transaction contract:
/// - Before executing the first operation an ST is sent automatically. This
/// is followed by SAD+R/W as appropriate.
/// - Data from adjacent operations of the same type are sent after each
/// other without an SP or SR.
/// - Between adjacent operations of a different type an SR and SAD+R/W is
/// sent.
/// - After executing the last operation an SP is sent automatically.
/// - If the last operation is a `Read` the master does not send an
/// acknowledge for the last byte.
///
/// - `ST` = start condition
/// - `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0
/// to indicate writing
/// - `SR` = repeated start condition
/// - `SP` = stop condition
///
/// # Errors
///
/// The corresponding error variant from [`Error`] will be returned if the
/// buffer passed to an [`Operation`] has zero length.
pub async fn transaction_async<'a, A: Into<I2cAddress>>(
&mut self,
address: A,
operations: impl IntoIterator<Item = &'a mut Operation<'a>>,
) -> Result<(), Error> {
self.transaction_impl_async(address.into(), operations.into_iter().map(Operation::from))
.await
.inspect_err(|_| self.internal_recover())
}
async fn transaction_impl_async<'a>(
&mut self,
address: I2cAddress,
operations: impl Iterator<Item = Operation<'a>>,
) -> Result<(), Error> {
let mut last_op: Option<OpKind> = None;
// filter out 0 length read operations
let mut op_iter = operations
.filter(|op| op.is_write() || !op.is_empty())
.peekable();
while let Some(op) = op_iter.next() {
let next_op = op_iter.peek().map(|v| v.kind());
let kind = op.kind();
match op {
Operation::Write(buffer) => {
// execute a write operation:
// - issue START/RSTART if op is different from previous
// - issue STOP if op is the last one
self.driver()
.write(
address,
buffer,
!matches!(last_op, Some(OpKind::Write)),
next_op.is_none(),
)
.await?;
}
Operation::Read(buffer) => {
// execute a read operation:
// - issue START/RSTART if op is different from previous
// - issue STOP if op is the last one
// - will_continue is true if there is another read operation next
self.driver()
.read(
address,
buffer,
!matches!(last_op, Some(OpKind::Read)),
next_op.is_none(),
matches!(next_op, Some(OpKind::Read)),
)
.await?;
}
}
last_op = Some(kind);
}
Ok(())
}
}
impl embedded_hal_async::i2c::I2c for I2c<'_, Async> {
async fn transaction(
&mut self,
address: u8,
operations: &mut [EhalOperation<'_>],
) -> Result<(), Self::Error> {
self.transaction_impl_async(address.into(), operations.iter_mut().map(Operation::from))
.await
.inspect_err(|_| self.internal_recover())
}
}
fn async_handler(info: &Info, state: &State) {
let regs = info.regs();
regs.int_ena().modify(|_, w| {
w.end_detect().clear_bit();
w.trans_complete().clear_bit();
w.arbitration_lost().clear_bit();
w.time_out().clear_bit();
#[cfg(not(any(esp32, esp32s2)))]
w.txfifo_wm().clear_bit();
w.nack().clear_bit()
});
state.waker.wake();
}
/// Sets the filter with a supplied threshold in clock cycles for which a
/// pulse must be present to pass the filter
fn set_filter(
register_block: &RegisterBlock,
sda_threshold: Option<u8>,
scl_threshold: Option<u8>,
) {
cfg_if::cfg_if! {
if #[cfg(any(esp32, esp32s2))] {
register_block.sda_filter_cfg().modify(|_, w| {
if let Some(threshold) = sda_threshold {
unsafe { w.sda_filter_thres().bits(threshold) };
}
w.sda_filter_en().bit(sda_threshold.is_some())
});
register_block.scl_filter_cfg().modify(|_, w| {
if let Some(threshold) = scl_threshold {
unsafe { w.scl_filter_thres().bits(threshold) };
}
w.scl_filter_en().bit(scl_threshold.is_some())
});
} else {
register_block.filter_cfg().modify(|_, w| {
if let Some(threshold) = sda_threshold {
unsafe { w.sda_filter_thres().bits(threshold) };
}
if let Some(threshold) = scl_threshold {
unsafe { w.scl_filter_thres().bits(threshold) };
}
w.sda_filter_en().bit(sda_threshold.is_some());
w.scl_filter_en().bit(scl_threshold.is_some())
});
}
}
}
#[allow(clippy::too_many_arguments, unused)]
/// Configures the clock and timing parameters for the I2C peripheral.
fn configure_clock(
register_block: &RegisterBlock,
sclk_div: u32,
scl_low_period: u32,
scl_high_period: u32,
scl_wait_high_period: u32,
sda_hold_time: u32,
sda_sample_time: u32,
scl_rstart_setup_time: u32,
scl_stop_setup_time: u32,
scl_start_hold_time: u32,
scl_stop_hold_time: u32,
timeout: BusTimeout,
) -> Result<(), ConfigError> {
unsafe {
// divider
#[cfg(any(esp32c2, esp32c3, esp32c6, esp32h2, esp32s3))]
register_block.clk_conf().modify(|_, w| {
w.sclk_sel().clear_bit();
w.sclk_div_num().bits((sclk_div - 1) as u8)
});
// scl period
register_block
.scl_low_period()
.write(|w| w.scl_low_period().bits(scl_low_period as u16));
#[cfg(not(esp32))]
let scl_wait_high_period = scl_wait_high_period
.try_into()
.map_err(|_| ConfigError::FrequencyInvalid)?;
register_block.scl_high_period().write(|w| {
#[cfg(not(esp32))] // ESP32 does not have a wait_high field
w.scl_wait_high_period().bits(scl_wait_high_period);
w.scl_high_period().bits(scl_high_period as u16)
});
// sda sample
register_block
.sda_hold()
.write(|w| w.time().bits(sda_hold_time as u16));
register_block
.sda_sample()
.write(|w| w.time().bits(sda_sample_time as u16));
// setup
register_block
.scl_rstart_setup()
.write(|w| w.time().bits(scl_rstart_setup_time as u16));
register_block
.scl_stop_setup()
.write(|w| w.time().bits(scl_stop_setup_time as u16));
// hold
register_block
.scl_start_hold()
.write(|w| w.time().bits(scl_start_hold_time as u16));
register_block
.scl_stop_hold()
.write(|w| w.time().bits(scl_stop_hold_time as u16));
// The ESP32 variant does not have an enable flag for the
// timeout mechanism
cfg_if::cfg_if! {
if #[cfg(esp32)] {
register_block
.to()
.write(|w| w.time_out().bits(timeout.cycles()));
} else {
register_block
.to()
.write(|w| w.time_out_en().bit(timeout.is_set())
.time_out_value()
.bits(timeout.cycles() as _)
);
}
}
}
Ok(())
}
/// Peripheral data describing a particular I2C instance.
#[doc(hidden)]
#[derive(Debug)]
#[non_exhaustive]
pub struct Info {
/// Pointer to the register block for this I2C instance.
///
/// Use [Self::register_block] to access the register block.
pub register_block: *const RegisterBlock,
/// System peripheral marker.
pub peripheral: crate::system::Peripheral,
/// Interrupt handler for the asynchronous operations of this I2C instance.
pub async_handler: InterruptHandler,
/// Interrupt for this I2C instance.
pub interrupt: Interrupt,
/// SCL output signal.
pub scl_output: OutputSignal,
/// SCL input signal.
pub scl_input: InputSignal,
/// SDA output signal.
pub sda_output: OutputSignal,
/// SDA input signal.
pub sda_input: InputSignal,
}
impl Info {
/// Returns the register block for this I2C instance.
pub fn regs(&self) -> &RegisterBlock {
unsafe { &*self.register_block }
}
/// Listen for the given interrupts
fn enable_listen(&self, interrupts: EnumSet<Event>, enable: bool) {
let reg_block = self.regs();
reg_block.int_ena().modify(|_, w| {
for interrupt in interrupts {
match interrupt {
Event::EndDetect => w.end_detect().bit(enable),
Event::TxComplete => w.trans_complete().bit(enable),
#[cfg(not(any(esp32, esp32s2)))]
Event::TxFifoWatermark => w.txfifo_wm().bit(enable),
};
}
w
});
}
fn interrupts(&self) -> EnumSet<Event> {
let mut res = EnumSet::new();
let reg_block = self.regs();
let ints = reg_block.int_raw().read();
if ints.end_detect().bit_is_set() {
res.insert(Event::EndDetect);
}
if ints.trans_complete().bit_is_set() {
res.insert(Event::TxComplete);
}
#[cfg(not(any(esp32, esp32s2)))]
if ints.txfifo_wm().bit_is_set() {
res.insert(Event::TxFifoWatermark);
}
res
}
fn clear_interrupts(&self, interrupts: EnumSet<Event>) {
let reg_block = self.regs();
reg_block.int_clr().write(|w| {
for interrupt in interrupts {
match interrupt {
Event::EndDetect => w.end_detect().clear_bit_by_one(),
Event::TxComplete => w.trans_complete().clear_bit_by_one(),
#[cfg(not(any(esp32, esp32s2)))]
Event::TxFifoWatermark => w.txfifo_wm().clear_bit_by_one(),
};
}
w
});
}
fn set_interrupt_handler(&self, handler: InterruptHandler) {
for core in crate::system::Cpu::other() {
crate::interrupt::disable(core, self.interrupt);
}
self.enable_listen(EnumSet::all(), false);
self.clear_interrupts(EnumSet::all());
unsafe { crate::interrupt::bind_interrupt(self.interrupt, handler.handler()) };
unwrap!(crate::interrupt::enable(self.interrupt, handler.priority()));
}
fn disable_interrupts(&self) {
crate::interrupt::disable(crate::system::Cpu::current(), self.interrupt);
}
}
impl PartialEq for Info {
fn eq(&self, other: &Self) -> bool {
self.register_block == other.register_block
}
}
unsafe impl Sync for Info {}
#[allow(dead_code)] // Some versions don't need `state`
struct Driver<'a> {
info: &'a Info,
state: &'a State,
}
impl Driver<'_> {
fn regs(&self) -> &RegisterBlock {
self.info.regs()
}
/// Configures the I2C peripheral with the specified frequency, clocks, and
/// optional timeout.
fn setup(&self, config: &Config) -> Result<(), ConfigError> {
self.regs().ctr().write(|w| {
// Set I2C controller to master mode
w.ms_mode().set_bit();
// Use open drain output for SDA and SCL
w.sda_force_out().set_bit();
w.scl_force_out().set_bit();
// Use Most Significant Bit first for sending and receiving data
w.tx_lsb_first().clear_bit();
w.rx_lsb_first().clear_bit();
// Ensure that clock is enabled
w.clk_en().set_bit()
});
#[cfg(esp32s2)]
self.regs().ctr().modify(|_, w| w.ref_always_on().set_bit());
// Configure filter
// FIXME if we ever change this we need to adapt `set_frequency` for ESP32
set_filter(self.regs(), Some(7), Some(7));
// Configure frequency
self.set_frequency(config, config.timeout)?;
self.update_config();
// Reset entire peripheral (also resets fifo)
self.reset();
Ok(())
}
/// Resets the I2C controller (FIFO + FSM + command list)
fn reset(&self) {
// Reset the FSM
// (the option to reset the FSM is not available
// for the ESP32)
#[cfg(not(esp32))]
self.regs().ctr().modify(|_, w| w.fsm_rst().set_bit());
// Clear all I2C interrupts
self.regs()
.int_clr()
.write(|w| unsafe { w.bits(I2C_LL_INTR_MASK) });
// Reset fifo
self.reset_fifo();
// Reset the command list
self.reset_command_list();
}
/// Resets the I2C peripheral's command registers
fn reset_command_list(&self) {
// Confirm that all commands that were configured were actually executed
for cmd in self.regs().comd_iter() {
cmd.reset();
}
}
#[cfg(esp32)]
/// Sets the frequency of the I2C interface by calculating and applying the
/// associated timings - corresponds to i2c_ll_cal_bus_clk and
/// i2c_ll_set_bus_timing in ESP-IDF
fn set_frequency(&self, clock_config: &Config, timeout: BusTimeout) -> Result<(), ConfigError> {
let clocks = Clocks::get();
let source_clk = clocks.i2c_clock.as_hz();
let bus_freq = clock_config.frequency.as_hz();
let half_cycle: u32 = source_clk / bus_freq / 2;
let scl_low = half_cycle;
let scl_high = half_cycle;
let sda_hold = half_cycle / 2;
let sda_sample = scl_high / 2;
let setup = half_cycle;
let hold = half_cycle;
let timeout = BusTimeout::BusCycles(match timeout {
BusTimeout::Maximum => 0xF_FFFF,
BusTimeout::BusCycles(cycles) => check_timeout(cycles * 2 * half_cycle, 0xF_FFFF)?,
});
// SCL period. According to the TRM, we should always subtract 1 to SCL low
// period
let scl_low = scl_low - 1;
// Still according to the TRM, if filter is not enbled, we have to subtract 7,
// if SCL filter is enabled, we have to subtract:
// 8 if SCL filter is between 0 and 2 (included)
// 6 + SCL threshold if SCL filter is between 3 and 7 (included)
// to SCL high period
let mut scl_high = scl_high;
// In the "worst" case, we will subtract 13, make sure the result will still be
// correct
// FIXME since we always set the filter threshold to 7 we don't need conditional
// code here once that changes we need the conditional code here
scl_high -= 7 + 6;
// if (filter_cfg_en) {
// if (thres <= 2) {
// scl_high -= 8;
// } else {
// assert(hw->scl_filter_cfg.thres <= 7);
// scl_high -= thres + 6;
// }
// } else {
// scl_high -= 7;
//}
let scl_high_period = scl_high;
let scl_low_period = scl_low;
// sda sample
let sda_hold_time = sda_hold;
let sda_sample_time = sda_sample;
// setup
let scl_rstart_setup_time = setup;
let scl_stop_setup_time = setup;
// hold
let scl_start_hold_time = hold;
let scl_stop_hold_time = hold;
configure_clock(
self.regs(),
0,
scl_low_period,
scl_high_period,
0,
sda_hold_time,
sda_sample_time,
scl_rstart_setup_time,
scl_stop_setup_time,
scl_start_hold_time,
scl_stop_hold_time,
timeout,
)?;
Ok(())
}
#[cfg(esp32s2)]
/// Sets the frequency of the I2C interface by calculating and applying the
/// associated timings - corresponds to i2c_ll_cal_bus_clk and
/// i2c_ll_set_bus_timing in ESP-IDF
fn set_frequency(&self, clock_config: &Config, timeout: BusTimeout) -> Result<(), ConfigError> {
let clocks = Clocks::get();
let source_clk = clocks.apb_clock.as_hz();
let bus_freq = clock_config.frequency.as_hz();
let half_cycle: u32 = source_clk / bus_freq / 2;
// SCL
let scl_low = half_cycle;
// default, scl_wait_high < scl_high
let scl_high = half_cycle / 2 + 2;
let scl_wait_high = half_cycle - scl_high;
let sda_hold = half_cycle / 2;
// scl_wait_high < sda_sample <= scl_high
let sda_sample = half_cycle / 2 - 1;
let setup = half_cycle;
let hold = half_cycle;
// scl period
let scl_low_period = scl_low - 1;
let scl_high_period = scl_high;
let scl_wait_high_period = scl_wait_high;
// sda sample
let sda_hold_time = sda_hold;
let sda_sample_time = sda_sample;
// setup
let scl_rstart_setup_time = setup;
let scl_stop_setup_time = setup;
// hold
let scl_start_hold_time = hold - 1;
let scl_stop_hold_time = hold;
let timeout = BusTimeout::BusCycles(match timeout {
BusTimeout::Maximum => 0xFF_FFFF,
BusTimeout::BusCycles(cycles) => check_timeout(cycles * 2 * half_cycle, 0xFF_FFFF)?,
});
configure_clock(
self.regs(),
0,
scl_low_period,
scl_high_period,
scl_wait_high_period,
sda_hold_time,
sda_sample_time,
scl_rstart_setup_time,
scl_stop_setup_time,
scl_start_hold_time,
scl_stop_hold_time,
timeout,
)?;
Ok(())
}
#[cfg(any(esp32c2, esp32c3, esp32c6, esp32h2, esp32s3))]
/// Sets the frequency of the I2C interface by calculating and applying the
/// associated timings - corresponds to i2c_ll_cal_bus_clk and
/// i2c_ll_set_bus_timing in ESP-IDF
fn set_frequency(&self, clock_config: &Config, timeout: BusTimeout) -> Result<(), ConfigError> {
let clocks = Clocks::get();
let source_clk = clocks.xtal_clock.as_hz();
let bus_freq = clock_config.frequency.as_hz();
let clkm_div: u32 = source_clk / (bus_freq * 1024) + 1;
let sclk_freq: u32 = source_clk / clkm_div;
let half_cycle: u32 = sclk_freq / bus_freq / 2;
// SCL
let scl_low = half_cycle;
// default, scl_wait_high < scl_high
// Make 80KHz as a boundary here, because when working at lower frequency, too
// much scl_wait_high will faster the frequency according to some
// hardware behaviors.
let scl_wait_high = if bus_freq >= 80 * 1000 {
half_cycle / 2 - 2
} else {
half_cycle / 4
};
let scl_high = half_cycle - scl_wait_high;
let sda_hold = half_cycle / 4;
let sda_sample = half_cycle / 2 + scl_wait_high;
let setup = half_cycle;
let hold = half_cycle;
// According to the Technical Reference Manual, the following timings must be
// subtracted by 1. However, according to the practical measurement and
// some hardware behaviour, if wait_high_period and scl_high minus one.
// The SCL frequency would be a little higher than expected. Therefore, the
// solution here is not to minus scl_high as well as scl_wait high, and
// the frequency will be absolutely accurate to all frequency
// to some extent.
let scl_low_period = scl_low - 1;
let scl_high_period = scl_high;
let scl_wait_high_period = scl_wait_high;
// sda sample
let sda_hold_time = sda_hold - 1;
let sda_sample_time = sda_sample - 1;
// setup
let scl_rstart_setup_time = setup - 1;
let scl_stop_setup_time = setup - 1;
// hold
let scl_start_hold_time = hold - 1;
let scl_stop_hold_time = hold - 1;
let timeout = match timeout {
BusTimeout::Maximum => BusTimeout::BusCycles(0x1F),
BusTimeout::Disabled => BusTimeout::Disabled,
BusTimeout::BusCycles(cycles) => {
let to_peri = (cycles * 2 * half_cycle).max(1);
let log2 = to_peri.ilog2();
// Round up so that we don't shorten timeouts.
let raw = if to_peri != 1 << log2 { log2 + 1 } else { log2 };
BusTimeout::BusCycles(check_timeout(raw, 0x1F)?)
}
};
configure_clock(
self.regs(),
clkm_div,
scl_low_period,
scl_high_period,
scl_wait_high_period,
sda_hold_time,
sda_sample_time,
scl_rstart_setup_time,
scl_stop_setup_time,
scl_start_hold_time,
scl_stop_hold_time,
timeout,
)?;
Ok(())
}
#[cfg(any(esp32, esp32s2))]
async fn read_all_from_fifo(&self, buffer: &mut [u8]) -> Result<(), Error> {
if buffer.len() > 32 {
return Err(Error::FifoExceeded);
}
self.wait_for_completion(false).await?;
for byte in buffer.iter_mut() {
*byte = read_fifo(self.regs());
}
Ok(())
}
#[cfg(not(any(esp32, esp32s2)))]
async fn read_all_from_fifo(&self, buffer: &mut [u8]) -> Result<(), Error> {
self.read_all_from_fifo_blocking(buffer)
}
/// Configures the I2C peripheral for a write operation.
/// - `addr` is the address of the slave device.
/// - `bytes` is the data two be sent.
/// - `start` indicates whether the operation should start by a START
/// condition and sending the address.
/// - `cmd_iterator` is an iterator over the command registers.
fn setup_write<'a, I>(
&self,
addr: I2cAddress,
bytes: &[u8],
start: bool,
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
// if start is true we can only send 254 additional bytes with the address as
// the first
let max_len = if start { 254usize } else { 255usize };
if bytes.len() > max_len {
// we could support more by adding multiple write operations
return Err(Error::FifoExceeded);
}
let write_len = if start { bytes.len() + 1 } else { bytes.len() };
// don't issue write if there is no data to write
if write_len > 0 {
// WRITE command
add_cmd(
cmd_iterator,
Command::Write {
ack_exp: Ack::Ack,
ack_check_en: true,
length: write_len as u8,
},
)?;
}
self.update_config();
if start {
// Load address and R/W bit into FIFO
match addr {
I2cAddress::SevenBit(addr) => {
write_fifo(self.regs(), (addr << 1) | OperationType::Write as u8);
}
}
}
Ok(())
}
/// Configures the I2C peripheral for a read operation.
/// - `addr` is the address of the slave device.
/// - `buffer` is the buffer to store the read data.
/// - `start` indicates whether the operation should start by a START
/// condition and sending the address.
/// - `will_continue` indicates whether there is another read operation
/// following this one and we should not nack the last byte.
/// - `cmd_iterator` is an iterator over the command registers.
fn setup_read<'a, I>(
&self,
addr: I2cAddress,
buffer: &mut [u8],
start: bool,
will_continue: bool,
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
if buffer.is_empty() {
return Err(Error::ZeroLengthInvalid);
}
let (max_len, initial_len) = if will_continue {
(255usize, buffer.len())
} else {
(254usize, buffer.len() - 1)
};
if buffer.len() > max_len {
// we could support more by adding multiple read operations
return Err(Error::FifoExceeded);
}
if start {
// WRITE command
add_cmd(
cmd_iterator,
Command::Write {
ack_exp: Ack::Ack,
ack_check_en: true,
length: 1,
},
)?;
}
if initial_len > 0 {
// READ command
add_cmd(
cmd_iterator,
Command::Read {
ack_value: Ack::Ack,
length: initial_len as u8,
},
)?;
}
if !will_continue {
// this is the last read so we need to nack the last byte
// READ w/o ACK
add_cmd(
cmd_iterator,
Command::Read {
ack_value: Ack::Nack,
length: 1,
},
)?;
}
self.update_config();
if start {
// Load address and R/W bit into FIFO
match addr {
I2cAddress::SevenBit(addr) => {
write_fifo(self.regs(), (addr << 1) | OperationType::Read as u8);
}
}
}
Ok(())
}
#[cfg(not(any(esp32, esp32s2)))]
/// Reads all bytes from the RX FIFO.
fn read_all_from_fifo_blocking(&self, buffer: &mut [u8]) -> Result<(), Error> {
// Read bytes from FIFO
// FIXME: Handle case where less data has been provided by the slave than
// requested? Or is this prevented from a protocol perspective?
for byte in buffer.iter_mut() {
loop {
self.check_errors()?;
let reg = self.regs().fifo_st().read();
if reg.rxfifo_raddr().bits() != reg.rxfifo_waddr().bits() {
break;
}
}
*byte = read_fifo(self.regs());
}
Ok(())
}
#[cfg(any(esp32, esp32s2))]
/// Reads all bytes from the RX FIFO.
fn read_all_from_fifo_blocking(&self, buffer: &mut [u8]) -> Result<(), Error> {
// on ESP32/ESP32-S2 we currently don't support I2C transactions larger than the
// FIFO apparently it would be possible by using non-fifo mode
// see https://github.com/espressif/arduino-esp32/blob/7e9afe8c5ed7b5bf29624a5cd6e07d431c027b97/cores/esp32/esp32-hal-i2c.c#L615
if buffer.len() > 32 {
return Err(Error::FifoExceeded);
}
// wait for completion - then we can just read the data from FIFO
// once we change to non-fifo mode to support larger transfers that
// won't work anymore
self.wait_for_completion_blocking(false)?;
// Read bytes from FIFO
// FIXME: Handle case where less data has been provided by the slave than
// requested? Or is this prevented from a protocol perspective?
for byte in buffer.iter_mut() {
*byte = read_fifo(self.regs());
}
Ok(())
}
/// Clears all pending interrupts for the I2C peripheral.
fn clear_all_interrupts(&self) {
self.regs()
.int_clr()
.write(|w| unsafe { w.bits(I2C_LL_INTR_MASK) });
}
#[cfg(any(esp32, esp32s2))]
async fn write_remaining_tx_fifo(&self, start_index: usize, bytes: &[u8]) -> Result<(), Error> {
if start_index >= bytes.len() {
return Ok(());
}
for b in bytes {
write_fifo(self.regs(), *b);
self.check_errors()?;
}
Ok(())
}
#[cfg(not(any(esp32, esp32s2)))]
async fn write_remaining_tx_fifo(&self, start_index: usize, bytes: &[u8]) -> Result<(), Error> {
let mut index = start_index;
loop {
self.check_errors()?;
I2cFuture::new(Event::TxFifoWatermark, self.info, self.state).await?;
self.regs()
.int_clr()
.write(|w| w.txfifo_wm().clear_bit_by_one());
I2cFuture::new(Event::TxFifoWatermark, self.info, self.state).await?;
if index >= bytes.len() {
break Ok(());
}
write_fifo(self.regs(), bytes[index]);
index += 1;
}
}
#[cfg(not(esp32))]
async fn wait_for_completion(&self, end_only: bool) -> Result<(), Error> {
self.check_errors()?;
if end_only {
I2cFuture::new(Event::EndDetect, self.info, self.state).await?;
} else {
let res = embassy_futures::select::select(
I2cFuture::new(Event::TxComplete, self.info, self.state),
I2cFuture::new(Event::EndDetect, self.info, self.state),
)
.await;
match res {
embassy_futures::select::Either::First(res) => res?,
embassy_futures::select::Either::Second(res) => res?,
}
}
self.check_all_commands_done()?;
Ok(())
}
#[cfg(esp32)]
async fn wait_for_completion(&self, end_only: bool) -> Result<(), Error> {
// for ESP32 we need a timeout here but wasting a timer seems unnecessary
// given the short time we spend here
let mut tout = MAX_ITERATIONS / 10; // adjust the timeout because we are yielding in the loop
loop {
let interrupts = self.regs().int_raw().read();
self.check_errors()?;
// Handle completion cases
// A full transmission was completed (either a STOP condition or END was
// processed)
if (!end_only && interrupts.trans_complete().bit_is_set())
|| interrupts.end_detect().bit_is_set()
{
break;
}
tout -= 1;
if tout == 0 {
return Err(Error::Timeout);
}
embassy_futures::yield_now().await;
}
self.check_all_commands_done()?;
Ok(())
}
/// Waits for the completion of an I2C transaction.
fn wait_for_completion_blocking(&self, end_only: bool) -> Result<(), Error> {
let mut tout = MAX_ITERATIONS;
loop {
let interrupts = self.regs().int_raw().read();
self.check_errors()?;
// Handle completion cases
// A full transmission was completed (either a STOP condition or END was
// processed)
if (!end_only && interrupts.trans_complete().bit_is_set())
|| interrupts.end_detect().bit_is_set()
{
break;
}
tout -= 1;
if tout == 0 {
return Err(Error::Timeout);
}
}
self.check_all_commands_done()?;
Ok(())
}
/// Checks whether all I2C commands have completed execution.
fn check_all_commands_done(&self) -> Result<(), Error> {
// NOTE: on esp32 executing the end command generates the end_detect interrupt
// but does not seem to clear the done bit! So we don't check the done
// status of an end command
for cmd_reg in self.regs().comd_iter() {
let cmd = cmd_reg.read();
if cmd.bits() != 0x0 && !cmd.opcode().is_end() && !cmd.command_done().bit_is_set() {
return Err(Error::ExecutionIncomplete);
}
}
Ok(())
}
/// Checks for I2C transmission errors and handles them.
///
/// This function inspects specific I2C-related interrupts to detect errors
/// during communication, such as timeouts, failed acknowledgments, or
/// arbitration loss. If an error is detected, the function handles it
/// by resetting the I2C peripheral to clear the error condition and then
/// returns an appropriate error.
fn check_errors(&self) -> Result<(), Error> {
let interrupts = self.regs().int_raw().read();
// The ESP32 variant has a slightly different interrupt naming
// scheme!
cfg_if::cfg_if! {
if #[cfg(esp32)] {
// Handle error cases
let retval = if interrupts.time_out().bit_is_set() {
Err(Error::Timeout)
} else if interrupts.nack().bit_is_set() {
Err(Error::AcknowledgeCheckFailed(estimate_ack_failed_reason(self.regs())))
} else if interrupts.arbitration_lost().bit_is_set() {
Err(Error::ArbitrationLost)
} else {
Ok(())
};
} else {
// Handle error cases
let retval = if interrupts.time_out().bit_is_set() {
Err(Error::Timeout)
} else if interrupts.nack().bit_is_set() {
Err(Error::AcknowledgeCheckFailed(estimate_ack_failed_reason(self.regs())))
} else if interrupts.arbitration_lost().bit_is_set() {
Err(Error::ArbitrationLost)
} else if interrupts.trans_complete().bit_is_set() && self.regs().sr().read().resp_rec().bit_is_clear() {
Err(Error::AcknowledgeCheckFailed(AcknowledgeCheckFailedReason::Data))
} else {
Ok(())
};
}
}
if retval.is_err() {
self.reset();
}
retval
}
/// Updates the configuration of the I2C peripheral.
///
/// This function ensures that the configuration values, such as clock
/// settings, SDA/SCL filtering, timeouts, and other operational
/// parameters, which are configured in other functions, are properly
/// propagated to the I2C hardware. This step is necessary to synchronize
/// the software-configured settings with the peripheral's internal
/// registers, ensuring that the hardware behaves according to the
/// current configuration.
fn update_config(&self) {
// Ensure that the configuration of the peripheral is correctly propagated
// (only necessary for C2, C3, C6, H2 and S3 variant)
#[cfg(any(esp32c2, esp32c3, esp32c6, esp32h2, esp32s3))]
self.regs().ctr().modify(|_, w| w.conf_upgate().set_bit());
}
/// Starts an I2C transmission.
fn start_transmission(&self) {
// Start transmission
self.regs().ctr().modify(|_, w| w.trans_start().set_bit());
}
#[cfg(not(any(esp32, esp32s2)))]
/// Fills the TX FIFO with data from the provided slice.
fn fill_tx_fifo(&self, bytes: &[u8]) -> Result<usize, Error> {
let mut index = 0;
while index < bytes.len() && !self.regs().int_raw().read().txfifo_ovf().bit_is_set() {
write_fifo(self.regs(), bytes[index]);
index += 1;
}
if self.regs().int_raw().read().txfifo_ovf().bit_is_set() {
index -= 1;
self.regs()
.int_clr()
.write(|w| w.txfifo_ovf().clear_bit_by_one());
}
Ok(index)
}
#[cfg(not(any(esp32, esp32s2)))]
/// Writes remaining data from byte slice to the TX FIFO from the specified
/// index.
fn write_remaining_tx_fifo_blocking(
&self,
start_index: usize,
bytes: &[u8],
) -> Result<(), Error> {
let mut index = start_index;
loop {
self.check_errors()?;
while !self.regs().int_raw().read().txfifo_wm().bit_is_set() {
self.check_errors()?;
}
self.regs()
.int_clr()
.write(|w| w.txfifo_wm().clear_bit_by_one());
while !self.regs().int_raw().read().txfifo_wm().bit_is_set() {
self.check_errors()?;
}
if index >= bytes.len() {
break Ok(());
}
write_fifo(self.regs(), bytes[index]);
index += 1;
}
}
#[cfg(any(esp32, esp32s2))]
/// Fills the TX FIFO with data from the provided slice.
fn fill_tx_fifo(&self, bytes: &[u8]) -> Result<usize, Error> {
// on ESP32/ESP32-S2 we currently don't support I2C transactions larger than the
// FIFO apparently it would be possible by using non-fifo mode
// see https://github.com/espressif/arduino-esp32/blob/7e9afe8c5ed7b5bf29624a5cd6e07d431c027b97/cores/esp32/esp32-hal-i2c.c#L615
if bytes.len() > 31 {
return Err(Error::FifoExceeded);
}
for b in bytes {
write_fifo(self.regs(), *b);
}
Ok(bytes.len())
}
#[cfg(any(esp32, esp32s2))]
/// Writes remaining data from byte slice to the TX FIFO from the specified
/// index.
fn write_remaining_tx_fifo_blocking(
&self,
start_index: usize,
bytes: &[u8],
) -> Result<(), Error> {
// on ESP32/ESP32-S2 we currently don't support I2C transactions larger than the
// FIFO apparently it would be possible by using non-fifo mode
// see https://github.com/espressif/arduino-esp32/blob/7e9afe8c5ed7b5bf29624a5cd6e07d431c027b97/cores/esp32/esp32-hal-i2c.c#L615
if start_index >= bytes.len() {
return Ok(());
}
// this is only possible when writing the I2C address in release mode
// from [perform_write_read]
for b in bytes {
write_fifo(self.regs(), *b);
self.check_errors()?;
}
Ok(())
}
/// Resets the transmit and receive FIFO buffers
#[cfg(not(esp32))]
fn reset_fifo(&self) {
// First, reset the fifo buffers
self.regs().fifo_conf().modify(|_, w| unsafe {
w.tx_fifo_rst().set_bit();
w.rx_fifo_rst().set_bit();
w.nonfifo_en().clear_bit();
w.fifo_prt_en().set_bit();
w.rxfifo_wm_thrhd().bits(1);
w.txfifo_wm_thrhd().bits(8)
});
self.regs().fifo_conf().modify(|_, w| {
w.tx_fifo_rst().clear_bit();
w.rx_fifo_rst().clear_bit()
});
self.regs().int_clr().write(|w| {
w.rxfifo_wm().clear_bit_by_one();
w.txfifo_wm().clear_bit_by_one()
});
self.update_config();
}
/// Resets the transmit and receive FIFO buffers
#[cfg(esp32)]
fn reset_fifo(&self) {
// First, reset the fifo buffers
self.regs().fifo_conf().modify(|_, w| unsafe {
w.tx_fifo_rst().set_bit();
w.rx_fifo_rst().set_bit();
w.nonfifo_en().clear_bit();
w.nonfifo_rx_thres().bits(1);
w.nonfifo_tx_thres().bits(32)
});
self.regs().fifo_conf().modify(|_, w| {
w.tx_fifo_rst().clear_bit();
w.rx_fifo_rst().clear_bit()
});
self.regs()
.int_clr()
.write(|w| w.rxfifo_full().clear_bit_by_one());
}
fn start_write_operation(
&self,
address: I2cAddress,
bytes: &[u8],
start: bool,
stop: bool,
) -> Result<usize, Error> {
self.reset_fifo();
self.reset_command_list();
let cmd_iterator = &mut self.regs().comd_iter();
if start {
add_cmd(cmd_iterator, Command::Start)?;
}
self.setup_write(address, bytes, start, cmd_iterator)?;
add_cmd(
cmd_iterator,
if stop { Command::Stop } else { Command::End },
)?;
let index = self.fill_tx_fifo(bytes)?;
self.start_transmission();
Ok(index)
}
/// Executes an I2C read operation.
/// - `addr` is the address of the slave device.
/// - `buffer` is the buffer to store the read data.
/// - `start` indicates whether the operation should start by a START
/// condition and sending the address.
/// - `stop` indicates whether the operation should end with a STOP
/// condition.
/// - `will_continue` indicates whether there is another read operation
/// following this one and we should not nack the last byte.
/// - `cmd_iterator` is an iterator over the command registers.
fn start_read_operation(
&self,
address: I2cAddress,
buffer: &mut [u8],
start: bool,
stop: bool,
will_continue: bool,
) -> Result<(), Error> {
self.reset_fifo();
self.reset_command_list();
let cmd_iterator = &mut self.regs().comd_iter();
if start {
add_cmd(cmd_iterator, Command::Start)?;
}
self.setup_read(address, buffer, start, will_continue, cmd_iterator)?;
add_cmd(
cmd_iterator,
if stop { Command::Stop } else { Command::End },
)?;
self.start_transmission();
Ok(())
}
/// Executes an I2C write operation.
/// - `addr` is the address of the slave device.
/// - `bytes` is the data two be sent.
/// - `start` indicates whether the operation should start by a START
/// condition and sending the address.
/// - `stop` indicates whether the operation should end with a STOP
/// condition.
/// - `cmd_iterator` is an iterator over the command registers.
fn write_operation_blocking(
&self,
address: I2cAddress,
bytes: &[u8],
start: bool,
stop: bool,
) -> Result<(), Error> {
self.clear_all_interrupts();
// Short circuit for zero length writes without start or end as that would be an
// invalid operation write lengths in the TRM (at least for ESP32-S3) are 1-255
if bytes.is_empty() && !start && !stop {
return Ok(());
}
let index = self.start_write_operation(address, bytes, start, stop)?;
// Fill the FIFO with the remaining bytes:
self.write_remaining_tx_fifo_blocking(index, bytes)?;
self.wait_for_completion_blocking(!stop)?;
Ok(())
}
/// Executes an I2C read operation.
/// - `addr` is the address of the slave device.
/// - `buffer` is the buffer to store the read data.
/// - `start` indicates whether the operation should start by a START
/// condition and sending the address.
/// - `stop` indicates whether the operation should end with a STOP
/// condition.
/// - `will_continue` indicates whether there is another read operation
/// following this one and we should not nack the last byte.
/// - `cmd_iterator` is an iterator over the command registers.
fn read_operation_blocking(
&self,
address: I2cAddress,
buffer: &mut [u8],
start: bool,
stop: bool,
will_continue: bool,
) -> Result<(), Error> {
self.clear_all_interrupts();
// Short circuit for zero length reads as that would be an invalid operation
// read lengths in the TRM (at least for ESP32-S3) are 1-255
if buffer.is_empty() {
return Ok(());
}
self.start_read_operation(address, buffer, start, stop, will_continue)?;
self.read_all_from_fifo_blocking(buffer)?;
self.wait_for_completion_blocking(!stop)?;
Ok(())
}
/// Executes an async I2C write operation.
/// - `addr` is the address of the slave device.
/// - `bytes` is the data two be sent.
/// - `start` indicates whether the operation should start by a START
/// condition and sending the address.
/// - `stop` indicates whether the operation should end with a STOP
/// condition.
/// - `cmd_iterator` is an iterator over the command registers.
async fn write_operation(
&self,
address: I2cAddress,
bytes: &[u8],
start: bool,
stop: bool,
) -> Result<(), Error> {
self.clear_all_interrupts();
// Short circuit for zero length writes without start or end as that would be an
// invalid operation write lengths in the TRM (at least for ESP32-S3) are 1-255
if bytes.is_empty() && !start && !stop {
return Ok(());
}
let index = self.start_write_operation(address, bytes, start, stop)?;
// Fill the FIFO with the remaining bytes:
self.write_remaining_tx_fifo(index, bytes).await?;
self.wait_for_completion(!stop).await?;
Ok(())
}
/// Executes an async I2C read operation.
/// - `addr` is the address of the slave device.
/// - `buffer` is the buffer to store the read data.
/// - `start` indicates whether the operation should start by a START
/// condition and sending the address.
/// - `stop` indicates whether the operation should end with a STOP
/// condition.
/// - `will_continue` indicates whether there is another read operation
/// following this one and we should not nack the last byte.
/// - `cmd_iterator` is an iterator over the command registers.
async fn read_operation(
&self,
address: I2cAddress,
buffer: &mut [u8],
start: bool,
stop: bool,
will_continue: bool,
) -> Result<(), Error> {
self.clear_all_interrupts();
// Short circuit for zero length reads as that would be an invalid operation
// read lengths in the TRM (at least for ESP32-S3) are 1-255
if buffer.is_empty() {
return Ok(());
}
self.start_read_operation(address, buffer, start, stop, will_continue)?;
self.read_all_from_fifo(buffer).await?;
self.wait_for_completion(!stop).await?;
Ok(())
}
fn read_blocking(
&self,
address: I2cAddress,
buffer: &mut [u8],
start: bool,
stop: bool,
will_continue: bool,
) -> Result<(), Error> {
let chunk_count = buffer.len().div_ceil(I2C_CHUNK_SIZE);
for (idx, chunk) in buffer.chunks_mut(I2C_CHUNK_SIZE).enumerate() {
self.read_operation_blocking(
address,
chunk,
start && idx == 0,
stop && idx == chunk_count - 1,
will_continue || idx < chunk_count - 1,
)?;
}
Ok(())
}
fn write_blocking(
&self,
address: I2cAddress,
buffer: &[u8],
start: bool,
stop: bool,
) -> Result<(), Error> {
if buffer.is_empty() {
return self.write_operation_blocking(address, &[], start, stop);
}
let chunk_count = buffer.len().div_ceil(I2C_CHUNK_SIZE);
for (idx, chunk) in buffer.chunks(I2C_CHUNK_SIZE).enumerate() {
self.write_operation_blocking(
address,
chunk,
start && idx == 0,
stop && idx == chunk_count - 1,
)?;
}
Ok(())
}
async fn read(
&self,
address: I2cAddress,
buffer: &mut [u8],
start: bool,
stop: bool,
will_continue: bool,
) -> Result<(), Error> {
let chunk_count = buffer.len().div_ceil(I2C_CHUNK_SIZE);
for (idx, chunk) in buffer.chunks_mut(I2C_CHUNK_SIZE).enumerate() {
self.read_operation(
address,
chunk,
start && idx == 0,
stop && idx == chunk_count - 1,
will_continue || idx < chunk_count - 1,
)
.await?;
}
Ok(())
}
async fn write(
&self,
address: I2cAddress,
buffer: &[u8],
start: bool,
stop: bool,
) -> Result<(), Error> {
if buffer.is_empty() {
return self.write_operation(address, &[], start, stop).await;
}
let chunk_count = buffer.len().div_ceil(I2C_CHUNK_SIZE);
for (idx, chunk) in buffer.chunks(I2C_CHUNK_SIZE).enumerate() {
self.write_operation(
address,
chunk,
start && idx == 0,
stop && idx == chunk_count - 1,
)
.await?;
}
Ok(())
}
}
fn check_timeout(v: u32, max: u32) -> Result<u32, ConfigError> {
if v <= max {
Ok(v)
} else {
Err(ConfigError::TimeoutInvalid)
}
}
/// Peripheral state for an I2C instance.
#[doc(hidden)]
#[non_exhaustive]
pub struct State {
/// Waker for the asynchronous operations.
pub waker: AtomicWaker,
}
/// I2C Peripheral Instance
#[doc(hidden)]
pub trait Instance: Peripheral<P = Self> + Into<AnyI2c> + 'static {
/// Returns the peripheral data and state describing this instance.
fn parts(&self) -> (&Info, &State);
/// Returns the peripheral data describing this instance.
#[inline(always)]
fn info(&self) -> &Info {
self.parts().0
}
/// Returns the peripheral state for this instance.
#[inline(always)]
fn state(&self) -> &State {
self.parts().1
}
}
/// Adds a command to the I2C command sequence.
fn add_cmd<'a, I>(cmd_iterator: &mut I, command: Command) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
let cmd = cmd_iterator.next().ok_or(Error::CommandNumberExceeded)?;
cmd.write(|w| match command {
Command::Start => w.opcode().rstart(),
Command::Stop => w.opcode().stop(),
Command::End => w.opcode().end(),
Command::Write {
ack_exp,
ack_check_en,
length,
} => unsafe {
w.opcode().write();
w.ack_exp().bit(ack_exp == Ack::Nack);
w.ack_check_en().bit(ack_check_en);
w.byte_num().bits(length);
w
},
Command::Read { ack_value, length } => unsafe {
w.opcode().read();
w.ack_value().bit(ack_value == Ack::Nack);
w.byte_num().bits(length);
w
},
});
Ok(())
}
#[cfg(not(esp32s2))]
fn read_fifo(register_block: &RegisterBlock) -> u8 {
register_block.data().read().fifo_rdata().bits()
}
#[cfg(not(esp32))]
fn write_fifo(register_block: &RegisterBlock, data: u8) {
register_block
.data()
.write(|w| unsafe { w.fifo_rdata().bits(data) });
}
#[cfg(esp32s2)]
fn read_fifo(register_block: &RegisterBlock) -> u8 {
let base_addr = register_block.scl_low_period().as_ptr();
let fifo_ptr = (if base_addr as u32 == 0x3f413000 {
0x6001301c
} else {
0x6002701c
}) as *mut u32;
unsafe { (fifo_ptr.read_volatile() & 0xff) as u8 }
}
#[cfg(esp32)]
fn write_fifo(register_block: &RegisterBlock, data: u8) {
let base_addr = register_block.scl_low_period().as_ptr();
let fifo_ptr = (if base_addr as u32 == 0x3FF53000 {
0x6001301c
} else {
0x6002701c
}) as *mut u32;
unsafe {
fifo_ptr.write_volatile(data as u32);
}
}
// Estimate the reason for an acknowledge check failure on a best effort basis.
// When in doubt it's better to return `Unknown` than to return a wrong reason.
fn estimate_ack_failed_reason(_register_block: &RegisterBlock) -> AcknowledgeCheckFailedReason {
cfg_if::cfg_if! {
if #[cfg(any(esp32, esp32s2, esp32c2, esp32c3))] {
AcknowledgeCheckFailedReason::Unknown
} else {
// this is based on observations rather than documented behavior
if _register_block.fifo_st().read().txfifo_raddr().bits() <= 1 {
AcknowledgeCheckFailedReason::Address
} else {
AcknowledgeCheckFailedReason::Data
}
}
}
}
macro_rules! instance {
($inst:ident, $peri:ident, $scl:ident, $sda:ident, $interrupt:ident) => {
impl Instance for crate::peripherals::$inst {
fn parts(&self) -> (&Info, &State) {
#[crate::handler]
pub(super) fn irq_handler() {
async_handler(&PERIPHERAL, &STATE);
}
static STATE: State = State {
waker: AtomicWaker::new(),
};
static PERIPHERAL: Info = Info {
register_block: crate::peripherals::$inst::ptr(),
peripheral: crate::system::Peripheral::$peri,
async_handler: irq_handler,
interrupt: Interrupt::$interrupt,
scl_output: OutputSignal::$scl,
scl_input: InputSignal::$scl,
sda_output: OutputSignal::$sda,
sda_input: InputSignal::$sda,
};
(&PERIPHERAL, &STATE)
}
}
};
}
#[cfg(i2c0)]
instance!(I2C0, I2cExt0, I2CEXT0_SCL, I2CEXT0_SDA, I2C_EXT0);
#[cfg(i2c1)]
instance!(I2C1, I2cExt1, I2CEXT1_SCL, I2CEXT1_SDA, I2C_EXT1);
crate::any_peripheral! {
/// Represents any I2C peripheral.
pub peripheral AnyI2c {
#[cfg(i2c0)]
I2c0(crate::peripherals::I2C0),
#[cfg(i2c1)]
I2c1(crate::peripherals::I2C1),
}
}
impl Instance for AnyI2c {
delegate::delegate! {
to match &self.0 {
AnyI2cInner::I2c0(i2c) => i2c,
#[cfg(i2c1)]
AnyI2cInner::I2c1(i2c) => i2c,
} {
fn parts(&self) -> (&Info, &State);
}
}
}