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
//! # I2C Driver
//!
//! ## Overview
//! The I2C Peripheral Driver for ESP chips is a software module that
//! facilitates communication with I2C devices using ESP microcontroller chips.
//! It provides an interface to initialize, configure, and perform read and
//! write operations over the I2C bus.
//!
//! The driver supports features such as handling transmission errors,
//! asynchronous operations, and interrupt-based communication, also supports
//! multiple I2C peripheral instances on `ESP32`, `ESP32H2`, `ESP32S2`, and
//! `ESP32S3` chips
//!
//! ## Example
//! Following code shows how to read data from a BMP180 sensor using I2C.
//!
//! ```no_run
//! // Create a new peripheral object with the described wiring
//! // and standard I2C clock speed
//! let mut i2c = I2C::new(
//! peripherals.I2C0,
//! io.pins.gpio1,
//! io.pins.gpio2,
//! 100u32.kHz(),
//! &clocks,
//! );
//! loop {
//! let mut data = [0u8; 22];
//! i2c.write_read(0x77, &[0xaa], &mut data).ok();
//!
//! println!("{:02x?}", data);
//! }
//! ```
use fugit::HertzU32;
use crate::{
clock::Clocks,
gpio::{InputPin, InputSignal, OutputPin, OutputSignal},
peripheral::{Peripheral, PeripheralRef},
peripherals::i2c0::{RegisterBlock, COMD},
system::PeripheralClockControl,
};
cfg_if::cfg_if! {
if #[cfg(esp32s2)] {
const I2C_LL_INTR_MASK: u32 = 0x1ffff;
} else {
const I2C_LL_INTR_MASK: u32 = 0x3ffff;
}
}
/// I2C-specific transmission errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
ExceedingFifo,
AckCheckFailed,
TimeOut,
ArbitrationLost,
ExecIncomplete,
CommandNrExceeded,
}
#[cfg(feature = "eh1")]
impl embedded_hal_1::i2c::Error for Error {
fn kind(&self) -> embedded_hal_1::i2c::ErrorKind {
use embedded_hal_1::i2c::ErrorKind;
match self {
Self::ExceedingFifo => ErrorKind::Overrun,
Self::ArbitrationLost => ErrorKind::ArbitrationLoss,
_ => ErrorKind::Other,
}
}
}
/// A generic I2C Command
enum Command {
Start,
Stop,
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,
},
}
impl From<Command> for u16 {
fn from(c: Command) -> u16 {
let opcode = match c {
Command::Start => Opcode::RStart,
Command::Stop => Opcode::Stop,
Command::Write { .. } => Opcode::Write,
Command::Read { .. } => Opcode::Read,
};
let length = match c {
Command::Start | Command::Stop => 0,
Command::Write { length: l, .. } | Command::Read { length: l, .. } => l,
};
let ack_exp = match c {
Command::Start | Command::Stop | Command::Read { .. } => Ack::Nack,
Command::Write { ack_exp: exp, .. } => exp,
};
let ack_check_en = match c {
Command::Start | Command::Stop | Command::Read { .. } => false,
Command::Write {
ack_check_en: en, ..
} => en,
};
let ack_value = match c {
Command::Start | Command::Stop | Command::Write { .. } => Ack::Nack,
Command::Read { ack_value: ack, .. } => ack,
};
let mut cmd: u16 = length.into();
if ack_check_en {
cmd |= 1 << 8;
} else {
cmd &= !(1 << 8);
}
if ack_exp == Ack::Nack {
cmd |= 1 << 9;
} else {
cmd &= !(1 << 9);
}
if ack_value == Ack::Nack {
cmd |= 1 << 10;
} else {
cmd &= !(1 << 10);
}
cmd |= (opcode as u16) << 11;
cmd
}
}
enum OperationType {
Write = 0,
Read = 1,
}
#[derive(Eq, PartialEq, Copy, Clone)]
enum Ack {
Ack,
Nack,
}
#[cfg(any(esp32c2, esp32c3, esp32c6, esp32h2, esp32s3))]
enum Opcode {
RStart = 6,
Write = 1,
Read = 3,
Stop = 2,
}
#[cfg(any(esp32, esp32s2))]
enum Opcode {
RStart = 0,
Write = 1,
Read = 2,
Stop = 3,
}
/// I2C peripheral container (I2C)
pub struct I2C<'d, T> {
peripheral: PeripheralRef<'d, T>,
}
impl<T> embedded_hal::blocking::i2c::Read for I2C<'_, T>
where
T: Instance,
{
type Error = Error;
fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.peripheral.master_read(address, buffer)
}
}
impl<T> embedded_hal::blocking::i2c::Write for I2C<'_, T>
where
T: Instance,
{
type Error = Error;
fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> {
self.peripheral.master_write(addr, bytes)
}
}
impl<T> embedded_hal::blocking::i2c::WriteRead for I2C<'_, T>
where
T: Instance,
{
type Error = Error;
fn write_read(
&mut self,
address: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Self::Error> {
self.peripheral.master_write_read(address, bytes, buffer)
}
}
#[cfg(feature = "eh1")]
impl<T> embedded_hal_1::i2c::ErrorType for I2C<'_, T> {
type Error = Error;
}
#[cfg(feature = "eh1")]
impl<T> embedded_hal_1::i2c::I2c for I2C<'_, T>
where
T: Instance,
{
fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.peripheral.master_read(address, buffer)
}
fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), Self::Error> {
self.peripheral.master_write(address, bytes)
}
fn write_read(
&mut self,
address: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Self::Error> {
self.peripheral.master_write_read(address, bytes, buffer)
}
fn transaction<'a>(
&mut self,
_address: u8,
_operations: &mut [embedded_hal_1::i2c::Operation<'a>],
) -> Result<(), Self::Error> {
todo!()
}
}
impl<'d, T> I2C<'d, T>
where
T: Instance,
{
/// Create a new I2C instance
/// This will enable the peripheral but the peripheral won't get
/// automatically disabled when this gets dropped.
pub fn new<SDA: OutputPin + InputPin, SCL: OutputPin + InputPin>(
i2c: impl Peripheral<P = T> + 'd,
sda: impl Peripheral<P = SDA> + 'd,
scl: impl Peripheral<P = SCL> + 'd,
frequency: HertzU32,
clocks: &Clocks,
) -> Self {
Self::new_with_timeout(i2c, sda, scl, frequency, clocks, None)
}
/// Create a new I2C instance with a custom timeout value.
/// This will enable the peripheral but the peripheral won't get
/// automatically disabled when this gets dropped.
pub fn new_with_timeout<SDA: OutputPin + InputPin, SCL: OutputPin + InputPin>(
i2c: impl Peripheral<P = T> + 'd,
sda: impl Peripheral<P = SDA> + 'd,
scl: impl Peripheral<P = SCL> + 'd,
frequency: HertzU32,
clocks: &Clocks,
timeout: Option<u32>,
) -> Self {
crate::into_ref!(i2c, sda, scl);
PeripheralClockControl::enable(match i2c.i2c_number() {
0 => crate::system::Peripheral::I2cExt0,
#[cfg(i2c1)]
1 => crate::system::Peripheral::I2cExt1,
_ => unreachable!(), // will never happen
});
let mut i2c = I2C { peripheral: i2c };
// avoid SCL/SDA going low during configuration
scl.set_output_high(true);
sda.set_output_high(true);
scl.set_to_open_drain_output()
.enable_input(true)
.internal_pull_up(true)
.connect_peripheral_to_output(i2c.peripheral.scl_output_signal())
.connect_input_to_peripheral(i2c.peripheral.scl_input_signal());
sda.set_to_open_drain_output()
.enable_input(true)
.internal_pull_up(true)
.connect_peripheral_to_output(i2c.peripheral.sda_output_signal())
.connect_input_to_peripheral(i2c.peripheral.sda_input_signal());
i2c.peripheral.setup(frequency, clocks, timeout);
i2c
}
#[cfg(feature = "async")]
pub(crate) fn inner(&self) -> &T {
&self.peripheral
}
}
#[cfg(feature = "async")]
mod asynch {
use core::{
pin::Pin,
task::{Context, Poll},
};
use cfg_if::cfg_if;
use embassy_futures::select::select;
use embassy_sync::waitqueue::AtomicWaker;
use embedded_hal_1::i2c::Operation;
use procmacros::interrupt;
use super::*;
cfg_if! {
if #[cfg(all(i2c0, i2c1))] {
const NUM_I2C: usize = 2;
} else if #[cfg(i2c0)] {
const NUM_I2C: usize = 1;
}
}
const INIT: AtomicWaker = AtomicWaker::new();
static WAKERS: [AtomicWaker; NUM_I2C] = [INIT; NUM_I2C];
pub(crate) enum Event {
EndDetect,
TxComplete,
#[cfg(not(any(esp32, esp32s2)))]
TxFifoWatermark,
}
pub(crate) struct I2cFuture<'a, T>
where
T: Instance,
{
event: Event,
instance: &'a T,
}
impl<'a, T> I2cFuture<'a, T>
where
T: Instance,
{
pub fn new(event: Event, instance: &'a T) -> Self {
instance
.register_block()
.int_ena()
.modify(|_, w| match event {
Event::EndDetect => w.end_detect_int_ena().set_bit(),
Event::TxComplete => w.trans_complete_int_ena().set_bit(),
#[cfg(not(any(esp32, esp32s2)))]
Event::TxFifoWatermark => w.txfifo_wm_int_ena().set_bit(),
});
Self { event, instance }
}
fn event_bit_is_clear(&self) -> bool {
let r = self.instance.register_block().int_ena().read();
match self.event {
Event::EndDetect => r.end_detect_int_ena().bit_is_clear(),
Event::TxComplete => r.trans_complete_int_ena().bit_is_clear(),
#[cfg(not(any(esp32, esp32s2)))]
Event::TxFifoWatermark => r.txfifo_wm_int_ena().bit_is_clear(),
}
}
}
impl<'a, T> core::future::Future for I2cFuture<'a, T>
where
T: Instance,
{
type Output = ();
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
WAKERS[self.instance.i2c_number()].register(ctx.waker());
if self.event_bit_is_clear() {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
impl<T> I2C<'_, T>
where
T: Instance,
{
async fn master_read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), Error> {
// Reset FIFO and command list
self.peripheral.reset_fifo();
self.peripheral.reset_command_list();
self.perform_read(
addr,
buffer,
&mut self.peripheral.register_block().comd_iter(),
)
.await
}
async fn perform_read<'a, I>(
&self,
addr: u8,
buffer: &mut [u8],
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
self.peripheral.setup_read(addr, buffer, cmd_iterator)?;
self.peripheral.start_transmission();
self.read_all_from_fifo(buffer).await?;
self.wait_for_completion().await?;
Ok(())
}
#[cfg(any(esp32, esp32s2))]
async fn read_all_from_fifo(&self, buffer: &mut [u8]) -> Result<(), Error> {
if buffer.len() > 32 {
panic!("On ESP32 and ESP32-S2 the max I2C read is limited to 32 bytes");
}
self.wait_for_completion().await?;
for byte in buffer.iter_mut() {
*byte = read_fifo(self.peripheral.register_block());
}
Ok(())
}
#[cfg(not(any(esp32, esp32s2)))]
async fn read_all_from_fifo(&self, buffer: &mut [u8]) -> Result<(), Error> {
self.peripheral.read_all_from_fifo(buffer)
}
async fn master_write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Error> {
// Reset FIFO and command list
self.peripheral.reset_fifo();
self.peripheral.reset_command_list();
self.perform_write(
addr,
bytes,
&mut self.peripheral.register_block().comd_iter(),
)
.await
}
async fn perform_write<'a, I>(
&self,
addr: u8,
bytes: &[u8],
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
self.peripheral.setup_write(addr, bytes, cmd_iterator)?;
let index = self.peripheral.fill_tx_fifo(bytes);
self.peripheral.start_transmission();
// Fill the FIFO with the remaining bytes:
self.write_remaining_tx_fifo(index, bytes).await?;
self.wait_for_completion().await?;
Ok(())
}
#[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.peripheral.register_block(), *b);
self.peripheral.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.peripheral.check_errors()?;
I2cFuture::new(Event::TxFifoWatermark, self.inner()).await;
self.peripheral
.register_block()
.int_clr()
.write(|w| w.txfifo_wm_int_clr().set_bit());
I2cFuture::new(Event::TxFifoWatermark, self.inner()).await;
if index >= bytes.len() {
break Ok(());
}
write_fifo(self.peripheral.register_block(), bytes[index]);
index += 1;
}
}
async fn wait_for_completion(&self) -> Result<(), Error> {
self.peripheral.check_errors()?;
select(
I2cFuture::new(Event::TxComplete, self.inner()),
I2cFuture::new(Event::EndDetect, self.inner()),
)
.await;
for cmd in self.peripheral.register_block().comd_iter() {
if cmd.read().command().bits() != 0x0 && cmd.read().command_done().bit_is_clear() {
return Err(Error::ExecIncomplete);
}
}
Ok(())
}
}
impl<'d, T> embedded_hal_async::i2c::I2c for I2C<'d, T>
where
T: Instance,
{
async fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> {
self.master_read(address, read).await
}
async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> {
self.master_write(address, write).await
}
async fn write_read(
&mut self,
address: u8,
write: &[u8],
read: &mut [u8],
) -> Result<(), Self::Error> {
self.master_write(address, write).await?;
self.master_read(address, read).await?;
Ok(())
}
async fn transaction(
&mut self,
_address: u8,
_operations: &mut [Operation<'_>],
) -> Result<(), Self::Error> {
todo!()
}
}
#[interrupt]
fn I2C_EXT0() {
unsafe { &*crate::peripherals::I2C0::PTR }
.int_ena()
.modify(|_, w| {
w.end_detect_int_ena()
.clear_bit()
.trans_complete_int_ena()
.clear_bit()
});
#[cfg(not(any(esp32, esp32s2)))]
unsafe { &*crate::peripherals::I2C0::PTR }
.int_ena()
.modify(|_, w| w.txfifo_wm_int_ena().clear_bit());
WAKERS[0].wake();
}
#[cfg(i2c1)]
#[interrupt]
fn I2C_EXT1() {
unsafe { &*crate::peripherals::I2C1::PTR }
.int_ena()
.modify(|_, w| {
w.end_detect_int_ena()
.clear_bit()
.trans_complete_int_ena()
.clear_bit()
});
#[cfg(not(any(esp32, esp32s2)))]
unsafe { &*crate::peripherals::I2C0::PTR }
.int_ena()
.modify(|_, w| w.txfifo_wm_int_ena().clear_bit());
WAKERS[1].wake();
}
}
/// I2C Peripheral Instance
pub trait Instance {
fn scl_output_signal(&self) -> OutputSignal;
fn scl_input_signal(&self) -> InputSignal;
fn sda_output_signal(&self) -> OutputSignal;
fn sda_input_signal(&self) -> InputSignal;
fn register_block(&self) -> &RegisterBlock;
fn i2c_number(&self) -> usize;
fn setup(&mut self, frequency: HertzU32, clocks: &Clocks, timeout: Option<u32>) {
self.register_block().ctr().modify(|_, w| unsafe {
// Clear register
w.bits(0)
// Set I2C controller to master mode
.ms_mode()
.set_bit()
// Use open drain output for SDA and SCL
.sda_force_out()
.set_bit()
.scl_force_out()
.set_bit()
// Use Most Significant Bit first for sending and receiving data
.tx_lsb_first()
.clear_bit()
.rx_lsb_first()
.clear_bit()
// Ensure that clock is enabled
.clk_en()
.set_bit()
});
#[cfg(esp32s2)]
self.register_block()
.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
self.set_filter(Some(7), Some(7));
// Configure frequency
#[cfg(esp32)]
self.set_frequency(clocks.i2c_clock.convert(), frequency, timeout);
#[cfg(not(esp32))]
self.set_frequency(clocks.xtal_clock.convert(), frequency, timeout);
self.update_config();
// Reset entire peripheral (also resets fifo)
self.reset();
}
/// 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.register_block()
.ctr()
.modify(|_, w| w.fsm_rst().set_bit());
// Clear all I2C interrupts
self.register_block()
.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.register_block().comd_iter() {
cmd.reset();
}
}
/// Sets the filter with a supplied threshold in clock cycles for which a
/// pulse must be present to pass the filter
fn set_filter(&mut self, sda_threshold: Option<u8>, scl_threshold: Option<u8>) {
cfg_if::cfg_if! {
if #[cfg(any(esp32, esp32s2))] {
let sda_register = &self.register_block().sda_filter_cfg();
let scl_register = &self.register_block().scl_filter_cfg();
} else {
let sda_register = &self.register_block().filter_cfg();
let scl_register = &self.register_block().filter_cfg();
}
}
match sda_threshold {
Some(threshold) => {
sda_register.modify(|_, w| unsafe { w.sda_filter_thres().bits(threshold) });
sda_register.modify(|_, w| w.sda_filter_en().set_bit());
}
None => sda_register.modify(|_, w| w.sda_filter_en().clear_bit()),
}
match scl_threshold {
Some(threshold) => {
scl_register.modify(|_, w| unsafe { w.scl_filter_thres().bits(threshold) });
scl_register.modify(|_, w| w.scl_filter_en().set_bit());
}
None => scl_register.modify(|_, w| w.scl_filter_en().clear_bit()),
}
}
#[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(&mut self, source_clk: HertzU32, bus_freq: HertzU32, timeout: Option<u32>) {
let source_clk = source_clk.raw();
let bus_freq = bus_freq.raw();
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 tout = if let Some(timeout) = timeout {
timeout
} else {
// default we set the timeout value to 10 bus cycles
half_cycle * 20
};
// 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;
let time_out_value = tout;
self.configure_clock(
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,
time_out_value,
true,
);
}
#[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(&mut self, source_clk: HertzU32, bus_freq: HertzU32, timeout: Option<u32>) {
let source_clk = source_clk.raw();
let bus_freq = bus_freq.raw();
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;
let tout = if let Some(timeout) = timeout {
timeout
} else {
// default we set the timeout value to 10 bus cycles
half_cycle * 20
};
// 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 time_out_value = tout;
let time_out_en = true;
self.configure_clock(
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,
time_out_value,
time_out_en,
);
}
#[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(&mut self, source_clk: HertzU32, bus_freq: HertzU32, timeout: Option<u32>) {
let source_clk = source_clk.raw();
let bus_freq = bus_freq.raw();
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;
let tout = if let Some(timeout) = timeout {
timeout
} else {
// default we set the timeout value to about 10 bus cycles
// log(20*half_cycle)/log(2) = log(half_cycle)/log(2) + log(20)/log(2)
(4 * 8 - (5 * half_cycle).leading_zeros()) + 2
};
// 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 time_out_value = tout;
let time_out_en = true;
self.configure_clock(
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,
time_out_value,
time_out_en,
);
}
#[allow(clippy::too_many_arguments, unused)]
fn configure_clock(
&mut self,
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,
time_out_value: u32,
time_out_en: bool,
) {
unsafe {
// divider
#[cfg(any(esp32c2, esp32c3, esp32c6, esp32h2, esp32s3))]
self.register_block().clk_conf().modify(|_, w| {
w.sclk_sel()
.clear_bit()
.sclk_div_num()
.bits((sclk_div - 1) as u8)
});
// scl period
self.register_block()
.scl_low_period()
.write(|w| w.scl_low_period().bits(scl_low_period as u16));
// for high/wait_high we have to differentiate between the chips
// as the EPS32 does not have a wait_high field
cfg_if::cfg_if! {
if #[cfg(not(esp32))] {
self.register_block().scl_high_period().write(|w| {
w.scl_high_period()
.bits(scl_high_period as u16)
.scl_wait_high_period()
.bits(scl_wait_high_period.try_into().unwrap())
});
}
else {
self.register_block().scl_high_period().write(|w| {
w.scl_high_period()
.bits(scl_high_period as u16)
});
}
}
// we already did that above but on S2 we need this to make it work
#[cfg(esp32s2)]
self.register_block().scl_high_period().write(|w| {
w.scl_wait_high_period()
.bits(scl_wait_high_period as u16)
.scl_high_period()
.bits(scl_high_period as u16)
});
// sda sample
self.register_block()
.sda_hold()
.write(|w| w.time().bits(sda_hold_time as u16));
self.register_block()
.sda_sample()
.write(|w| w.time().bits(sda_sample_time as u16));
// setup
self.register_block()
.scl_rstart_setup()
.write(|w| w.time().bits(scl_rstart_setup_time as u16));
self.register_block()
.scl_stop_setup()
.write(|w| w.time().bits(scl_stop_setup_time as u16));
// hold
self.register_block()
.scl_start_hold()
.write(|w| w.time().bits(scl_start_hold_time as u16));
self.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)] {
// timeout
self.register_block()
.to()
.write(|w| w.time_out().bits(time_out_value));
}
else {
// timeout
// FIXME: Enable timout for other chips!
#[allow(clippy::useless_conversion)]
self.register_block()
.to()
.write(|w| w.time_out_en().bit(time_out_en)
.time_out_value()
.variant(time_out_value.try_into().unwrap())
);
}
}
}
}
fn setup_write<'a, I>(&self, addr: u8, bytes: &[u8], cmd_iterator: &mut I) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
if bytes.len() > 254 {
// we could support more by adding multiple write operations
return Err(Error::ExceedingFifo);
}
// Clear all I2C interrupts
self.clear_all_interrupts();
// RSTART command
add_cmd(cmd_iterator, Command::Start)?;
// WRITE command
add_cmd(
cmd_iterator,
Command::Write {
ack_exp: Ack::Ack,
ack_check_en: true,
length: 1 + bytes.len() as u8,
},
)?;
add_cmd(cmd_iterator, Command::Stop)?;
self.update_config();
// Load address and R/W bit into FIFO
write_fifo(
self.register_block(),
addr << 1 | OperationType::Write as u8,
);
Ok(())
}
fn perform_write<'a, I>(
&self,
addr: u8,
bytes: &[u8],
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
self.setup_write(addr, bytes, cmd_iterator)?;
let index = self.fill_tx_fifo(bytes);
self.start_transmission();
// Fill the FIFO with the remaining bytes:
self.write_remaining_tx_fifo(index, bytes)?;
self.wait_for_completion()?;
Ok(())
}
fn setup_read<'a, I>(
&self,
addr: u8,
buffer: &mut [u8],
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
if buffer.len() > 254 {
// we could support more by adding multiple read operations
return Err(Error::ExceedingFifo);
}
// Clear all I2C interrupts
self.clear_all_interrupts();
// RSTART command
add_cmd(cmd_iterator, Command::Start)?;
// WRITE command
add_cmd(
cmd_iterator,
Command::Write {
ack_exp: Ack::Ack,
ack_check_en: true,
length: 1,
},
)?;
if buffer.len() > 1 {
// READ command (N - 1)
add_cmd(
cmd_iterator,
Command::Read {
ack_value: Ack::Ack,
length: buffer.len() as u8 - 1,
},
)?;
}
// READ w/o ACK
add_cmd(
cmd_iterator,
Command::Read {
ack_value: Ack::Nack,
length: 1,
},
)?;
add_cmd(cmd_iterator, Command::Stop)?;
self.update_config();
// Load address and R/W bit into FIFO
write_fifo(self.register_block(), addr << 1 | OperationType::Read as u8);
Ok(())
}
fn perform_read<'a, I>(
&self,
addr: u8,
buffer: &mut [u8],
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
self.setup_read(addr, buffer, cmd_iterator)?;
self.start_transmission();
self.read_all_from_fifo(buffer)?;
self.wait_for_completion()?;
Ok(())
}
#[cfg(not(any(esp32, esp32s2)))]
fn read_all_from_fifo(&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.register_block().fifo_st().read();
if reg.rxfifo_raddr().bits() != reg.rxfifo_waddr().bits() {
break;
}
}
*byte = read_fifo(self.register_block());
}
Ok(())
}
#[cfg(any(esp32, esp32s2))]
fn read_all_from_fifo(&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 {
panic!("On ESP32 and ESP32-S2 the max I2C read is limited to 32 bytes");
}
// 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()?;
// 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.register_block());
}
Ok(())
}
fn clear_all_interrupts(&self) {
self.register_block()
.int_clr()
.write(|w| unsafe { w.bits(I2C_LL_INTR_MASK) });
}
fn wait_for_completion(&self) -> Result<(), Error> {
loop {
let interrupts = self.register_block().int_raw().read();
self.check_errors()?;
// Handle completion cases
// A full transmission was completed
if interrupts.trans_complete_int_raw().bit_is_set()
|| interrupts.end_detect_int_raw().bit_is_set()
{
break;
}
}
for cmd in self.register_block().comd_iter() {
if cmd.read().command().bits() != 0x0 && cmd.read().command_done().bit_is_clear() {
return Err(Error::ExecIncomplete);
}
}
Ok(())
}
fn check_errors(&self) -> Result<(), Error> {
let interrupts = self.register_block().int_raw().read();
// The ESP32 variant has a slightly different interrupt naming
// scheme!
cfg_if::cfg_if! {
if #[cfg(esp32)] {
// Handle error cases
if interrupts.time_out_int_raw().bit_is_set() {
self.reset();
return Err(Error::TimeOut);
} else if interrupts.ack_err_int_raw().bit_is_set() {
self.reset();
return Err(Error::AckCheckFailed);
} else if interrupts.arbitration_lost_int_raw().bit_is_set() {
self.reset();
return Err(Error::ArbitrationLost);
}
}
else {
// Handle error cases
if interrupts.time_out_int_raw().bit_is_set() {
self.reset();
return Err(Error::TimeOut);
} else if interrupts.nack_int_raw().bit_is_set() {
self.reset();
return Err(Error::AckCheckFailed);
} else if interrupts.arbitration_lost_int_raw().bit_is_set() {
self.reset();
return Err(Error::ArbitrationLost);
} else if interrupts.trans_complete_int_raw().bit_is_set() && self.register_block().sr().read().resp_rec().bit_is_clear() {
self.reset();
return Err(Error::AckCheckFailed);
}
}
}
Ok(())
}
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.register_block()
.ctr()
.modify(|_, w| w.conf_upgate().set_bit());
}
fn start_transmission(&self) {
// Start transmission
self.register_block()
.ctr()
.modify(|_, w| w.trans_start().set_bit());
}
#[cfg(not(any(esp32, esp32s2)))]
fn fill_tx_fifo(&self, bytes: &[u8]) -> usize {
let mut index = 0;
while index < bytes.len()
&& !self
.register_block()
.int_raw()
.read()
.txfifo_ovf_int_raw()
.bit_is_set()
{
write_fifo(self.register_block(), bytes[index]);
index += 1;
}
if self
.register_block()
.int_raw()
.read()
.txfifo_ovf_int_raw()
.bit_is_set()
{
index -= 1;
self.register_block()
.int_clr()
.write(|w| w.txfifo_ovf_int_clr().set_bit());
}
index
}
#[cfg(not(any(esp32, esp32s2)))]
fn write_remaining_tx_fifo(&self, start_index: usize, bytes: &[u8]) -> Result<(), Error> {
let mut index = start_index;
loop {
self.check_errors()?;
while !self
.register_block()
.int_raw()
.read()
.txfifo_wm_int_raw()
.bit_is_set()
{}
self.register_block()
.int_clr()
.write(|w| w.txfifo_wm_int_clr().set_bit());
while !self
.register_block()
.int_raw()
.read()
.txfifo_wm_int_raw()
.bit_is_set()
{}
if index >= bytes.len() {
break Ok(());
}
write_fifo(self.register_block(), bytes[index]);
index += 1;
}
}
#[cfg(any(esp32, esp32s2))]
fn fill_tx_fifo(&self, bytes: &[u8]) -> usize {
// 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 {
panic!("On ESP32 and ESP32-S2 the max I2C transfer is limited to 31 bytes");
}
for b in bytes {
write_fifo(self.register_block(), *b);
}
bytes.len()
}
#[cfg(any(esp32, esp32s2))]
fn write_remaining_tx_fifo(&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.register_block(), *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.register_block().fifo_conf().modify(|_, w| {
w.tx_fifo_rst()
.set_bit()
.rx_fifo_rst()
.set_bit()
.nonfifo_en()
.clear_bit()
.fifo_prt_en()
.set_bit()
.rxfifo_wm_thrhd()
.variant(1)
.txfifo_wm_thrhd()
.variant(8)
});
self.register_block()
.fifo_conf()
.modify(|_, w| w.tx_fifo_rst().clear_bit().rx_fifo_rst().clear_bit());
self.register_block().int_clr().write(|w| {
w.rxfifo_wm_int_clr()
.set_bit()
.txfifo_wm_int_clr()
.set_bit()
});
self.update_config();
}
/// Resets the transmit and receive FIFO buffers
#[cfg(esp32)]
fn reset_fifo(&self) {
// First, reset the fifo buffers
self.register_block().fifo_conf().modify(|_, w| {
w.tx_fifo_rst()
.set_bit()
.rx_fifo_rst()
.set_bit()
.nonfifo_en()
.clear_bit()
.nonfifo_rx_thres()
.variant(1)
.nonfifo_tx_thres()
.variant(32)
});
self.register_block()
.fifo_conf()
.modify(|_, w| w.tx_fifo_rst().clear_bit().rx_fifo_rst().clear_bit());
self.register_block()
.int_clr()
.write(|w| w.rxfifo_full_int_clr().set_bit());
}
/// Send data bytes from the `bytes` array to a target slave with the
/// address `addr`
fn master_write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Error> {
// Reset FIFO and command list
self.reset_fifo();
self.reset_command_list();
self.perform_write(addr, bytes, &mut self.register_block().comd_iter())?;
Ok(())
}
/// Read bytes from a target slave with the address `addr`
/// The number of read bytes is deterimed by the size of the `buffer`
/// argument
fn master_read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), Error> {
// Reset FIFO and command list
self.reset_fifo();
self.reset_command_list();
self.perform_read(addr, buffer, &mut self.register_block().comd_iter())?;
Ok(())
}
/// Write bytes from the `bytes` array first and then read n bytes into
/// the `buffer` array with n being the size of the array.
fn master_write_read(
&mut self,
addr: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Error> {
// it would be possible to combine the write and read
// in one transaction but filling the tx fifo with
// the current code is somewhat slow even in release mode
// which can cause issues
self.master_write(addr, bytes)?;
self.master_read(addr, buffer)?;
Ok(())
}
}
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::CommandNrExceeded)?;
cmd.write(|w| unsafe { w.command().bits(command.into()) });
Ok(())
}
#[cfg(not(any(esp32, 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 read_fifo(register_block: &RegisterBlock) -> u8 {
register_block.data().read().fifo_rdata().bits()
}
#[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);
}
}
impl Instance for crate::peripherals::I2C0 {
#[inline(always)]
fn scl_output_signal(&self) -> OutputSignal {
OutputSignal::I2CEXT0_SCL
}
#[inline(always)]
fn scl_input_signal(&self) -> InputSignal {
InputSignal::I2CEXT0_SCL
}
#[inline(always)]
fn sda_output_signal(&self) -> OutputSignal {
OutputSignal::I2CEXT0_SDA
}
fn sda_input_signal(&self) -> InputSignal {
InputSignal::I2CEXT0_SDA
}
#[inline(always)]
fn register_block(&self) -> &RegisterBlock {
self
}
#[inline(always)]
fn i2c_number(&self) -> usize {
0
}
}
#[cfg(i2c1)]
impl Instance for crate::peripherals::I2C1 {
#[inline(always)]
fn scl_output_signal(&self) -> OutputSignal {
OutputSignal::I2CEXT1_SCL
}
#[inline(always)]
fn scl_input_signal(&self) -> InputSignal {
InputSignal::I2CEXT1_SCL
}
#[inline(always)]
fn sda_output_signal(&self) -> OutputSignal {
OutputSignal::I2CEXT1_SDA
}
fn sda_input_signal(&self) -> InputSignal {
InputSignal::I2CEXT1_SDA
}
#[inline(always)]
fn register_block(&self) -> &RegisterBlock {
self
}
#[inline(always)]
fn i2c_number(&self) -> usize {
1
}
}
#[cfg(lp_i2c0)]
pub mod lp_i2c {
//! Low-power I2C driver
use fugit::HertzU32;
use crate::{
gpio::{lp_gpio::LowPowerPin, OpenDrain},
peripherals::{LP_CLKRST, LP_I2C0},
};
const LP_I2C_FILTER_CYC_NUM_DEF: u8 = 7;
/// I2C-specific transmission errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
ExceedingFifo,
AckCheckFailed,
TimeOut,
ArbitrationLost,
ExecIncomplete,
CommandNrExceeded,
InvalidResponse,
}
#[allow(unused)]
enum OperationType {
Write = 0,
Read = 1,
}
#[allow(unused)]
#[derive(Eq, PartialEq, Copy, Clone)]
enum Ack {
Ack,
Nack,
}
#[allow(unused)]
enum Opcode {
RStart = 6,
Write = 1,
Read = 3,
Stop = 2,
End = 4,
}
#[derive(PartialEq)]
#[allow(unused)]
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,
},
}
impl From<Command> for u16 {
fn from(c: Command) -> u16 {
let opcode = match c {
Command::Start => Opcode::RStart,
Command::Stop => Opcode::Stop,
Command::End => Opcode::End,
Command::Write { .. } => Opcode::Write,
Command::Read { .. } => Opcode::Read,
};
let length = match c {
Command::Start | Command::Stop | Command::End => 0,
Command::Write { length: l, .. } | Command::Read { length: l, .. } => l,
};
let ack_exp = match c {
Command::Start | Command::Stop | Command::End | Command::Read { .. } => Ack::Nack,
Command::Write { ack_exp: exp, .. } => exp,
};
let ack_check_en = match c {
Command::Start | Command::Stop | Command::End | Command::Read { .. } => false,
Command::Write {
ack_check_en: en, ..
} => en,
};
let ack_value = match c {
Command::Start | Command::Stop | Command::End | Command::Write { .. } => Ack::Nack,
Command::Read { ack_value: ack, .. } => ack,
};
let mut cmd: u16 = length.into();
if ack_check_en {
cmd |= 1 << 8;
} else {
cmd &= !(1 << 8);
}
if ack_exp == Ack::Nack {
cmd |= 1 << 9;
} else {
cmd &= !(1 << 9);
}
if ack_value == Ack::Nack {
cmd |= 1 << 10;
} else {
cmd &= !(1 << 10);
}
cmd |= (opcode as u16) << 11;
cmd
}
}
impl From<Command> for u32 {
fn from(c: Command) -> u32 {
let opcode = match c {
Command::Start => Opcode::RStart,
Command::Stop => Opcode::Stop,
Command::End => Opcode::End,
Command::Write { .. } => Opcode::Write,
Command::Read { .. } => Opcode::Read,
};
let length = match c {
Command::Start | Command::Stop | Command::End => 0,
Command::Write { length: l, .. } | Command::Read { length: l, .. } => l,
};
let ack_exp = match c {
Command::Start | Command::Stop | Command::End | Command::Read { .. } => Ack::Nack,
Command::Write { ack_exp: exp, .. } => exp,
};
let ack_check_en = match c {
Command::Start | Command::Stop | Command::End | Command::Read { .. } => false,
Command::Write {
ack_check_en: en, ..
} => en,
};
let ack_value = match c {
Command::Start | Command::Stop | Command::End | Command::Write { .. } => Ack::Nack,
Command::Read { ack_value: ack, .. } => ack,
};
let mut cmd: u32 = length.into();
if ack_check_en {
cmd |= 1 << 8;
} else {
cmd &= !(1 << 8);
}
if ack_exp == Ack::Nack {
cmd |= 1 << 9;
} else {
cmd &= !(1 << 9);
}
if ack_value == Ack::Nack {
cmd |= 1 << 10;
} else {
cmd &= !(1 << 10);
}
cmd |= (opcode as u32) << 11;
cmd
}
}
// https://github.com/espressif/esp-idf/blob/master/components/ulp/lp_core/lp_core_i2c.c#L122
// TX/RX RAM size is 16*8 bit
// TX RX FIFO has 16 bit depth
// The clock source of APB_CLK in LP_I2C is CLK_AON_FAST.
// Configure LP_I2C_SCLK_SEL to select the clock source for I2C_SCLK.
// When LP_I2C_SCLK_SEL is 0, select CLK_ROOT_FAST as clock source,
// and when LP_I2C_SCLK_SEL is 1, select CLK _XTALD2 as the clock source.
// Configure LP_EXT_I2C_CK_EN high to enable the clock source of I2C_SCLK.
// Adjust the timing registers accordingly when the clock frequency changes.
pub struct LpI2c {
i2c: LP_I2C0,
}
impl LpI2c {
pub fn new(
i2c: LP_I2C0,
_sda: LowPowerPin<OpenDrain, 6>,
_scl: LowPowerPin<OpenDrain, 7>,
frequency: HertzU32,
) -> Self {
let me = Self { i2c };
// Configure LP I2C GPIOs
// Initialize IO Pins
let lp_io = unsafe { &*crate::peripherals::LP_IO::PTR };
let lp_aon = unsafe { &*crate::peripherals::LP_AON::PTR };
let lp_peri = unsafe { &*crate::peripherals::LP_PERI::PTR };
unsafe {
lp_aon
.gpio_mux()
.modify(|r, w| w.sel().bits(r.sel().bits() | (1 << 6)));
lp_aon
.gpio_mux()
.modify(|r, w| w.sel().bits(r.sel().bits() | (1 << 7)));
lp_io.gpio6().modify(|_, w| w.mcu_sel().variant(1)); // TODO
lp_io.gpio7().modify(|_, w| w.mcu_sel().variant(1));
// Set output mode to Normal
lp_io.pin6().modify(|_, w| w.pad_driver().set_bit());
// Enable output (writing to write-1-to-set register, then internally the
// `GPIO_OUT_REG` will be set)
lp_io
.out_enable_w1ts()
.write(|w| w.enable_w1ts().bits(1 << 6));
// Enable input
lp_io.gpio6().modify(|_, w| w.fun_ie().set_bit());
// Disable pulldown (enable internal weak pull-down)
lp_io.gpio6().modify(|_, w| w.fun_wpd().clear_bit());
// Enable pullup
lp_io.gpio6().modify(|_, w| w.fun_wpu().set_bit());
// Same process for SCL pin
lp_io.pin7().modify(|_, w| w.pad_driver().set_bit());
// Enable output (writing to write-1-to-set register, then internally the
// `GPIO_OUT_REG` will be set)
lp_io
.out_enable_w1ts()
.write(|w| w.enable_w1ts().bits(1 << 7));
// Enable input
lp_io.gpio7().modify(|_, w| w.fun_ie().set_bit());
// Disable pulldown (enable internal weak pull-down)
lp_io.gpio7().modify(|_, w| w.fun_wpd().clear_bit());
// Enable pullup
lp_io.gpio7().modify(|_, w| w.fun_wpu().set_bit());
// Select LP I2C function for the SDA and SCL pins
lp_io.gpio6().modify(|_, w| w.mcu_sel().bits(1));
lp_io.gpio7().modify(|_, w| w.mcu_sel().bits(1));
}
// Initialize LP I2C HAL */
me.i2c.clk_conf().modify(|_, w| w.sclk_active().set_bit());
// Enable LP I2C controller clock
lp_peri
.clk_en()
.modify(|_, w| w.lp_ext_i2c_ck_en().set_bit());
lp_peri
.reset_en()
.modify(|_, w| w.lp_ext_i2c_reset_en().set_bit());
lp_peri
.reset_en()
.modify(|_, w| w.lp_ext_i2c_reset_en().clear_bit());
// Set LP I2C source clock
unsafe { &*LP_CLKRST::PTR }
.lpperi()
.modify(|_, w| w.lp_i2c_clk_sel().clear_bit());
// Initialize LP I2C Master mode
me.i2c.ctr().modify(|_, w| unsafe {
// Clear register
w.bits(0)
// Use open drain output for SDA and SCL
.sda_force_out()
.set_bit()
.scl_force_out()
.set_bit()
// Ensure that clock is enabled
.clk_en()
.set_bit()
});
// First, reset the fifo buffers
me.i2c.fifo_conf().modify(|_, w| w.nonfifo_en().clear_bit());
me.i2c
.ctr()
.modify(|_, w| w.tx_lsb_first().clear_bit().rx_lsb_first().clear_bit());
me.reset_fifo();
// Set LP I2C source clock
unsafe { &*LP_CLKRST::PTR }
.lpperi()
.modify(|_, w| w.lp_i2c_clk_sel().clear_bit());
// Configure LP I2C timing paramters. source_clk is ignored for LP_I2C in this
// call
let source_clk = 16_000_000;
let bus_freq = frequency.raw();
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; // TODO + scl_wait_high;
let setup = half_cycle;
let hold = half_cycle;
// default we set the timeout value to about 10 bus cycles
// log(20*half_cycle)/log(2) = log(half_cycle)/log(2) + log(20)/log(2)
let tout = (4 * 8 - (5 * half_cycle).leading_zeros()) + 2;
// 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 time_out_value = tout;
let time_out_en = true;
// Write data to registers
unsafe {
me.i2c.clk_conf().modify(|_, w| {
w.sclk_sel()
.clear_bit()
.sclk_div_num()
.bits((clkm_div - 1) as u8)
});
// scl period
me.i2c
.scl_low_period()
.write(|w| w.scl_low_period().bits(scl_low_period as u16));
me.i2c.scl_high_period().write(|w| {
w.scl_high_period()
.bits(scl_high_period as u16)
.scl_wait_high_period()
.bits(scl_wait_high_period as u8)
});
// sda sample
me.i2c
.sda_hold()
.write(|w| w.time().bits(sda_hold_time as u16));
me.i2c
.sda_sample()
.write(|w| w.time().bits(sda_sample_time as u16));
// setup
me.i2c
.scl_rstart_setup()
.write(|w| w.time().bits(scl_rstart_setup_time as u16));
me.i2c
.scl_stop_setup()
.write(|w| w.time().bits(scl_stop_setup_time as u16));
// hold
me.i2c
.scl_start_hold()
.write(|w| w.time().bits(scl_start_hold_time as u16));
me.i2c
.scl_stop_hold()
.write(|w| w.time().bits(scl_stop_hold_time as u16));
me.i2c.to().write(|w| {
w.time_out_en()
.bit(time_out_en)
.time_out_value()
.variant(time_out_value.try_into().unwrap())
});
}
// Enable SDA and SCL filtering. This configuration matches the HP I2C filter
// config
me.i2c
.filter_cfg()
.modify(|_, w| unsafe { w.sda_filter_thres().bits(LP_I2C_FILTER_CYC_NUM_DEF) });
me.i2c
.filter_cfg()
.modify(|_, w| unsafe { w.scl_filter_thres().bits(LP_I2C_FILTER_CYC_NUM_DEF) });
me.i2c
.filter_cfg()
.modify(|_, w| w.sda_filter_en().set_bit());
me.i2c
.filter_cfg()
.modify(|_, w| w.scl_filter_en().set_bit());
// Configure the I2C master to send a NACK when the Rx FIFO count is full
me.i2c.ctr().modify(|_, w| w.rx_full_ack_level().set_bit());
// Synchronize the config register values to the LP I2C peripheral clock
me.lp_i2c_update();
me
}
/// Update I2C configuration
fn lp_i2c_update(&self) {
self.i2c.ctr().modify(|_, w| w.conf_upgate().set_bit());
}
fn reset_fifo(&self) {
self.i2c
.fifo_conf()
.modify(|_, w| w.tx_fifo_rst().set_bit());
self.i2c
.fifo_conf()
.modify(|_, w| w.tx_fifo_rst().clear_bit());
self.i2c
.fifo_conf()
.modify(|_, w| w.rx_fifo_rst().set_bit());
self.i2c
.fifo_conf()
.modify(|_, w| w.rx_fifo_rst().clear_bit());
}
}
}