esp_hal/spi/master.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
//! # Serial Peripheral Interface - Master Mode
//!
//! ## Overview
//!
//! In this mode, the SPI acts as master and initiates the SPI transactions.
//!
//! ## Configuration
//!
//! The peripheral can be used in full-duplex and half-duplex mode and can
//! leverage DMA for data transfers. It can also be used in blocking or async.
//!
//! ### Exclusive access to the SPI bus
//!
//! If all you want to do is to communicate to a single device, and you initiate
//! transactions yourself, there are a number of ways to achieve this:
//!
//! - Use the [`SpiBus`](embedded_hal::spi::SpiBus) trait and its associated
//! functions to initiate transactions with simultaneous reads and writes, or
//! - Use the `ExclusiveDevice` struct from [`embedded-hal-bus`] or `SpiDevice`
//! from [`embassy-embedded-hal`].
//!
//! ### Shared SPI access
//!
//! If you have multiple devices on the same SPI bus that each have their own CS
//! line (and optionally, configuration), you may want to have a look at the
//! implementations provided by [`embedded-hal-bus`] and
//! [`embassy-embedded-hal`].
//!
//! ## Usage
//!
//! The module implements several third-party traits from embedded-hal@1.x.x
//! and [`embassy-embedded-hal`].
//!
//! [`embedded-hal-bus`]: https://docs.rs/embedded-hal-bus/latest/embedded_hal_bus/spi/index.html
//! [`embassy-embedded-hal`]: embassy_embedded_hal::shared_bus
use core::marker::PhantomData;
#[instability::unstable]
pub use dma::*;
use enumset::{EnumSet, EnumSetType};
#[cfg(place_spi_driver_in_ram)]
use procmacros::ram;
use super::{BitOrder, DataMode, DmaError, Error, Mode};
use crate::{
asynch::AtomicWaker,
clock::Clocks,
dma::{DmaChannelFor, DmaEligible, DmaRxBuffer, DmaTxBuffer, Rx, Tx},
gpio::{
interconnect::{OutputConnection, PeripheralInput, PeripheralOutput},
InputSignal,
NoPin,
OutputSignal,
PinGuard,
},
interrupt::InterruptHandler,
pac::spi2::RegisterBlock,
peripheral::{Peripheral, PeripheralRef},
private::{self, Sealed},
spi::AnySpi,
system::{Cpu, PeripheralGuard},
time::Rate,
Async,
Blocking,
DriverMode,
};
/// Enumeration of possible SPI interrupt events.
#[derive(Debug, Hash, EnumSetType)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
#[instability::unstable]
pub enum SpiInterrupt {
/// Indicates that the SPI transaction has completed successfully.
///
/// This interrupt is triggered when an SPI transaction has finished
/// transmitting and receiving data.
TransferDone,
/// Triggered at the end of configurable segmented transfer.
#[cfg(any(esp32s2, gdma))]
DmaSegmentedTransferDone,
/// Used and triggered by software. Only used for user defined function.
#[cfg(gdma)]
App2,
/// Used and triggered by software. Only used for user defined function.
#[cfg(gdma)]
App1,
}
/// The size of the FIFO buffer for SPI
const FIFO_SIZE: usize = if cfg!(esp32s2) { 72 } else { 64 };
/// Padding byte for empty write transfers
const EMPTY_WRITE_PAD: u8 = 0x00;
const MAX_DMA_SIZE: usize = 32736;
/// SPI commands, each consisting of a 16-bit command value and a data mode.
///
/// Used to define specific commands sent over the SPI bus.
/// Can be [Command::None] if command phase should be suppressed.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum Command {
/// No command is sent.
None,
/// A 1-bit command.
_1Bit(u16, DataMode),
/// A 2-bit command.
_2Bit(u16, DataMode),
/// A 3-bit command.
_3Bit(u16, DataMode),
/// A 4-bit command.
_4Bit(u16, DataMode),
/// A 5-bit command.
_5Bit(u16, DataMode),
/// A 6-bit command.
_6Bit(u16, DataMode),
/// A 7-bit command.
_7Bit(u16, DataMode),
/// A 8-bit command.
_8Bit(u16, DataMode),
/// A 9-bit command.
_9Bit(u16, DataMode),
/// A 10-bit command.
_10Bit(u16, DataMode),
/// A 11-bit command.
_11Bit(u16, DataMode),
/// A 12-bit command.
_12Bit(u16, DataMode),
/// A 13-bit command.
_13Bit(u16, DataMode),
/// A 14-bit command.
_14Bit(u16, DataMode),
/// A 15-bit command.
_15Bit(u16, DataMode),
/// A 16-bit command.
_16Bit(u16, DataMode),
}
impl Command {
fn width(&self) -> usize {
match self {
Command::None => 0,
Command::_1Bit(_, _) => 1,
Command::_2Bit(_, _) => 2,
Command::_3Bit(_, _) => 3,
Command::_4Bit(_, _) => 4,
Command::_5Bit(_, _) => 5,
Command::_6Bit(_, _) => 6,
Command::_7Bit(_, _) => 7,
Command::_8Bit(_, _) => 8,
Command::_9Bit(_, _) => 9,
Command::_10Bit(_, _) => 10,
Command::_11Bit(_, _) => 11,
Command::_12Bit(_, _) => 12,
Command::_13Bit(_, _) => 13,
Command::_14Bit(_, _) => 14,
Command::_15Bit(_, _) => 15,
Command::_16Bit(_, _) => 16,
}
}
fn value(&self) -> u16 {
match self {
Command::None => 0,
Command::_1Bit(value, _)
| Command::_2Bit(value, _)
| Command::_3Bit(value, _)
| Command::_4Bit(value, _)
| Command::_5Bit(value, _)
| Command::_6Bit(value, _)
| Command::_7Bit(value, _)
| Command::_8Bit(value, _)
| Command::_9Bit(value, _)
| Command::_10Bit(value, _)
| Command::_11Bit(value, _)
| Command::_12Bit(value, _)
| Command::_13Bit(value, _)
| Command::_14Bit(value, _)
| Command::_15Bit(value, _)
| Command::_16Bit(value, _) => *value,
}
}
fn mode(&self) -> DataMode {
match self {
Command::None => DataMode::SingleTwoDataLines,
Command::_1Bit(_, mode)
| Command::_2Bit(_, mode)
| Command::_3Bit(_, mode)
| Command::_4Bit(_, mode)
| Command::_5Bit(_, mode)
| Command::_6Bit(_, mode)
| Command::_7Bit(_, mode)
| Command::_8Bit(_, mode)
| Command::_9Bit(_, mode)
| Command::_10Bit(_, mode)
| Command::_11Bit(_, mode)
| Command::_12Bit(_, mode)
| Command::_13Bit(_, mode)
| Command::_14Bit(_, mode)
| Command::_15Bit(_, mode)
| Command::_16Bit(_, mode) => *mode,
}
}
fn is_none(&self) -> bool {
matches!(self, Command::None)
}
}
/// SPI address, ranging from 1 to 32 bits, paired with a data mode.
///
/// This can be used to specify the address phase of SPI transactions.
/// Can be [Address::None] if address phase should be suppressed.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum Address {
/// No address phase.
None,
/// A 1-bit address.
_1Bit(u32, DataMode),
/// A 2-bit address.
_2Bit(u32, DataMode),
/// A 3-bit address.
_3Bit(u32, DataMode),
/// A 4-bit address.
_4Bit(u32, DataMode),
/// A 5-bit address.
_5Bit(u32, DataMode),
/// A 6-bit address.
_6Bit(u32, DataMode),
/// A 7-bit address.
_7Bit(u32, DataMode),
/// A 8-bit address.
_8Bit(u32, DataMode),
/// A 9-bit address.
_9Bit(u32, DataMode),
/// A 10-bit address.
_10Bit(u32, DataMode),
/// A 11-bit address.
_11Bit(u32, DataMode),
/// A 12-bit address.
_12Bit(u32, DataMode),
/// A 13-bit address.
_13Bit(u32, DataMode),
/// A 14-bit address.
_14Bit(u32, DataMode),
/// A 15-bit address.
_15Bit(u32, DataMode),
/// A 16-bit address.
_16Bit(u32, DataMode),
/// A 17-bit address.
_17Bit(u32, DataMode),
/// A 18-bit address.
_18Bit(u32, DataMode),
/// A 19-bit address.
_19Bit(u32, DataMode),
/// A 20-bit address.
_20Bit(u32, DataMode),
/// A 21-bit address.
_21Bit(u32, DataMode),
/// A 22-bit address.
_22Bit(u32, DataMode),
/// A 23-bit address.
_23Bit(u32, DataMode),
/// A 24-bit address.
_24Bit(u32, DataMode),
/// A 25-bit address.
_25Bit(u32, DataMode),
/// A 26-bit address.
_26Bit(u32, DataMode),
/// A 27-bit address.
_27Bit(u32, DataMode),
/// A 28-bit address.
_28Bit(u32, DataMode),
/// A 29-bit address.
_29Bit(u32, DataMode),
/// A 30-bit address.
_30Bit(u32, DataMode),
/// A 31-bit address.
_31Bit(u32, DataMode),
/// A 32-bit address.
_32Bit(u32, DataMode),
}
impl Address {
fn width(&self) -> usize {
match self {
Address::None => 0,
Address::_1Bit(_, _) => 1,
Address::_2Bit(_, _) => 2,
Address::_3Bit(_, _) => 3,
Address::_4Bit(_, _) => 4,
Address::_5Bit(_, _) => 5,
Address::_6Bit(_, _) => 6,
Address::_7Bit(_, _) => 7,
Address::_8Bit(_, _) => 8,
Address::_9Bit(_, _) => 9,
Address::_10Bit(_, _) => 10,
Address::_11Bit(_, _) => 11,
Address::_12Bit(_, _) => 12,
Address::_13Bit(_, _) => 13,
Address::_14Bit(_, _) => 14,
Address::_15Bit(_, _) => 15,
Address::_16Bit(_, _) => 16,
Address::_17Bit(_, _) => 17,
Address::_18Bit(_, _) => 18,
Address::_19Bit(_, _) => 19,
Address::_20Bit(_, _) => 20,
Address::_21Bit(_, _) => 21,
Address::_22Bit(_, _) => 22,
Address::_23Bit(_, _) => 23,
Address::_24Bit(_, _) => 24,
Address::_25Bit(_, _) => 25,
Address::_26Bit(_, _) => 26,
Address::_27Bit(_, _) => 27,
Address::_28Bit(_, _) => 28,
Address::_29Bit(_, _) => 29,
Address::_30Bit(_, _) => 30,
Address::_31Bit(_, _) => 31,
Address::_32Bit(_, _) => 32,
}
}
fn value(&self) -> u32 {
match self {
Address::None => 0,
Address::_1Bit(value, _)
| Address::_2Bit(value, _)
| Address::_3Bit(value, _)
| Address::_4Bit(value, _)
| Address::_5Bit(value, _)
| Address::_6Bit(value, _)
| Address::_7Bit(value, _)
| Address::_8Bit(value, _)
| Address::_9Bit(value, _)
| Address::_10Bit(value, _)
| Address::_11Bit(value, _)
| Address::_12Bit(value, _)
| Address::_13Bit(value, _)
| Address::_14Bit(value, _)
| Address::_15Bit(value, _)
| Address::_16Bit(value, _)
| Address::_17Bit(value, _)
| Address::_18Bit(value, _)
| Address::_19Bit(value, _)
| Address::_20Bit(value, _)
| Address::_21Bit(value, _)
| Address::_22Bit(value, _)
| Address::_23Bit(value, _)
| Address::_24Bit(value, _)
| Address::_25Bit(value, _)
| Address::_26Bit(value, _)
| Address::_27Bit(value, _)
| Address::_28Bit(value, _)
| Address::_29Bit(value, _)
| Address::_30Bit(value, _)
| Address::_31Bit(value, _)
| Address::_32Bit(value, _) => *value,
}
}
fn is_none(&self) -> bool {
matches!(self, Address::None)
}
fn mode(&self) -> DataMode {
match self {
Address::None => DataMode::SingleTwoDataLines,
Address::_1Bit(_, mode)
| Address::_2Bit(_, mode)
| Address::_3Bit(_, mode)
| Address::_4Bit(_, mode)
| Address::_5Bit(_, mode)
| Address::_6Bit(_, mode)
| Address::_7Bit(_, mode)
| Address::_8Bit(_, mode)
| Address::_9Bit(_, mode)
| Address::_10Bit(_, mode)
| Address::_11Bit(_, mode)
| Address::_12Bit(_, mode)
| Address::_13Bit(_, mode)
| Address::_14Bit(_, mode)
| Address::_15Bit(_, mode)
| Address::_16Bit(_, mode)
| Address::_17Bit(_, mode)
| Address::_18Bit(_, mode)
| Address::_19Bit(_, mode)
| Address::_20Bit(_, mode)
| Address::_21Bit(_, mode)
| Address::_22Bit(_, mode)
| Address::_23Bit(_, mode)
| Address::_24Bit(_, mode)
| Address::_25Bit(_, mode)
| Address::_26Bit(_, mode)
| Address::_27Bit(_, mode)
| Address::_28Bit(_, mode)
| Address::_29Bit(_, mode)
| Address::_30Bit(_, mode)
| Address::_31Bit(_, mode)
| Address::_32Bit(_, mode) => *mode,
}
}
}
/// SPI clock source.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum ClockSource {
/// Use the APB clock.
Apb,
// #[cfg(any(esp32c2, esp32c3, esp32s3))]
// Xtal,
}
/// SPI peripheral configuration
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct Config {
/// The precomputed clock configuration register value.
///
/// Clock divider calculations are relatively expensive, and the SPI
/// peripheral is commonly expected to be used in a shared bus
/// configuration, where different devices may need different bus clock
/// frequencies. To reduce the time required to reconfigure the bus, we
/// cache clock register's value here, for each configuration.
///
/// This field is not intended to be set by the user, and is only used
/// internally.
#[builder_lite(skip)]
reg: Result<u32, ConfigError>,
/// The target frequency
#[builder_lite(skip_setter)]
frequency: Rate,
/// The clock source
#[cfg_attr(not(feature = "unstable"), builder_lite(skip))]
#[builder_lite(skip_setter)]
clock_source: ClockSource,
/// SPI sample/shift mode.
mode: Mode,
/// Bit order of the read data.
read_bit_order: BitOrder,
/// Bit order of the written data.
write_bit_order: BitOrder,
}
impl Default for Config {
fn default() -> Self {
let mut this = Config {
reg: Ok(0),
frequency: Rate::from_mhz(1),
clock_source: ClockSource::Apb,
mode: Mode::_0,
read_bit_order: BitOrder::MsbFirst,
write_bit_order: BitOrder::MsbFirst,
};
this.reg = this.recalculate();
this
}
}
impl Config {
/// Set the frequency of the SPI bus clock.
pub fn with_frequency(mut self, frequency: Rate) -> Self {
self.frequency = frequency;
self.reg = self.recalculate();
self
}
/// Set the clock source of the SPI bus.
#[instability::unstable]
pub fn with_clock_source(mut self, clock_source: ClockSource) -> Self {
self.clock_source = clock_source;
self.reg = self.recalculate();
self
}
fn recalculate(&self) -> Result<u32, ConfigError> {
// taken from https://github.com/apache/incubator-nuttx/blob/8267a7618629838231256edfa666e44b5313348e/arch/risc-v/src/esp32c3/esp32c3_spi.c#L496
let clocks = Clocks::get();
cfg_if::cfg_if! {
if #[cfg(esp32h2)] {
// ESP32-H2 is using PLL_48M_CLK source instead of APB_CLK
let apb_clk_freq = clocks.pll_48m_clock;
} else {
let apb_clk_freq = clocks.apb_clock;
}
}
let reg_val: u32;
let duty_cycle = 128;
// In HW, n, h and l fields range from 1 to 64, pre ranges from 1 to 8K.
// The value written to register is one lower than the used value.
if self.frequency > ((apb_clk_freq / 4) * 3) {
// Using APB frequency directly will give us the best result here.
reg_val = 1 << 31;
} else {
// For best duty cycle resolution, we want n to be as close to 32 as
// possible, but we also need a pre/n combo that gets us as close as
// possible to the intended frequency. To do this, we bruteforce n and
// calculate the best pre to go along with that. If there's a choice
// between pre/n combos that give the same result, use the one with the
// higher n.
let mut pre: i32;
let mut bestn: i32 = -1;
let mut bestpre: i32 = -1;
let mut besterr: i32 = 0;
let mut errval: i32;
let raw_freq = self.frequency.as_hz() as i32;
let raw_apb_freq = apb_clk_freq.as_hz() as i32;
// Start at n = 2. We need to be able to set h/l so we have at least
// one high and one low pulse.
for n in 2..64 {
// Effectively, this does:
// pre = round((APB_CLK_FREQ / n) / frequency)
pre = ((raw_apb_freq / n) + (raw_freq / 2)) / raw_freq;
if pre <= 0 {
pre = 1;
}
if pre > 16 {
pre = 16;
}
errval = (raw_apb_freq / (pre * n) - raw_freq).abs();
if bestn == -1 || errval <= besterr {
besterr = errval;
bestn = n;
bestpre = pre;
}
}
let n: i32 = bestn;
pre = bestpre;
let l: i32 = n;
// Effectively, this does:
// h = round((duty_cycle * n) / 256)
let mut h: i32 = (duty_cycle * n + 127) / 256;
if h <= 0 {
h = 1;
}
reg_val = (l as u32 - 1)
| ((h as u32 - 1) << 6)
| ((n as u32 - 1) << 12)
| ((pre as u32 - 1) << 18);
}
Ok(reg_val)
}
fn raw_clock_reg_value(&self) -> Result<u32, ConfigError> {
self.reg
}
fn validate(&self) -> Result<(), ConfigError> {
cfg_if::cfg_if! {
if #[cfg(esp32h2)] {
if self.frequency < Rate::from_khz(70) || self.frequency > Rate::from_mhz(48) {
return Err(ConfigError::UnsupportedFrequency);
}
} else {
if self.frequency < Rate::from_khz(70) || self.frequency > Rate::from_mhz(80) {
return Err(ConfigError::UnsupportedFrequency);
}
}
}
Ok(())
}
}
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
struct SpiPinGuard {
mosi_pin: PinGuard,
sclk_pin: PinGuard,
cs_pin: PinGuard,
sio1_pin: PinGuard,
sio2_pin: Option<PinGuard>,
sio3_pin: Option<PinGuard>,
}
/// Configuration errors.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ConfigError {
/// The requested frequency is not supported.
UnsupportedFrequency,
}
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::UnsupportedFrequency => {
write!(f, "The requested frequency is not supported")
}
}
}
}
/// SPI peripheral driver
///
/// ### SPI Initialization
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::spi::Mode;
/// # use esp_hal::spi::master::{Config, Spi};
/// let mut spi = Spi::new(
/// peripherals.SPI2,
/// Config::default().with_frequency(Rate::from_khz(100)).
/// with_mode(Mode::_0) )?
/// .with_sck(peripherals.GPIO0)
/// .with_mosi(peripherals.GPIO1)
/// .with_miso(peripherals.GPIO2);
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Spi<'d, Dm: DriverMode> {
spi: PeripheralRef<'d, AnySpi>,
_mode: PhantomData<Dm>,
guard: PeripheralGuard,
pins: SpiPinGuard,
}
impl<Dm: DriverMode> Sealed for Spi<'_, Dm> {}
impl<Dm> Spi<'_, Dm>
where
Dm: DriverMode,
{
fn driver(&self) -> Driver {
Driver {
info: self.spi.info(),
state: self.spi.state(),
}
}
/// Write bytes to SPI. After writing, flush is called to ensure all data
/// has been transmitted.
pub fn write(&mut self, words: &[u8]) -> Result<(), Error> {
self.driver().write(words)?;
self.driver().flush()?;
Ok(())
}
/// Read bytes from SPI. The provided slice is filled with data received
/// from the slave.
pub fn read(&mut self, words: &mut [u8]) -> Result<(), Error> {
self.driver().read(words)
}
/// Sends `words` to the slave. Returns the `words` received from the slave.
pub fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Error> {
self.driver().transfer(words)
}
}
impl<'d> Spi<'d, Blocking> {
/// Constructs an SPI instance in 8bit dataframe mode.
///
/// # Errors
///
/// See [`Spi::apply_config`].
pub fn new(
spi: impl Peripheral<P = impl PeripheralInstance> + 'd,
config: Config,
) -> Result<Self, ConfigError> {
crate::into_mapped_ref!(spi);
let guard = PeripheralGuard::new(spi.info().peripheral);
let mosi_pin = PinGuard::new_unconnected(spi.info().mosi);
let sclk_pin = PinGuard::new_unconnected(spi.info().sclk);
let cs_pin = PinGuard::new_unconnected(spi.info().cs);
let sio1_pin = PinGuard::new_unconnected(spi.info().sio1_output);
let sio2_pin = spi.info().sio2_output.map(PinGuard::new_unconnected);
let sio3_pin = spi.info().sio3_output.map(PinGuard::new_unconnected);
let mut this = Spi {
spi,
_mode: PhantomData,
guard,
pins: SpiPinGuard {
mosi_pin,
sclk_pin,
cs_pin,
sio1_pin,
sio2_pin,
sio3_pin,
},
};
this.driver().init();
this.apply_config(&config)?;
let this = this
.with_sio0(NoPin)
.with_sio1(NoPin)
.with_sck(NoPin)
.with_cs(NoPin);
let is_qspi = this.driver().info.sio2_input.is_some();
if is_qspi {
unwrap!(this.driver().info.sio2_input).connect_to(NoPin);
unwrap!(this.driver().info.sio2_output).connect_to(NoPin);
unwrap!(this.driver().info.sio3_input).connect_to(NoPin);
unwrap!(this.driver().info.sio3_output).connect_to(NoPin);
}
Ok(this)
}
/// Converts the SPI instance into async mode.
pub fn into_async(mut self) -> Spi<'d, Async> {
self.set_interrupt_handler(self.spi.handler());
Spi {
spi: self.spi,
_mode: PhantomData,
guard: self.guard,
pins: self.pins,
}
}
/// Configures the SPI instance to use DMA with the specified channel.
///
/// This method prepares the SPI instance for DMA transfers using SPI
/// and returns an instance of `SpiDma` that supports DMA
/// operations.
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::spi::Mode;
/// # use esp_hal::spi::master::{Config, Spi};
/// # use esp_hal::dma::{DmaRxBuf, DmaTxBuf};
/// # use esp_hal::dma_buffers;
#[cfg_attr(any(esp32, esp32s2), doc = "let dma_channel = peripherals.DMA_SPI2;")]
#[cfg_attr(
not(any(esp32, esp32s2)),
doc = "let dma_channel = peripherals.DMA_CH0;"
)]
/// let (rx_buffer, rx_descriptors, tx_buffer, tx_descriptors) =
/// dma_buffers!(32000);
///
/// let dma_rx_buf = DmaRxBuf::new(
/// rx_descriptors,
/// rx_buffer
/// )?;
///
/// let dma_tx_buf = DmaTxBuf::new(
/// tx_descriptors,
/// tx_buffer
/// )?;
///
/// let mut spi = Spi::new(
/// peripherals.SPI2,
/// Config::default().with_frequency(Rate::from_khz(100)).
/// with_mode(Mode::_0) )?
/// .with_dma(dma_channel)
/// .with_buffers(dma_rx_buf, dma_tx_buf);
/// # Ok(())
/// # }
/// ```
#[instability::unstable]
pub fn with_dma<CH>(self, channel: impl Peripheral<P = CH> + 'd) -> SpiDma<'d, Blocking>
where
CH: DmaChannelFor<AnySpi>,
{
SpiDma::new(
self.spi,
self.pins,
channel.map(|ch| ch.degrade()).into_ref(),
)
}
#[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::interrupt::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) {
let interrupt = self.driver().info.interrupt;
for core in Cpu::other() {
crate::interrupt::disable(core, interrupt);
}
unsafe { crate::interrupt::bind_interrupt(interrupt, handler.handler()) };
unwrap!(crate::interrupt::enable(interrupt, handler.priority()));
}
}
#[instability::unstable]
impl crate::interrupt::InterruptConfigurable for Spi<'_, Blocking> {
/// Sets the interrupt handler
///
/// Interrupts are not enabled at the peripheral level here.
fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
Spi::set_interrupt_handler(self, handler);
}
}
impl<'d> Spi<'d, Async> {
/// Converts the SPI instance into blocking mode.
pub fn into_blocking(self) -> Spi<'d, Blocking> {
crate::interrupt::disable(Cpu::current(), self.driver().info.interrupt);
Spi {
spi: self.spi,
_mode: PhantomData,
guard: self.guard,
pins: self.pins,
}
}
/// Waits for the completion of previous operations.
pub async fn flush_async(&mut self) -> Result<(), Error> {
let driver = self.driver();
if !driver.busy() {
return Ok(());
}
let future = SpiFuture::setup(&driver).await;
future.await;
Ok(())
}
/// Sends `words` to the slave. Returns the `words` received from the slave
pub async fn transfer_in_place_async(&mut self, words: &mut [u8]) -> Result<(), Error> {
// We need to flush because the blocking transfer functions may return while a
// transfer is still in progress.
self.flush_async().await?;
self.driver().transfer_in_place_async(words).await
}
}
impl<'d, Dm> Spi<'d, Dm>
where
Dm: DriverMode,
{
/// Assign the MOSI (Master Out Slave In) pin for the SPI instance.
///
/// Enables output functionality for the pin, and connects it as the MOSI
/// signal. You want to use this for full-duplex SPI or
/// if you intend to use [DataMode::SingleTwoDataLines].
///
/// Disconnects the previous pin that was assigned with `with_mosi` or
/// `with_sio0`.
pub fn with_mosi<MOSI: PeripheralOutput>(
mut self,
mosi: impl Peripheral<P = MOSI> + 'd,
) -> Self {
crate::into_mapped_ref!(mosi);
mosi.enable_output(false);
self.pins.mosi_pin = OutputConnection::connect_with_guard(mosi, self.driver().info.mosi);
self
}
/// Assign the SIO0 pin for the SPI instance.
///
/// Enables both input and output functionality for the pin, and connects it
/// to the MOSI signal and SIO0 input signal.
///
/// Disconnects the previous pin that was assigned with `with_sio0` or
/// `with_mosi`.
///
/// Use this if any of the devices on the bus use half-duplex SPI.
///
/// The pin is configured to open-drain mode.
///
/// Note: You do not need to call [Self::with_mosi] when this is used.
#[instability::unstable]
pub fn with_sio0<MOSI: PeripheralOutput>(
mut self,
mosi: impl Peripheral<P = MOSI> + 'd,
) -> Self {
crate::into_mapped_ref!(mosi);
mosi.enable_output(true);
mosi.enable_input(true);
self.driver().info.sio0_input.connect_to(&mut mosi);
self.pins.mosi_pin = OutputConnection::connect_with_guard(mosi, self.driver().info.mosi);
self
}
/// Assign the MISO (Master In Slave Out) pin for the SPI instance.
///
/// Enables input functionality for the pin, and connects it to the MISO
/// signal.
///
/// You want to use this for full-duplex SPI or
/// [DataMode::SingleTwoDataLines]
pub fn with_miso<MISO: PeripheralInput>(self, miso: impl Peripheral<P = MISO> + 'd) -> Self {
crate::into_mapped_ref!(miso);
miso.enable_input(true);
self.driver().info.miso.connect_to(miso);
self
}
/// Assign the SIO1/MISO pin for the SPI instance.
///
/// Enables both input and output functionality for the pin, and connects it
/// to the MISO signal and SIO1 input signal.
///
/// Disconnects the previous pin that was assigned with `with_sio1`.
///
/// Use this if any of the devices on the bus use half-duplex SPI.
///
/// The pin is configured to open-drain mode.
///
/// Note: You do not need to call [Self::with_miso] when this is used.
#[instability::unstable]
pub fn with_sio1<SIO1: PeripheralOutput>(
mut self,
miso: impl Peripheral<P = SIO1> + 'd,
) -> Self {
crate::into_mapped_ref!(miso);
miso.enable_input(true);
miso.enable_output(true);
self.driver().info.miso.connect_to(&mut miso);
self.pins.sio1_pin =
OutputConnection::connect_with_guard(miso, self.driver().info.sio1_output);
self
}
/// Assign the SCK (Serial Clock) pin for the SPI instance.
///
/// Configures the specified pin to push-pull output and connects it to the
/// SPI clock signal.
///
/// Disconnects the previous pin that was assigned with `with_sck`.
pub fn with_sck<SCK: PeripheralOutput>(mut self, sclk: impl Peripheral<P = SCK> + 'd) -> Self {
crate::into_mapped_ref!(sclk);
sclk.set_to_push_pull_output();
self.pins.sclk_pin = OutputConnection::connect_with_guard(sclk, self.driver().info.sclk);
self
}
/// Assign the CS (Chip Select) pin for the SPI instance.
///
/// Configures the specified pin to push-pull output and connects it to the
/// SPI CS signal.
///
/// Disconnects the previous pin that was assigned with `with_cs`.
///
/// # Current Stability Limitations
/// The hardware chip select functionality is limited; only one CS line can
/// be set, regardless of the total number available. There is no
/// mechanism to select which CS line to use.
#[instability::unstable]
pub fn with_cs<CS: PeripheralOutput>(mut self, cs: impl Peripheral<P = CS> + 'd) -> Self {
crate::into_mapped_ref!(cs);
cs.set_to_push_pull_output();
self.pins.cs_pin = OutputConnection::connect_with_guard(cs, self.driver().info.cs);
self
}
/// Change the bus configuration.
///
/// # Errors
///
/// If frequency passed in config exceeds
#[cfg_attr(not(esp32h2), doc = " 80MHz")]
#[cfg_attr(esp32h2, doc = " 48MHz")]
/// or is below 70kHz,
/// [`ConfigError::UnsupportedFrequency`] error will be returned.
pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.driver().apply_config(config)
}
}
#[instability::unstable]
impl<Dm> embassy_embedded_hal::SetConfig for Spi<'_, Dm>
where
Dm: DriverMode,
{
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
impl<'d, Dm> Spi<'d, Dm>
where
Dm: DriverMode,
{
/// Assign the SIO2 pin for the SPI instance.
///
/// Enables both input and output functionality for the pin, and connects it
/// to the SIO2 output and input signals.
///
/// # Current Stability Limitations
/// QSPI operations are unstable, associated pins configuration is
/// inefficient.
#[instability::unstable]
pub fn with_sio2<SIO2: PeripheralOutput>(
mut self,
sio2: impl Peripheral<P = SIO2> + 'd,
) -> Self {
// TODO: panic if not QSPI?
crate::into_mapped_ref!(sio2);
sio2.enable_input(true);
sio2.enable_output(true);
unwrap!(self.driver().info.sio2_input).connect_to(&mut sio2);
self.pins.sio2_pin = self
.driver()
.info
.sio2_output
.map(|signal| OutputConnection::connect_with_guard(sio2, signal));
self
}
/// Assign the SIO3 pin for the SPI instance.
///
/// Enables both input and output functionality for the pin, and connects it
/// to the SIO3 output and input signals.
///
/// # Current Stability Limitations
/// QSPI operations are unstable, associated pins configuration is
/// inefficient.
#[instability::unstable]
pub fn with_sio3<SIO3: PeripheralOutput>(
mut self,
sio3: impl Peripheral<P = SIO3> + 'd,
) -> Self {
// TODO: panic if not QSPI?
crate::into_mapped_ref!(sio3);
sio3.enable_input(true);
sio3.enable_output(true);
unwrap!(self.driver().info.sio3_input).connect_to(&mut sio3);
self.pins.sio3_pin = self
.driver()
.info
.sio3_output
.map(|signal| OutputConnection::connect_with_guard(sio3, signal));
self
}
}
impl<Dm> Spi<'_, Dm>
where
Dm: DriverMode,
{
/// Half-duplex read.
///
/// # Errors
///
/// [`Error::FifoSizeExeeded`] or [`Error::Unsupported`] will be returned if
/// passed buffer is bigger than FIFO size or if buffer is empty (currently
/// unsupported). `DataMode::Single` cannot be combined with any other
/// [`DataMode`], otherwise [`Error::Unsupported`] will be returned.
#[instability::unstable]
pub fn half_duplex_read(
&mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &mut [u8],
) -> Result<(), Error> {
if buffer.len() > FIFO_SIZE {
return Err(Error::FifoSizeExeeded);
}
if buffer.is_empty() {
return Err(Error::Unsupported);
}
self.driver().setup_half_duplex(
false,
cmd,
address,
false,
dummy,
buffer.is_empty(),
data_mode,
)?;
self.driver().configure_datalen(buffer.len(), 0);
self.driver().start_operation();
self.driver().flush()?;
self.driver().read_from_fifo(buffer)
}
/// Half-duplex write.
///
/// # Errors
///
/// [`Error::FifoSizeExeeded`] will be returned if
/// passed buffer is bigger than FIFO size.
#[cfg_attr(
esp32,
doc = "Dummy phase configuration is currently not supported, only value `0` is valid (see issue [#2240](https://github.com/esp-rs/esp-hal/issues/2240))."
)]
#[instability::unstable]
pub fn half_duplex_write(
&mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &[u8],
) -> Result<(), Error> {
if buffer.len() > FIFO_SIZE {
return Err(Error::FifoSizeExeeded);
}
cfg_if::cfg_if! {
if #[cfg(all(esp32, spi_address_workaround))] {
let mut buffer = buffer;
let mut data_mode = data_mode;
let mut address = address;
let addr_bytes;
if buffer.is_empty() && !address.is_none() {
// If the buffer is empty, we need to send a dummy byte
// to trigger the address phase.
let bytes_to_write = address.width().div_ceil(8);
// The address register is read in big-endian order,
// we have to prepare the emulated write in the same way.
addr_bytes = address.value().to_be_bytes();
buffer = &addr_bytes[4 - bytes_to_write..][..bytes_to_write];
data_mode = address.mode();
address = Address::None;
}
if dummy > 0 {
// FIXME: https://github.com/esp-rs/esp-hal/issues/2240
return Err(Error::Unsupported);
}
}
}
self.driver().setup_half_duplex(
true,
cmd,
address,
false,
dummy,
buffer.is_empty(),
data_mode,
)?;
if !buffer.is_empty() {
// re-using the full-duplex write here
self.driver().write(buffer)?;
} else {
self.driver().start_operation();
}
self.driver().flush()
}
}
mod dma {
use core::{
cmp::min,
mem::ManuallyDrop,
sync::atomic::{fence, Ordering},
};
use super::*;
use crate::dma::{
asynch::{DmaRxFuture, DmaTxFuture},
Channel,
DmaRxBuf,
DmaTxBuf,
EmptyBuf,
PeripheralDmaChannel,
};
/// A DMA capable SPI instance.
///
/// Using `SpiDma` is not recommended unless you wish
/// to manage buffers yourself. It's recommended to use
/// [`SpiDmaBus`] via `with_buffers` to get access
/// to a DMA capable SPI bus that implements the
/// embedded-hal traits.
/// ```rust, no_run
#[doc = crate::before_snippet!()]
/// # use esp_hal::spi::Mode;
/// # use esp_hal::spi::master::{Config, Spi};
/// # use esp_hal::dma::{DmaRxBuf, DmaTxBuf};
/// # use esp_hal::dma_buffers;
#[cfg_attr(any(esp32, esp32s2), doc = "let dma_channel = peripherals.DMA_SPI2;")]
#[cfg_attr(
not(any(esp32, esp32s2)),
doc = "let dma_channel = peripherals.DMA_CH0;"
)]
/// let (rx_buffer, rx_descriptors, tx_buffer, tx_descriptors) =
/// dma_buffers!(32000);
///
/// let dma_rx_buf = DmaRxBuf::new(
/// rx_descriptors,
/// rx_buffer
/// )?;
///
/// let dma_tx_buf = DmaTxBuf::new(
/// tx_descriptors,
/// tx_buffer
/// )?;
///
/// let mut spi = Spi::new(
/// peripherals.SPI2,
/// Config::default().with_frequency(Rate::from_khz(100)).
/// with_mode(Mode::_0) )?
/// .with_dma(dma_channel)
/// .with_buffers(dma_rx_buf, dma_tx_buf);
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SpiDma<'d, Dm>
where
Dm: DriverMode,
{
pub(crate) spi: PeripheralRef<'d, AnySpi>,
pub(crate) channel: Channel<'d, Dm, PeripheralDmaChannel<AnySpi>>,
tx_transfer_in_progress: bool,
rx_transfer_in_progress: bool,
#[cfg(all(esp32, spi_address_workaround))]
address_buffer: DmaTxBuf,
guard: PeripheralGuard,
pins: SpiPinGuard,
}
impl<Dm> crate::private::Sealed for SpiDma<'_, Dm> where Dm: DriverMode {}
impl<'d> SpiDma<'d, Blocking> {
/// Converts the SPI instance into async mode.
#[instability::unstable]
pub fn into_async(self) -> SpiDma<'d, Async> {
SpiDma {
spi: self.spi,
channel: self.channel.into_async(),
tx_transfer_in_progress: self.tx_transfer_in_progress,
rx_transfer_in_progress: self.rx_transfer_in_progress,
#[cfg(all(esp32, spi_address_workaround))]
address_buffer: self.address_buffer,
guard: self.guard,
pins: self.pins,
}
}
}
impl<'d> SpiDma<'d, Async> {
/// Converts the SPI instance into async mode.
#[instability::unstable]
pub fn into_blocking(self) -> SpiDma<'d, Blocking> {
SpiDma {
spi: self.spi,
channel: self.channel.into_blocking(),
tx_transfer_in_progress: self.tx_transfer_in_progress,
rx_transfer_in_progress: self.rx_transfer_in_progress,
#[cfg(all(esp32, spi_address_workaround))]
address_buffer: self.address_buffer,
guard: self.guard,
pins: self.pins,
}
}
}
impl<Dm> core::fmt::Debug for SpiDma<'_, Dm>
where
Dm: DriverMode,
{
/// Formats the `SpiDma` instance for debugging purposes.
///
/// This method returns a debug struct with the name "SpiDma" without
/// exposing internal details.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("SpiDma").field("spi", &self.spi).finish()
}
}
#[instability::unstable]
impl crate::interrupt::InterruptConfigurable for SpiDma<'_, Blocking> {
/// Sets the interrupt handler
///
/// Interrupts are not enabled at the peripheral level here.
fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
let interrupt = self.driver().info.interrupt;
for core in crate::system::Cpu::other() {
crate::interrupt::disable(core, interrupt);
}
unsafe { crate::interrupt::bind_interrupt(interrupt, handler.handler()) };
unwrap!(crate::interrupt::enable(interrupt, handler.priority()));
}
}
impl SpiDma<'_, Blocking> {
/// Listen for the given interrupts
#[instability::unstable]
pub fn listen(&mut self, interrupts: impl Into<EnumSet<SpiInterrupt>>) {
self.driver().enable_listen(interrupts.into(), true);
}
/// Unlisten the given interrupts
#[instability::unstable]
pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<SpiInterrupt>>) {
self.driver().enable_listen(interrupts.into(), false);
}
/// Gets asserted interrupts
#[instability::unstable]
pub fn interrupts(&mut self) -> EnumSet<SpiInterrupt> {
self.driver().interrupts()
}
/// Resets asserted interrupts
#[instability::unstable]
pub fn clear_interrupts(&mut self, interrupts: impl Into<EnumSet<SpiInterrupt>>) {
self.driver().clear_interrupts(interrupts.into());
}
}
impl<'d> SpiDma<'d, Blocking> {
pub(super) fn new(
spi: PeripheralRef<'d, AnySpi>,
pins: SpiPinGuard,
channel: PeripheralRef<'d, PeripheralDmaChannel<AnySpi>>,
) -> Self {
let channel = Channel::new(channel);
channel.runtime_ensure_compatible(&spi);
#[cfg(all(esp32, spi_address_workaround))]
let address_buffer = {
use crate::dma::DmaDescriptor;
const SPI_NUM: usize = 2;
static mut DESCRIPTORS: [[DmaDescriptor; 1]; SPI_NUM] =
[[DmaDescriptor::EMPTY]; SPI_NUM];
static mut BUFFERS: [[u32; 1]; SPI_NUM] = [[0; 1]; SPI_NUM];
let id = if spi.info() == unsafe { crate::peripherals::SPI2::steal().info() } {
0
} else {
1
};
unwrap!(DmaTxBuf::new(
unsafe { &mut DESCRIPTORS[id] },
crate::dma::as_mut_byte_array!(BUFFERS[id], 4)
))
};
let guard = PeripheralGuard::new(spi.info().peripheral);
Self {
spi,
channel,
#[cfg(all(esp32, spi_address_workaround))]
address_buffer,
tx_transfer_in_progress: false,
rx_transfer_in_progress: false,
guard,
pins,
}
}
}
impl<'d, Dm> SpiDma<'d, Dm>
where
Dm: DriverMode,
{
fn driver(&self) -> Driver {
Driver {
info: self.spi.info(),
state: self.spi.state(),
}
}
fn dma_driver(&self) -> DmaDriver {
DmaDriver {
driver: self.driver(),
dma_peripheral: self.spi.dma_peripheral(),
}
}
fn is_done(&self) -> bool {
if self.tx_transfer_in_progress && !self.channel.tx.is_done() {
return false;
}
if self.driver().busy() {
return false;
}
if self.rx_transfer_in_progress {
// If this is an asymmetric transfer and the RX side is smaller, the RX channel
// will never be "done" as it won't have enough descriptors/buffer to receive
// the EOF bit from the SPI. So instead the RX channel will hit
// a "descriptor empty" which means the DMA is written as much
// of the received data as possible into the buffer and
// discarded the rest. The user doesn't care about this discarded data.
if !self.channel.rx.is_done() && !self.channel.rx.has_dscr_empty_error() {
return false;
}
}
true
}
fn wait_for_idle(&mut self) {
while !self.is_done() {
// Wait for the SPI to become idle
}
self.rx_transfer_in_progress = false;
self.tx_transfer_in_progress = false;
fence(Ordering::Acquire);
}
async fn wait_for_idle_async(&mut self) {
// As a future enhancement, setup Spi Future in here as well.
if self.rx_transfer_in_progress {
_ = DmaRxFuture::new(&mut self.channel.rx).await;
self.rx_transfer_in_progress = false;
}
if self.tx_transfer_in_progress {
_ = DmaTxFuture::new(&mut self.channel.tx).await;
self.tx_transfer_in_progress = false;
}
core::future::poll_fn(|cx| {
use core::task::Poll;
if self.is_done() {
Poll::Ready(())
} else {
cx.waker().wake_by_ref();
Poll::Pending
}
})
.await;
}
/// # Safety:
///
/// The caller must ensure to not access the buffer contents while the
/// transfer is in progress. Moving the buffer itself is allowed.
#[cfg_attr(place_spi_driver_in_ram, ram)]
unsafe fn start_transfer_dma<RX: DmaRxBuffer, TX: DmaTxBuffer>(
&mut self,
full_duplex: bool,
bytes_to_read: usize,
bytes_to_write: usize,
rx_buffer: &mut RX,
tx_buffer: &mut TX,
) -> Result<(), Error> {
if bytes_to_read > MAX_DMA_SIZE || bytes_to_write > MAX_DMA_SIZE {
return Err(Error::MaxDmaTransferSizeExceeded);
}
self.rx_transfer_in_progress = bytes_to_read > 0;
self.tx_transfer_in_progress = bytes_to_write > 0;
unsafe {
self.dma_driver().start_transfer_dma(
full_duplex,
bytes_to_read,
bytes_to_write,
rx_buffer,
tx_buffer,
&mut self.channel.rx,
&mut self.channel.tx,
)
}
}
#[cfg(all(esp32, spi_address_workaround))]
fn set_up_address_workaround(
&mut self,
cmd: Command,
address: Address,
dummy: u8,
) -> Result<(), Error> {
if dummy > 0 {
// FIXME: https://github.com/esp-rs/esp-hal/issues/2240
return Err(Error::Unsupported);
}
let bytes_to_write = address.width().div_ceil(8);
// The address register is read in big-endian order,
// we have to prepare the emulated write in the same way.
let addr_bytes = address.value().to_be_bytes();
let addr_bytes = &addr_bytes[4 - bytes_to_write..][..bytes_to_write];
self.address_buffer.fill(addr_bytes);
self.driver().setup_half_duplex(
true,
cmd,
Address::None,
false,
dummy,
bytes_to_write == 0,
address.mode(),
)?;
// FIXME: we could use self.start_transfer_dma if the address buffer was part of
// the (yet-to-be-created) State struct.
self.tx_transfer_in_progress = true;
unsafe {
self.dma_driver().start_transfer_dma(
false,
0,
bytes_to_write,
&mut EmptyBuf,
&mut self.address_buffer,
&mut self.channel.rx,
&mut self.channel.tx,
)
}
}
fn cancel_transfer(&mut self) {
// The SPI peripheral is controlling how much data we transfer, so let's
// update its counter.
// 0 doesn't take effect on ESP32 and cuts the currently transmitted byte
// immediately.
// 1 seems to stop after transmitting the current byte which is somewhat less
// impolite.
if self.tx_transfer_in_progress || self.rx_transfer_in_progress {
self.dma_driver().abort_transfer();
// We need to stop the DMA transfer, too.
if self.tx_transfer_in_progress {
self.channel.tx.stop_transfer();
self.tx_transfer_in_progress = false;
}
if self.rx_transfer_in_progress {
self.channel.rx.stop_transfer();
self.rx_transfer_in_progress = false;
}
}
}
/// Change the bus configuration.
///
/// # Errors
///
/// If frequency passed in config exceeds
#[cfg_attr(not(esp32h2), doc = " 80MHz")]
#[cfg_attr(esp32h2, doc = " 48MHz")]
/// or is below 70kHz,
/// [`ConfigError::UnsupportedFrequency`] error will be returned.
#[instability::unstable]
pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.driver().apply_config(config)
}
/// Configures the DMA buffers for the SPI instance.
///
/// This method sets up both RX and TX buffers for DMA transfers.
/// It returns an instance of `SpiDmaBus` that can be used for SPI
/// communication.
#[instability::unstable]
pub fn with_buffers(self, dma_rx_buf: DmaRxBuf, dma_tx_buf: DmaTxBuf) -> SpiDmaBus<'d, Dm> {
SpiDmaBus::new(self, dma_rx_buf, dma_tx_buf)
}
}
#[instability::unstable]
impl<Dm> embassy_embedded_hal::SetConfig for SpiDma<'_, Dm>
where
Dm: DriverMode,
{
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
/// A structure representing a DMA transfer for SPI.
///
/// This structure holds references to the SPI instance, DMA buffers, and
/// transfer status.
#[instability::unstable]
pub struct SpiDmaTransfer<'d, Dm, Buf>
where
Dm: DriverMode,
{
spi_dma: ManuallyDrop<SpiDma<'d, Dm>>,
dma_buf: ManuallyDrop<Buf>,
}
impl<'d, Dm, Buf> SpiDmaTransfer<'d, Dm, Buf>
where
Dm: DriverMode,
{
fn new(spi_dma: SpiDma<'d, Dm>, dma_buf: Buf) -> Self {
Self {
spi_dma: ManuallyDrop::new(spi_dma),
dma_buf: ManuallyDrop::new(dma_buf),
}
}
/// Checks if the transfer is complete.
///
/// This method returns `true` if both RX and TX operations are done,
/// and the SPI instance is no longer busy.
pub fn is_done(&self) -> bool {
self.spi_dma.is_done()
}
/// Waits for the DMA transfer to complete.
///
/// This method blocks until the transfer is finished and returns the
/// `SpiDma` instance and the associated buffer.
#[instability::unstable]
pub fn wait(mut self) -> (SpiDma<'d, Dm>, Buf) {
self.spi_dma.wait_for_idle();
let retval = unsafe {
(
ManuallyDrop::take(&mut self.spi_dma),
ManuallyDrop::take(&mut self.dma_buf),
)
};
core::mem::forget(self);
retval
}
/// Cancels the DMA transfer.
#[instability::unstable]
pub fn cancel(&mut self) {
if !self.spi_dma.is_done() {
self.spi_dma.cancel_transfer();
}
}
}
impl<Dm, Buf> Drop for SpiDmaTransfer<'_, Dm, Buf>
where
Dm: DriverMode,
{
fn drop(&mut self) {
if !self.is_done() {
self.spi_dma.cancel_transfer();
self.spi_dma.wait_for_idle();
unsafe {
ManuallyDrop::drop(&mut self.spi_dma);
ManuallyDrop::drop(&mut self.dma_buf);
}
}
}
}
impl<Buf> SpiDmaTransfer<'_, Async, Buf> {
/// Waits for the DMA transfer to complete asynchronously.
///
/// This method awaits the completion of both RX and TX operations.
#[instability::unstable]
pub async fn wait_for_done(&mut self) {
self.spi_dma.wait_for_idle_async().await;
}
}
impl<'d, Dm> SpiDma<'d, Dm>
where
Dm: DriverMode,
{
/// # Safety:
///
/// The caller must ensure that the buffers are not accessed while the
/// transfer is in progress. Moving the buffers is allowed.
#[cfg_attr(place_spi_driver_in_ram, ram)]
unsafe fn start_dma_write(
&mut self,
bytes_to_write: usize,
buffer: &mut impl DmaTxBuffer,
) -> Result<(), Error> {
self.start_dma_transfer(0, bytes_to_write, &mut EmptyBuf, buffer)
}
/// Perform a DMA write.
///
/// This will return a [SpiDmaTransfer] owning the buffer and the
/// SPI instance. The maximum amount of data to be sent is 32736
/// bytes.
#[allow(clippy::type_complexity)]
#[cfg_attr(place_spi_driver_in_ram, ram)]
#[instability::unstable]
pub fn write<TX: DmaTxBuffer>(
mut self,
bytes_to_write: usize,
mut buffer: TX,
) -> Result<SpiDmaTransfer<'d, Dm, TX>, (Error, Self, TX)> {
self.wait_for_idle();
match unsafe { self.start_dma_write(bytes_to_write, &mut buffer) } {
Ok(_) => Ok(SpiDmaTransfer::new(self, buffer)),
Err(e) => Err((e, self, buffer)),
}
}
/// # Safety:
///
/// The caller must ensure that the buffers are not accessed while the
/// transfer is in progress. Moving the buffers is allowed.
#[cfg_attr(place_spi_driver_in_ram, ram)]
unsafe fn start_dma_read(
&mut self,
bytes_to_read: usize,
buffer: &mut impl DmaRxBuffer,
) -> Result<(), Error> {
self.start_dma_transfer(bytes_to_read, 0, buffer, &mut EmptyBuf)
}
/// Perform a DMA read.
///
/// This will return a [SpiDmaTransfer] owning the buffer and
/// the SPI instance. The maximum amount of data to be
/// received is 32736 bytes.
#[allow(clippy::type_complexity)]
#[cfg_attr(place_spi_driver_in_ram, ram)]
#[instability::unstable]
pub fn read<RX: DmaRxBuffer>(
mut self,
bytes_to_read: usize,
mut buffer: RX,
) -> Result<SpiDmaTransfer<'d, Dm, RX>, (Error, Self, RX)> {
self.wait_for_idle();
match unsafe { self.start_dma_read(bytes_to_read, &mut buffer) } {
Ok(_) => Ok(SpiDmaTransfer::new(self, buffer)),
Err(e) => Err((e, self, buffer)),
}
}
/// # Safety:
///
/// The caller must ensure that the buffers are not accessed while the
/// transfer is in progress. Moving the buffers is allowed.
#[cfg_attr(place_spi_driver_in_ram, ram)]
unsafe fn start_dma_transfer(
&mut self,
bytes_to_read: usize,
bytes_to_write: usize,
rx_buffer: &mut impl DmaRxBuffer,
tx_buffer: &mut impl DmaTxBuffer,
) -> Result<(), Error> {
self.start_transfer_dma(true, bytes_to_read, bytes_to_write, rx_buffer, tx_buffer)
}
/// Perform a DMA transfer
///
/// This will return a [SpiDmaTransfer] owning the buffers and
/// the SPI instance. The maximum amount of data to be
/// sent/received is 32736 bytes.
#[allow(clippy::type_complexity)]
#[cfg_attr(place_spi_driver_in_ram, ram)]
#[instability::unstable]
pub fn transfer<RX: DmaRxBuffer, TX: DmaTxBuffer>(
mut self,
bytes_to_read: usize,
mut rx_buffer: RX,
bytes_to_write: usize,
mut tx_buffer: TX,
) -> Result<SpiDmaTransfer<'d, Dm, (RX, TX)>, (Error, Self, RX, TX)> {
self.wait_for_idle();
match unsafe {
self.start_dma_transfer(
bytes_to_read,
bytes_to_write,
&mut rx_buffer,
&mut tx_buffer,
)
} {
Ok(_) => Ok(SpiDmaTransfer::new(self, (rx_buffer, tx_buffer))),
Err(e) => Err((e, self, rx_buffer, tx_buffer)),
}
}
/// # Safety:
///
/// The caller must ensure that the buffers are not accessed while the
/// transfer is in progress. Moving the buffers is allowed.
#[cfg_attr(place_spi_driver_in_ram, ram)]
unsafe fn start_half_duplex_read(
&mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
bytes_to_read: usize,
buffer: &mut impl DmaRxBuffer,
) -> Result<(), Error> {
self.driver().setup_half_duplex(
false,
cmd,
address,
false,
dummy,
bytes_to_read == 0,
data_mode,
)?;
self.start_transfer_dma(false, bytes_to_read, 0, buffer, &mut EmptyBuf)
}
/// Perform a half-duplex read operation using DMA.
#[allow(clippy::type_complexity)]
#[cfg_attr(place_spi_driver_in_ram, ram)]
#[instability::unstable]
pub fn half_duplex_read<RX: DmaRxBuffer>(
mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
bytes_to_read: usize,
mut buffer: RX,
) -> Result<SpiDmaTransfer<'d, Dm, RX>, (Error, Self, RX)> {
self.wait_for_idle();
match unsafe {
self.start_half_duplex_read(
data_mode,
cmd,
address,
dummy,
bytes_to_read,
&mut buffer,
)
} {
Ok(_) => Ok(SpiDmaTransfer::new(self, buffer)),
Err(e) => Err((e, self, buffer)),
}
}
/// # Safety:
///
/// The caller must ensure that the buffers are not accessed while the
/// transfer is in progress. Moving the buffers is allowed.
#[cfg_attr(place_spi_driver_in_ram, ram)]
unsafe fn start_half_duplex_write(
&mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
bytes_to_write: usize,
buffer: &mut impl DmaTxBuffer,
) -> Result<(), Error> {
#[cfg(all(esp32, spi_address_workaround))]
{
// On the ESP32, if we don't have data, the address is always sent
// on a single line, regardless of its data mode.
if bytes_to_write == 0 && address.mode() != DataMode::SingleTwoDataLines {
return self.set_up_address_workaround(cmd, address, dummy);
}
}
self.driver().setup_half_duplex(
true,
cmd,
address,
false,
dummy,
bytes_to_write == 0,
data_mode,
)?;
self.start_transfer_dma(false, 0, bytes_to_write, &mut EmptyBuf, buffer)
}
/// Perform a half-duplex write operation using DMA.
#[allow(clippy::type_complexity)]
#[cfg_attr(place_spi_driver_in_ram, ram)]
#[instability::unstable]
pub fn half_duplex_write<TX: DmaTxBuffer>(
mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
bytes_to_write: usize,
mut buffer: TX,
) -> Result<SpiDmaTransfer<'d, Dm, TX>, (Error, Self, TX)> {
self.wait_for_idle();
match unsafe {
self.start_half_duplex_write(
data_mode,
cmd,
address,
dummy,
bytes_to_write,
&mut buffer,
)
} {
Ok(_) => Ok(SpiDmaTransfer::new(self, buffer)),
Err(e) => Err((e, self, buffer)),
}
}
}
/// A DMA-capable SPI bus.
///
/// This structure is responsible for managing SPI transfers using DMA
/// buffers.
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub struct SpiDmaBus<'d, Dm>
where
Dm: DriverMode,
{
spi_dma: SpiDma<'d, Dm>,
rx_buf: DmaRxBuf,
tx_buf: DmaTxBuf,
}
impl<Dm> crate::private::Sealed for SpiDmaBus<'_, Dm> where Dm: DriverMode {}
impl<'d> SpiDmaBus<'d, Blocking> {
/// Converts the SPI instance into async mode.
#[instability::unstable]
pub fn into_async(self) -> SpiDmaBus<'d, Async> {
SpiDmaBus {
spi_dma: self.spi_dma.into_async(),
rx_buf: self.rx_buf,
tx_buf: self.tx_buf,
}
}
}
impl<'d> SpiDmaBus<'d, Async> {
/// Converts the SPI instance into async mode.
#[instability::unstable]
pub fn into_blocking(self) -> SpiDmaBus<'d, Blocking> {
SpiDmaBus {
spi_dma: self.spi_dma.into_blocking(),
rx_buf: self.rx_buf,
tx_buf: self.tx_buf,
}
}
}
impl<'d, Dm> SpiDmaBus<'d, Dm>
where
Dm: DriverMode,
{
/// Creates a new `SpiDmaBus` with the specified SPI instance and DMA
/// buffers.
pub fn new(spi_dma: SpiDma<'d, Dm>, rx_buf: DmaRxBuf, tx_buf: DmaTxBuf) -> Self {
Self {
spi_dma,
rx_buf,
tx_buf,
}
}
/// Splits [SpiDmaBus] back into [SpiDma], [DmaRxBuf] and [DmaTxBuf].
#[instability::unstable]
pub fn split(mut self) -> (SpiDma<'d, Dm>, DmaRxBuf, DmaTxBuf) {
self.wait_for_idle();
(self.spi_dma, self.rx_buf, self.tx_buf)
}
}
#[instability::unstable]
impl crate::interrupt::InterruptConfigurable for SpiDmaBus<'_, Blocking> {
/// Sets the interrupt handler
///
/// Interrupts are not enabled at the peripheral level here.
fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
self.spi_dma.set_interrupt_handler(handler);
}
}
impl SpiDmaBus<'_, Blocking> {
/// Listen for the given interrupts
#[instability::unstable]
pub fn listen(&mut self, interrupts: impl Into<EnumSet<SpiInterrupt>>) {
self.spi_dma.listen(interrupts.into());
}
/// Unlisten the given interrupts
#[instability::unstable]
pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<SpiInterrupt>>) {
self.spi_dma.unlisten(interrupts.into());
}
/// Gets asserted interrupts
#[instability::unstable]
pub fn interrupts(&mut self) -> EnumSet<SpiInterrupt> {
self.spi_dma.interrupts()
}
/// Resets asserted interrupts
#[instability::unstable]
pub fn clear_interrupts(&mut self, interrupts: impl Into<EnumSet<SpiInterrupt>>) {
self.spi_dma.clear_interrupts(interrupts.into());
}
}
impl<Dm> SpiDmaBus<'_, Dm>
where
Dm: DriverMode,
{
fn wait_for_idle(&mut self) {
self.spi_dma.wait_for_idle();
}
/// Change the bus configuration.
///
/// # Errors
///
/// If frequency passed in config exceeds
#[cfg_attr(not(esp32h2), doc = " 80MHz")]
#[cfg_attr(esp32h2, doc = " 48MHz")]
/// or is below 70kHz,
/// [`ConfigError::UnsupportedFrequency`] error will be returned.
#[instability::unstable]
pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.spi_dma.apply_config(config)
}
/// Reads data from the SPI bus using DMA.
#[instability::unstable]
pub fn read(&mut self, words: &mut [u8]) -> Result<(), Error> {
self.wait_for_idle();
for chunk in words.chunks_mut(self.rx_buf.capacity()) {
self.rx_buf.set_length(chunk.len());
unsafe {
self.spi_dma.start_dma_transfer(
chunk.len(),
0,
&mut self.rx_buf,
&mut EmptyBuf,
)?;
}
self.wait_for_idle();
let bytes_read = self.rx_buf.read_received_data(chunk);
debug_assert_eq!(bytes_read, chunk.len());
}
Ok(())
}
/// Writes data to the SPI bus using DMA.
#[instability::unstable]
pub fn write(&mut self, words: &[u8]) -> Result<(), Error> {
self.wait_for_idle();
for chunk in words.chunks(self.tx_buf.capacity()) {
self.tx_buf.fill(chunk);
unsafe {
self.spi_dma.start_dma_transfer(
0,
chunk.len(),
&mut EmptyBuf,
&mut self.tx_buf,
)?;
}
self.wait_for_idle();
}
Ok(())
}
/// Transfers data to and from the SPI bus simultaneously using DMA.
#[instability::unstable]
pub fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Error> {
self.wait_for_idle();
let chunk_size = min(self.tx_buf.capacity(), self.rx_buf.capacity());
let common_length = min(read.len(), write.len());
let (read_common, read_remainder) = read.split_at_mut(common_length);
let (write_common, write_remainder) = write.split_at(common_length);
for (read_chunk, write_chunk) in read_common
.chunks_mut(chunk_size)
.zip(write_common.chunks(chunk_size))
{
self.tx_buf.fill(write_chunk);
self.rx_buf.set_length(read_chunk.len());
unsafe {
self.spi_dma.start_dma_transfer(
read_chunk.len(),
write_chunk.len(),
&mut self.rx_buf,
&mut self.tx_buf,
)?;
}
self.wait_for_idle();
let bytes_read = self.rx_buf.read_received_data(read_chunk);
debug_assert_eq!(bytes_read, read_chunk.len());
}
if !read_remainder.is_empty() {
self.read(read_remainder)
} else if !write_remainder.is_empty() {
self.write(write_remainder)
} else {
Ok(())
}
}
/// Transfers data in place on the SPI bus using DMA.
#[instability::unstable]
pub fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Error> {
self.wait_for_idle();
let chunk_size = min(self.tx_buf.capacity(), self.rx_buf.capacity());
for chunk in words.chunks_mut(chunk_size) {
self.tx_buf.fill(chunk);
self.rx_buf.set_length(chunk.len());
unsafe {
self.spi_dma.start_dma_transfer(
chunk.len(),
chunk.len(),
&mut self.rx_buf,
&mut self.tx_buf,
)?;
}
self.wait_for_idle();
let bytes_read = self.rx_buf.read_received_data(chunk);
debug_assert_eq!(bytes_read, chunk.len());
}
Ok(())
}
/// Half-duplex read.
#[instability::unstable]
pub fn half_duplex_read(
&mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &mut [u8],
) -> Result<(), Error> {
if buffer.len() > self.rx_buf.capacity() {
return Err(Error::from(DmaError::Overflow));
}
self.wait_for_idle();
self.rx_buf.set_length(buffer.len());
unsafe {
self.spi_dma.start_half_duplex_read(
data_mode,
cmd,
address,
dummy,
buffer.len(),
&mut self.rx_buf,
)?;
}
self.wait_for_idle();
let bytes_read = self.rx_buf.read_received_data(buffer);
debug_assert_eq!(bytes_read, buffer.len());
Ok(())
}
/// Half-duplex write.
#[instability::unstable]
pub fn half_duplex_write(
&mut self,
data_mode: DataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &[u8],
) -> Result<(), Error> {
if buffer.len() > self.tx_buf.capacity() {
return Err(Error::from(DmaError::Overflow));
}
self.wait_for_idle();
self.tx_buf.fill(buffer);
unsafe {
self.spi_dma.start_half_duplex_write(
data_mode,
cmd,
address,
dummy,
buffer.len(),
&mut self.tx_buf,
)?;
}
self.wait_for_idle();
Ok(())
}
}
#[instability::unstable]
impl<Dm> embassy_embedded_hal::SetConfig for SpiDmaBus<'_, Dm>
where
Dm: DriverMode,
{
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
/// Async functionality
mod asynch {
#[cfg(any(doc, feature = "unstable"))]
use core::cmp::min;
use core::ops::{Deref, DerefMut};
use super::*;
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
struct DropGuard<I, F: FnOnce(I)> {
inner: ManuallyDrop<I>,
on_drop: ManuallyDrop<F>,
}
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
impl<I, F: FnOnce(I)> DropGuard<I, F> {
fn new(inner: I, on_drop: F) -> Self {
Self {
inner: ManuallyDrop::new(inner),
on_drop: ManuallyDrop::new(on_drop),
}
}
fn defuse(self) {}
}
impl<I, F: FnOnce(I)> Drop for DropGuard<I, F> {
fn drop(&mut self) {
let inner = unsafe { ManuallyDrop::take(&mut self.inner) };
let on_drop = unsafe { ManuallyDrop::take(&mut self.on_drop) };
(on_drop)(inner)
}
}
impl<I, F: FnOnce(I)> Deref for DropGuard<I, F> {
type Target = I;
fn deref(&self) -> &I {
&self.inner
}
}
impl<I, F: FnOnce(I)> DerefMut for DropGuard<I, F> {
fn deref_mut(&mut self) -> &mut I {
&mut self.inner
}
}
impl SpiDmaBus<'_, Async> {
/// Fill the given buffer with data from the bus.
#[instability::unstable]
pub async fn read_async(&mut self, words: &mut [u8]) -> Result<(), Error> {
self.spi_dma.wait_for_idle_async().await;
let chunk_size = self.rx_buf.capacity();
for chunk in words.chunks_mut(chunk_size) {
self.rx_buf.set_length(chunk.len());
let mut spi = DropGuard::new(&mut self.spi_dma, |spi| spi.cancel_transfer());
unsafe {
spi.start_dma_transfer(chunk.len(), 0, &mut self.rx_buf, &mut EmptyBuf)?
};
spi.wait_for_idle_async().await;
let bytes_read = self.rx_buf.read_received_data(chunk);
debug_assert_eq!(bytes_read, chunk.len());
spi.defuse();
}
Ok(())
}
/// Transmit the given buffer to the bus.
#[instability::unstable]
pub async fn write_async(&mut self, words: &[u8]) -> Result<(), Error> {
self.spi_dma.wait_for_idle_async().await;
let mut spi = DropGuard::new(&mut self.spi_dma, |spi| spi.cancel_transfer());
let chunk_size = self.tx_buf.capacity();
for chunk in words.chunks(chunk_size) {
self.tx_buf.fill(chunk);
unsafe {
spi.start_dma_transfer(0, chunk.len(), &mut EmptyBuf, &mut self.tx_buf)?
};
spi.wait_for_idle_async().await;
}
spi.defuse();
Ok(())
}
/// Transfer by writing out a buffer and reading the response from
/// the bus into another buffer.
#[instability::unstable]
pub async fn transfer_async(
&mut self,
read: &mut [u8],
write: &[u8],
) -> Result<(), Error> {
self.spi_dma.wait_for_idle_async().await;
let mut spi = DropGuard::new(&mut self.spi_dma, |spi| spi.cancel_transfer());
let chunk_size = min(self.tx_buf.capacity(), self.rx_buf.capacity());
let common_length = min(read.len(), write.len());
let (read_common, read_remainder) = read.split_at_mut(common_length);
let (write_common, write_remainder) = write.split_at(common_length);
for (read_chunk, write_chunk) in read_common
.chunks_mut(chunk_size)
.zip(write_common.chunks(chunk_size))
{
self.tx_buf.fill(write_chunk);
self.rx_buf.set_length(read_chunk.len());
unsafe {
spi.start_dma_transfer(
read_chunk.len(),
write_chunk.len(),
&mut self.rx_buf,
&mut self.tx_buf,
)?;
}
spi.wait_for_idle_async().await;
let bytes_read = self.rx_buf.read_received_data(read_chunk);
debug_assert_eq!(bytes_read, read_chunk.len());
}
spi.defuse();
if !read_remainder.is_empty() {
self.read_async(read_remainder).await
} else if !write_remainder.is_empty() {
self.write_async(write_remainder).await
} else {
Ok(())
}
}
/// Transfer by writing out a buffer and reading the response from
/// the bus into the same buffer.
#[instability::unstable]
pub async fn transfer_in_place_async(&mut self, words: &mut [u8]) -> Result<(), Error> {
self.spi_dma.wait_for_idle_async().await;
let mut spi = DropGuard::new(&mut self.spi_dma, |spi| spi.cancel_transfer());
for chunk in words.chunks_mut(self.tx_buf.capacity()) {
self.tx_buf.fill(chunk);
self.rx_buf.set_length(chunk.len());
unsafe {
spi.start_dma_transfer(
chunk.len(),
chunk.len(),
&mut self.rx_buf,
&mut self.tx_buf,
)?;
}
spi.wait_for_idle_async().await;
let bytes_read = self.rx_buf.read_received_data(chunk);
debug_assert_eq!(bytes_read, chunk.len());
}
spi.defuse();
Ok(())
}
}
#[instability::unstable]
impl embedded_hal_async::spi::SpiBus for SpiDmaBus<'_, Async> {
async fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.read_async(words).await
}
async fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
self.write_async(words).await
}
async fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
self.transfer_async(read, write).await
}
async fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.transfer_in_place_async(words).await
}
async fn flush(&mut self) -> Result<(), Self::Error> {
// All operations currently flush so this is no-op.
Ok(())
}
}
}
mod ehal1 {
#[cfg(any(doc, feature = "unstable"))]
use embedded_hal::spi::{ErrorType, SpiBus};
#[cfg(any(doc, feature = "unstable"))]
use super::*;
#[instability::unstable]
impl<Dm> ErrorType for SpiDmaBus<'_, Dm>
where
Dm: DriverMode,
{
type Error = Error;
}
#[instability::unstable]
impl<Dm> SpiBus for SpiDmaBus<'_, Dm>
where
Dm: DriverMode,
{
fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.read(words)
}
fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
self.write(words)
}
fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
self.transfer(read, write)
}
fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.transfer_in_place(words)
}
fn flush(&mut self) -> Result<(), Self::Error> {
// All operations currently flush so this is no-op.
Ok(())
}
}
}
}
mod ehal1 {
use embedded_hal::spi::SpiBus;
use embedded_hal_async::spi::SpiBus as SpiBusAsync;
use super::*;
impl<Dm> embedded_hal::spi::ErrorType for Spi<'_, Dm>
where
Dm: DriverMode,
{
type Error = Error;
}
impl<Dm> SpiBus for Spi<'_, Dm>
where
Dm: DriverMode,
{
fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.driver().read(words)
}
fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
self.driver().write(words)
}
fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
// Optimizations
if read.is_empty() {
return SpiBus::write(self, write);
} else if write.is_empty() {
return SpiBus::read(self, read);
}
let mut write_from = 0;
let mut read_from = 0;
loop {
// How many bytes we write in this chunk
let write_inc = core::cmp::min(FIFO_SIZE, write.len() - write_from);
let write_to = write_from + write_inc;
// How many bytes we read in this chunk
let read_inc = core::cmp::min(FIFO_SIZE, read.len() - read_from);
let read_to = read_from + read_inc;
if (write_inc == 0) && (read_inc == 0) {
break;
}
// No need to flush here, `SpiBus::write` will do it for us
if write_to < read_to {
// Read more than we write, must pad writing part with zeros
let mut empty = [EMPTY_WRITE_PAD; FIFO_SIZE];
empty[0..write_inc].copy_from_slice(&write[write_from..write_to]);
SpiBus::write(self, &empty)?;
} else {
SpiBus::write(self, &write[write_from..write_to])?;
}
if read_inc > 0 {
SpiBus::flush(self)?;
self.driver()
.read_from_fifo(&mut read[read_from..read_to])?;
}
write_from = write_to;
read_from = read_to;
}
Ok(())
}
fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.driver().transfer(words).map(|_| ())
}
fn flush(&mut self) -> Result<(), Self::Error> {
self.driver().flush()
}
}
impl SpiBusAsync for Spi<'_, Async> {
async fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
// We need to flush because the blocking transfer functions may return while a
// transfer is still in progress.
self.flush_async().await?;
self.driver().read_async(words).await
}
async fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
// We need to flush because the blocking transfer functions may return while a
// transfer is still in progress.
self.flush_async().await?;
self.driver().write_async(words).await
}
async fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
// Optimizations
if read.is_empty() {
return SpiBusAsync::write(self, write).await;
} else if write.is_empty() {
return SpiBusAsync::read(self, read).await;
}
let mut write_from = 0;
let mut read_from = 0;
loop {
// How many bytes we write in this chunk
let write_inc = core::cmp::min(FIFO_SIZE, write.len() - write_from);
let write_to = write_from + write_inc;
// How many bytes we read in this chunk
let read_inc = core::cmp::min(FIFO_SIZE, read.len() - read_from);
let read_to = read_from + read_inc;
if (write_inc == 0) && (read_inc == 0) {
break;
}
// No need to flush here, `SpiBusAsync::write` will do it for us
if write_to < read_to {
// Read more than we write, must pad writing part with zeros
let mut empty = [EMPTY_WRITE_PAD; FIFO_SIZE];
empty[0..write_inc].copy_from_slice(&write[write_from..write_to]);
SpiBusAsync::write(self, &empty).await?;
} else {
SpiBusAsync::write(self, &write[write_from..write_to]).await?;
}
if read_inc > 0 {
self.driver()
.read_from_fifo(&mut read[read_from..read_to])?;
}
write_from = write_to;
read_from = read_to;
}
Ok(())
}
async fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
self.transfer_in_place_async(words).await
}
async fn flush(&mut self) -> Result<(), Self::Error> {
self.flush_async().await
}
}
}
/// SPI peripheral instance.
#[doc(hidden)]
pub trait PeripheralInstance: private::Sealed + Into<AnySpi> + DmaEligible + 'static {
/// Returns the peripheral data describing this SPI instance.
fn info(&self) -> &'static Info;
}
/// Marker trait for QSPI-capable SPI peripherals.
#[doc(hidden)]
pub trait QspiInstance: PeripheralInstance {}
/// Peripheral data describing a particular SPI instance.
#[doc(hidden)]
#[non_exhaustive]
pub struct Info {
/// Pointer to the register block for this SPI instance.
///
/// Use [Self::register_block] to access the register block.
pub register_block: *const RegisterBlock,
/// The system peripheral marker.
pub peripheral: crate::system::Peripheral,
/// Interrupt for this SPI instance.
pub interrupt: crate::peripherals::Interrupt,
/// SCLK signal.
pub sclk: OutputSignal,
/// MOSI signal.
pub mosi: OutputSignal,
/// MISO signal.
pub miso: InputSignal,
/// Chip select signal.
pub cs: OutputSignal,
/// SIO0 (MOSI) input signal for half-duplex mode.
pub sio0_input: InputSignal,
/// SIO1 (MISO) output signal for half-duplex mode.
pub sio1_output: OutputSignal,
/// SIO2 output signal for QSPI mode.
pub sio2_output: Option<OutputSignal>,
/// SIO2 input signal for QSPI mode.
pub sio2_input: Option<InputSignal>,
/// SIO3 output signal for QSPI mode.
pub sio3_output: Option<OutputSignal>,
/// SIO3 input signal for QSPI mode.
pub sio3_input: Option<InputSignal>,
}
struct DmaDriver {
driver: Driver,
dma_peripheral: crate::dma::DmaPeripheral,
}
impl DmaDriver {
fn abort_transfer(&self) {
self.driver.configure_datalen(1, 1);
self.driver.update();
}
fn regs(&self) -> &RegisterBlock {
self.driver.regs()
}
#[allow(clippy::too_many_arguments)]
#[cfg_attr(place_spi_driver_in_ram, ram)]
unsafe fn start_transfer_dma<RX: Rx, TX: Tx>(
&self,
_full_duplex: bool,
rx_len: usize,
tx_len: usize,
rx_buffer: &mut impl DmaRxBuffer,
tx_buffer: &mut impl DmaTxBuffer,
rx: &mut RX,
tx: &mut TX,
) -> Result<(), Error> {
#[cfg(esp32s2)]
{
// without this a transfer after a write will fail
self.regs().dma_out_link().write(|w| w.bits(0));
self.regs().dma_in_link().write(|w| w.bits(0));
}
self.driver.configure_datalen(rx_len, tx_len);
// enable the MISO and MOSI if needed
self.regs()
.user()
.modify(|_, w| w.usr_miso().bit(rx_len > 0).usr_mosi().bit(tx_len > 0));
self.enable_dma();
if rx_len > 0 {
rx.prepare_transfer(self.dma_peripheral, rx_buffer)
.and_then(|_| rx.start_transfer())?;
} else {
#[cfg(esp32)]
{
// see https://github.com/espressif/esp-idf/commit/366e4397e9dae9d93fe69ea9d389b5743295886f
// see https://github.com/espressif/esp-idf/commit/0c3653b1fd7151001143451d4aa95dbf15ee8506
if _full_duplex {
self.regs()
.dma_in_link()
.modify(|_, w| unsafe { w.inlink_addr().bits(0) });
self.regs()
.dma_in_link()
.modify(|_, w| w.inlink_start().set_bit());
}
}
}
if tx_len > 0 {
tx.prepare_transfer(self.dma_peripheral, tx_buffer)
.and_then(|_| tx.start_transfer())?;
}
#[cfg(gdma)]
self.reset_dma();
self.driver.start_operation();
Ok(())
}
fn enable_dma(&self) {
#[cfg(gdma)]
// for non GDMA this is done in `assign_tx_device` / `assign_rx_device`
self.regs().dma_conf().modify(|_, w| {
w.dma_tx_ena().set_bit();
w.dma_rx_ena().set_bit()
});
#[cfg(pdma)]
self.reset_dma();
}
fn reset_dma(&self) {
fn set_reset_bit(reg_block: &RegisterBlock, bit: bool) {
#[cfg(pdma)]
reg_block.dma_conf().modify(|_, w| {
w.out_rst().bit(bit);
w.in_rst().bit(bit);
w.ahbm_fifo_rst().bit(bit);
w.ahbm_rst().bit(bit)
});
#[cfg(gdma)]
reg_block.dma_conf().modify(|_, w| {
w.rx_afifo_rst().bit(bit);
w.buf_afifo_rst().bit(bit);
w.dma_afifo_rst().bit(bit)
});
}
set_reset_bit(self.regs(), true);
set_reset_bit(self.regs(), false);
self.clear_dma_interrupts();
}
#[cfg(gdma)]
fn clear_dma_interrupts(&self) {
self.regs().dma_int_clr().write(|w| {
w.dma_infifo_full_err().clear_bit_by_one();
w.dma_outfifo_empty_err().clear_bit_by_one();
w.trans_done().clear_bit_by_one();
w.mst_rx_afifo_wfull_err().clear_bit_by_one();
w.mst_tx_afifo_rempty_err().clear_bit_by_one()
});
}
#[cfg(pdma)]
fn clear_dma_interrupts(&self) {
self.regs().dma_int_clr().write(|w| {
w.inlink_dscr_empty().clear_bit_by_one();
w.outlink_dscr_error().clear_bit_by_one();
w.inlink_dscr_error().clear_bit_by_one();
w.in_done().clear_bit_by_one();
w.in_err_eof().clear_bit_by_one();
w.in_suc_eof().clear_bit_by_one();
w.out_done().clear_bit_by_one();
w.out_eof().clear_bit_by_one();
w.out_total_eof().clear_bit_by_one()
});
}
}
struct Driver {
info: &'static Info,
state: &'static State,
}
// private implementation bits
// FIXME: split this up into peripheral versions
impl Driver {
/// Returns the register block for this SPI instance.
pub fn regs(&self) -> &RegisterBlock {
unsafe { &*self.info.register_block }
}
/// Initialize for full-duplex 1 bit mode
fn init(&self) {
self.regs().user().modify(|_, w| {
w.usr_miso_highpart().clear_bit();
w.usr_mosi_highpart().clear_bit();
w.doutdin().set_bit();
w.usr_miso().set_bit();
w.usr_mosi().set_bit();
w.cs_hold().set_bit();
w.usr_dummy_idle().set_bit();
w.usr_addr().clear_bit();
w.usr_command().clear_bit()
});
#[cfg(gdma)]
self.regs().clk_gate().modify(|_, w| {
w.clk_en().set_bit();
w.mst_clk_active().set_bit();
w.mst_clk_sel().set_bit()
});
#[cfg(any(esp32c6, esp32h2))]
unsafe {
// use default clock source PLL_F80M_CLK (ESP32-C6) and
// PLL_F48M_CLK (ESP32-H2)
crate::peripherals::PCR::regs()
.spi2_clkm_conf()
.modify(|_, w| w.spi2_clkm_sel().bits(1));
}
#[cfg(gdma)]
self.regs().ctrl().modify(|_, w| {
w.q_pol().clear_bit();
w.d_pol().clear_bit();
w.hold_pol().clear_bit()
});
#[cfg(esp32s2)]
self.regs().ctrl().modify(|_, w| {
w.q_pol().clear_bit();
w.d_pol().clear_bit();
w.wp().clear_bit()
});
#[cfg(esp32)]
self.regs().ctrl().modify(|_, w| w.wp().clear_bit());
#[cfg(not(esp32))]
self.regs().misc().write(|w| unsafe { w.bits(0) });
self.regs().slave().write(|w| unsafe { w.bits(0) });
}
#[cfg(not(esp32))]
fn init_spi_data_mode(
&self,
cmd_mode: DataMode,
address_mode: DataMode,
data_mode: DataMode,
) -> Result<(), Error> {
self.regs().ctrl().modify(|_, w| {
w.fcmd_dual().bit(cmd_mode == DataMode::Dual);
w.fcmd_quad().bit(cmd_mode == DataMode::Quad);
w.faddr_dual().bit(address_mode == DataMode::Dual);
w.faddr_quad().bit(address_mode == DataMode::Quad);
w.fread_dual().bit(data_mode == DataMode::Dual);
w.fread_quad().bit(data_mode == DataMode::Quad)
});
self.regs().user().modify(|_, w| {
w.fwrite_dual().bit(data_mode == DataMode::Dual);
w.fwrite_quad().bit(data_mode == DataMode::Quad)
});
Ok(())
}
#[cfg(esp32)]
fn init_spi_data_mode(
&self,
cmd_mode: DataMode,
address_mode: DataMode,
data_mode: DataMode,
) -> Result<(), Error> {
match cmd_mode {
DataMode::Single => (),
DataMode::SingleTwoDataLines => (),
// FIXME: more detailed error - Only 1-bit commands are supported.
_ => return Err(Error::Unsupported),
}
match address_mode {
DataMode::Single | DataMode::SingleTwoDataLines => {
self.regs().ctrl().modify(|_, w| {
w.fread_dio().clear_bit();
w.fread_qio().clear_bit();
w.fread_dual().bit(data_mode == DataMode::Dual);
w.fread_quad().bit(data_mode == DataMode::Quad)
});
self.regs().user().modify(|_, w| {
w.fwrite_dio().clear_bit();
w.fwrite_qio().clear_bit();
w.fwrite_dual().bit(data_mode == DataMode::Dual);
w.fwrite_quad().bit(data_mode == DataMode::Quad)
});
}
address_mode if address_mode == data_mode => {
self.regs().ctrl().modify(|_, w| {
w.fastrd_mode().set_bit();
w.fread_dio().bit(address_mode == DataMode::Dual);
w.fread_qio().bit(address_mode == DataMode::Quad);
w.fread_dual().clear_bit();
w.fread_quad().clear_bit()
});
self.regs().user().modify(|_, w| {
w.fwrite_dio().bit(address_mode == DataMode::Dual);
w.fwrite_qio().bit(address_mode == DataMode::Quad);
w.fwrite_dual().clear_bit();
w.fwrite_quad().clear_bit()
});
}
// FIXME: more detailed error - Unsupported combination of data-modes,
_ => return Err(Error::Unsupported),
}
Ok(())
}
/// Enable or disable listening for the given interrupts.
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
fn enable_listen(&self, interrupts: EnumSet<SpiInterrupt>, enable: bool) {
cfg_if::cfg_if! {
if #[cfg(esp32)] {
self.regs().slave().modify(|_, w| {
for interrupt in interrupts {
match interrupt {
SpiInterrupt::TransferDone => w.trans_inten().bit(enable),
};
}
w
});
} else if #[cfg(esp32s2)] {
self.regs().slave().modify(|_, w| {
for interrupt in interrupts {
match interrupt {
SpiInterrupt::TransferDone => w.int_trans_done_en().bit(enable),
SpiInterrupt::DmaSegmentedTransferDone => w.int_dma_seg_trans_en().bit(enable),
};
}
w
});
} else {
self.regs().dma_int_ena().modify(|_, w| {
for interrupt in interrupts {
match interrupt {
SpiInterrupt::TransferDone => w.trans_done().bit(enable),
SpiInterrupt::DmaSegmentedTransferDone => w.dma_seg_trans_done().bit(enable),
SpiInterrupt::App2 => w.app2().bit(enable),
SpiInterrupt::App1 => w.app1().bit(enable),
};
}
w
});
}
}
}
/// Gets asserted interrupts
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
fn interrupts(&self) -> EnumSet<SpiInterrupt> {
let mut res = EnumSet::new();
cfg_if::cfg_if! {
if #[cfg(esp32)] {
if self.regs().slave().read().trans_done().bit() {
res.insert(SpiInterrupt::TransferDone);
}
} else if #[cfg(esp32s2)] {
if self.regs().slave().read().trans_done().bit() {
res.insert(SpiInterrupt::TransferDone);
}
if self.regs().hold().read().dma_seg_trans_done().bit() {
res.insert(SpiInterrupt::DmaSegmentedTransferDone);
}
} else {
let ints = self.regs().dma_int_raw().read();
if ints.trans_done().bit() {
res.insert(SpiInterrupt::TransferDone);
}
if ints.dma_seg_trans_done().bit() {
res.insert(SpiInterrupt::DmaSegmentedTransferDone);
}
if ints.app2().bit() {
res.insert(SpiInterrupt::App2);
}
if ints.app1().bit() {
res.insert(SpiInterrupt::App1);
}
}
}
res
}
/// Resets asserted interrupts
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
fn clear_interrupts(&self, interrupts: EnumSet<SpiInterrupt>) {
cfg_if::cfg_if! {
if #[cfg(esp32)] {
for interrupt in interrupts {
match interrupt {
SpiInterrupt::TransferDone => {
self.regs().slave().modify(|_, w| w.trans_done().clear_bit());
}
}
}
} else if #[cfg(esp32s2)] {
for interrupt in interrupts {
match interrupt {
SpiInterrupt::TransferDone => {
self.regs().slave().modify(|_, w| w.trans_done().clear_bit());
}
SpiInterrupt::DmaSegmentedTransferDone => {
self.regs()
.hold()
.modify(|_, w| w.dma_seg_trans_done().clear_bit());
}
}
}
} else {
self.regs().dma_int_clr().write(|w| {
for interrupt in interrupts {
match interrupt {
SpiInterrupt::TransferDone => w.trans_done().clear_bit_by_one(),
SpiInterrupt::DmaSegmentedTransferDone => w.dma_seg_trans_done().clear_bit_by_one(),
SpiInterrupt::App2 => w.app2().clear_bit_by_one(),
SpiInterrupt::App1 => w.app1().clear_bit_by_one(),
};
}
w
});
}
}
}
fn apply_config(&self, config: &Config) -> Result<(), ConfigError> {
config.validate()?;
self.ch_bus_freq(config)?;
self.set_bit_order(config.read_bit_order, config.write_bit_order);
self.set_data_mode(config.mode);
Ok(())
}
fn set_data_mode(&self, data_mode: Mode) {
cfg_if::cfg_if! {
if #[cfg(esp32)] {
let pin_reg = self.regs().pin();
} else {
let pin_reg = self.regs().misc();
}
};
pin_reg.modify(|_, w| {
w.ck_idle_edge()
.bit(matches!(data_mode, Mode::_2 | Mode::_3))
});
self.regs().user().modify(|_, w| {
w.ck_out_edge()
.bit(matches!(data_mode, Mode::_1 | Mode::_2))
});
}
fn ch_bus_freq(&self, bus_clock_config: &Config) -> Result<(), ConfigError> {
fn enable_clocks(_reg_block: &RegisterBlock, _enable: bool) {
#[cfg(gdma)]
_reg_block.clk_gate().modify(|_, w| {
w.clk_en().bit(_enable);
w.mst_clk_active().bit(_enable);
w.mst_clk_sel().bit(true) // TODO: support XTAL clock source
});
}
// Change clock frequency
let raw = bus_clock_config.raw_clock_reg_value()?;
enable_clocks(self.regs(), false);
self.regs().clock().write(|w| unsafe { w.bits(raw) });
enable_clocks(self.regs(), true);
Ok(())
}
#[cfg(not(any(esp32, esp32c3, esp32s2)))]
fn set_bit_order(&self, read_order: BitOrder, write_order: BitOrder) {
let read_value = match read_order {
BitOrder::MsbFirst => 0,
BitOrder::LsbFirst => 1,
};
let write_value = match write_order {
BitOrder::MsbFirst => 0,
BitOrder::LsbFirst => 1,
};
self.regs().ctrl().modify(|_, w| unsafe {
w.rd_bit_order().bits(read_value);
w.wr_bit_order().bits(write_value);
w
});
}
#[cfg(any(esp32, esp32c3, esp32s2))]
fn set_bit_order(&self, read_order: BitOrder, write_order: BitOrder) {
let read_value = match read_order {
BitOrder::MsbFirst => false,
BitOrder::LsbFirst => true,
};
let write_value = match write_order {
BitOrder::MsbFirst => false,
BitOrder::LsbFirst => true,
};
self.regs().ctrl().modify(|_, w| {
w.rd_bit_order().bit(read_value);
w.wr_bit_order().bit(write_value);
w
});
}
#[cfg_attr(place_spi_driver_in_ram, ram)]
fn fill_fifo(&self, chunk: &[u8]) {
// TODO: replace with `array_chunks` and `from_le_bytes`
let mut c_iter = chunk.chunks_exact(4);
let mut w_iter = self.regs().w_iter();
for c in c_iter.by_ref() {
if let Some(w_reg) = w_iter.next() {
let word = (c[0] as u32)
| ((c[1] as u32) << 8)
| ((c[2] as u32) << 16)
| ((c[3] as u32) << 24);
w_reg.write(|w| w.buf().set(word));
}
}
let rem = c_iter.remainder();
if !rem.is_empty() {
if let Some(w_reg) = w_iter.next() {
let word = match rem.len() {
3 => (rem[0] as u32) | ((rem[1] as u32) << 8) | ((rem[2] as u32) << 16),
2 => (rem[0] as u32) | ((rem[1] as u32) << 8),
1 => rem[0] as u32,
_ => unreachable!(),
};
w_reg.write(|w| w.buf().set(word));
}
}
}
/// Write bytes to SPI.
///
/// This function will return before all bytes of the last chunk to transmit
/// have been sent to the wire. If you must ensure that the whole
/// messages was written correctly, use [`Self::flush`].
#[cfg_attr(place_spi_driver_in_ram, ram)]
fn write(&self, words: &[u8]) -> Result<(), Error> {
let num_chunks = words.len() / FIFO_SIZE;
// Flush in case previous writes have not completed yet, required as per
// embedded-hal documentation (#1369).
self.flush()?;
// The fifo has a limited fixed size, so the data must be chunked and then
// transmitted
for (i, chunk) in words.chunks(FIFO_SIZE).enumerate() {
self.configure_datalen(0, chunk.len());
self.fill_fifo(chunk);
self.start_operation();
// Wait for all chunks to complete except the last one.
// The function is allowed to return before the bus is idle.
// see [embedded-hal flushing](https://docs.rs/embedded-hal/1.0.0/embedded_hal/spi/index.html#flushing)
if i < num_chunks {
self.flush()?;
}
}
Ok(())
}
/// Write bytes to SPI.
#[cfg_attr(place_spi_driver_in_ram, ram)]
async fn write_async(&self, words: &[u8]) -> Result<(), Error> {
// The fifo has a limited fixed size, so the data must be chunked and then
// transmitted
for chunk in words.chunks(FIFO_SIZE) {
self.configure_datalen(0, chunk.len());
self.fill_fifo(chunk);
self.execute_operation_async().await;
}
Ok(())
}
/// Read bytes from SPI.
///
/// Sends out a stuffing byte for every byte to read. This function doesn't
/// perform flushing. If you want to read the response to something you
/// have written before, consider using [`Self::transfer`] instead.
#[cfg_attr(place_spi_driver_in_ram, ram)]
fn read(&self, words: &mut [u8]) -> Result<(), Error> {
let empty_array = [EMPTY_WRITE_PAD; FIFO_SIZE];
for chunk in words.chunks_mut(FIFO_SIZE) {
self.write(&empty_array[0..chunk.len()])?;
self.flush()?;
self.read_from_fifo(chunk)?;
}
Ok(())
}
/// Read bytes from SPI.
///
/// Sends out a stuffing byte for every byte to read. This function doesn't
/// perform flushing. If you want to read the response to something you
/// have written before, consider using [`Self::transfer`] instead.
#[cfg_attr(place_spi_driver_in_ram, ram)]
async fn read_async(&self, words: &mut [u8]) -> Result<(), Error> {
let empty_array = [EMPTY_WRITE_PAD; FIFO_SIZE];
for chunk in words.chunks_mut(FIFO_SIZE) {
self.write_async(&empty_array[0..chunk.len()]).await?;
self.read_from_fifo(chunk)?;
}
Ok(())
}
/// Read received bytes from SPI FIFO.
///
/// Copies the contents of the SPI receive FIFO into `words`. This function
/// doesn't perform flushing. If you want to read the response to
/// something you have written before, consider using [`Self::transfer`]
/// instead.
#[cfg_attr(place_spi_driver_in_ram, ram)]
fn read_from_fifo(&self, words: &mut [u8]) -> Result<(), Error> {
let reg_block = self.regs();
for chunk in words.chunks_mut(FIFO_SIZE) {
self.configure_datalen(chunk.len(), 0);
for (index, w_reg) in (0..chunk.len()).step_by(4).zip(reg_block.w_iter()) {
let reg_val = w_reg.read().bits();
let bytes = reg_val.to_le_bytes();
let len = usize::min(chunk.len(), index + 4) - index;
chunk[index..(index + len)].clone_from_slice(&bytes[0..len]);
}
}
Ok(())
}
fn busy(&self) -> bool {
let reg_block = self.regs();
reg_block.cmd().read().usr().bit_is_set()
}
// Check if the bus is busy and if it is wait for it to be idle
fn flush(&self) -> Result<(), Error> {
while self.busy() {
// wait for bus to be clear
}
Ok(())
}
#[cfg_attr(place_spi_driver_in_ram, ram)]
fn transfer<'w>(&self, words: &'w mut [u8]) -> Result<&'w [u8], Error> {
for chunk in words.chunks_mut(FIFO_SIZE) {
self.write(chunk)?;
self.flush()?;
self.read_from_fifo(chunk)?;
}
Ok(words)
}
#[cfg_attr(place_spi_driver_in_ram, ram)]
async fn transfer_in_place_async(&self, words: &mut [u8]) -> Result<(), Error> {
for chunk in words.chunks_mut(FIFO_SIZE) {
self.write_async(chunk).await?;
self.read_from_fifo(chunk)?;
}
Ok(())
}
fn start_operation(&self) {
self.update();
self.regs().cmd().modify(|_, w| w.usr().set_bit());
}
/// Starts the operation and waits for it to complete.
async fn execute_operation_async(&self) {
// On ESP32, the interrupt seems to not fire in specific circumstances, when
// `listen` is called after `start_operation`. Let's call it before, to be sure.
let future = SpiFuture::setup(self).await;
self.start_operation();
future.await;
}
#[allow(clippy::too_many_arguments)]
fn setup_half_duplex(
&self,
is_write: bool,
cmd: Command,
address: Address,
dummy_idle: bool,
dummy: u8,
no_mosi_miso: bool,
data_mode: DataMode,
) -> Result<(), Error> {
let three_wire = cmd.mode() == DataMode::Single
|| address.mode() == DataMode::Single
|| data_mode == DataMode::Single;
if three_wire
&& ((cmd != Command::None && cmd.mode() != DataMode::Single)
|| (address != Address::None && address.mode() != DataMode::Single)
|| data_mode != DataMode::Single)
{
return Err(Error::Unsupported);
}
self.init_spi_data_mode(cmd.mode(), address.mode(), data_mode)?;
let reg_block = self.regs();
reg_block.user().modify(|_, w| {
w.usr_miso_highpart().clear_bit();
w.usr_mosi_highpart().clear_bit();
w.sio().bit(three_wire);
w.doutdin().clear_bit();
w.usr_miso().bit(!is_write && !no_mosi_miso);
w.usr_mosi().bit(is_write && !no_mosi_miso);
w.cs_hold().set_bit();
w.usr_dummy_idle().bit(dummy_idle);
w.usr_dummy().bit(dummy != 0);
w.usr_addr().bit(!address.is_none());
w.usr_command().bit(!cmd.is_none())
});
#[cfg(gdma)]
reg_block.clk_gate().modify(|_, w| {
w.clk_en().set_bit();
w.mst_clk_active().set_bit();
w.mst_clk_sel().set_bit()
});
#[cfg(any(esp32c6, esp32h2))]
// use default clock source PLL_F80M_CLK
crate::peripherals::PCR::regs()
.spi2_clkm_conf()
.modify(|_, w| unsafe { w.spi2_clkm_sel().bits(1) });
#[cfg(not(esp32))]
reg_block.misc().write(|w| unsafe { w.bits(0) });
reg_block.slave().write(|w| unsafe { w.bits(0) });
self.update();
// set cmd, address, dummy cycles
self.set_up_common_phases(cmd, address, dummy);
Ok(())
}
fn set_up_common_phases(&self, cmd: Command, address: Address, dummy: u8) {
let reg_block = self.regs();
if !cmd.is_none() {
reg_block.user2().modify(|_, w| unsafe {
w.usr_command_bitlen().bits((cmd.width() - 1) as u8);
w.usr_command_value().bits(cmd.value())
});
}
if !address.is_none() {
reg_block
.user1()
.modify(|_, w| unsafe { w.usr_addr_bitlen().bits((address.width() - 1) as u8) });
let addr = address.value() << (32 - address.width());
#[cfg(not(esp32))]
reg_block
.addr()
.write(|w| unsafe { w.usr_addr_value().bits(addr) });
#[cfg(esp32)]
reg_block.addr().write(|w| unsafe { w.bits(addr) });
}
if dummy > 0 {
reg_block
.user1()
.modify(|_, w| unsafe { w.usr_dummy_cyclelen().bits(dummy - 1) });
}
}
fn update(&self) {
cfg_if::cfg_if! {
if #[cfg(gdma)] {
let reg_block = self.regs();
reg_block.cmd().modify(|_, w| w.update().set_bit());
while reg_block.cmd().read().update().bit_is_set() {
// wait
}
} else {
// Doesn't seem to be needed for ESP32 and ESP32-S2
}
}
}
fn configure_datalen(&self, rx_len_bytes: usize, tx_len_bytes: usize) {
let reg_block = self.regs();
let rx_len = rx_len_bytes as u32 * 8;
let tx_len = tx_len_bytes as u32 * 8;
let rx_len = rx_len.saturating_sub(1);
let tx_len = tx_len.saturating_sub(1);
cfg_if::cfg_if! {
if #[cfg(esp32)] {
let len = rx_len.max(tx_len);
reg_block
.mosi_dlen()
.write(|w| unsafe { w.usr_mosi_dbitlen().bits(len) });
reg_block
.miso_dlen()
.write(|w| unsafe { w.usr_miso_dbitlen().bits(len) });
} else if #[cfg(esp32s2)] {
reg_block
.mosi_dlen()
.write(|w| unsafe { w.usr_mosi_dbitlen().bits(tx_len) });
reg_block
.miso_dlen()
.write(|w| unsafe { w.usr_miso_dbitlen().bits(rx_len) });
} else {
reg_block
.ms_dlen()
.write(|w| unsafe { w.ms_data_bitlen().bits(rx_len.max(tx_len)) });
}
}
}
}
impl PartialEq for Info {
fn eq(&self, other: &Self) -> bool {
self.register_block == other.register_block
}
}
unsafe impl Sync for Info {}
// TODO: this macro needs to move to one level up, and it needs to describe the
// hardware fully. The master module should extend it with the master specific
// details.
macro_rules! spi_instance {
($num:literal, $sclk:ident, $mosi:ident, $miso:ident, $cs:ident $(, $sio2:ident, $sio3:ident)?) => {
paste::paste! {
impl PeripheralInstance for crate::peripherals::[<SPI $num>] {
#[inline(always)]
fn info(&self) -> &'static Info {
static INFO: Info = Info {
register_block: crate::peripherals::[<SPI $num>]::regs(),
peripheral: crate::system::Peripheral::[<Spi $num>],
interrupt: crate::peripherals::Interrupt::[<SPI $num>],
sclk: OutputSignal::$sclk,
mosi: OutputSignal::$mosi,
miso: InputSignal::$miso,
cs: OutputSignal::$cs,
sio0_input: InputSignal::$mosi,
sio1_output: OutputSignal::$miso,
sio2_output: $crate::if_set!($(Some(OutputSignal::$sio2))?, None),
sio2_input: $crate::if_set!($(Some(InputSignal::$sio2))?, None),
sio3_output: $crate::if_set!($(Some(OutputSignal::$sio3))?, None),
sio3_input: $crate::if_set!($(Some(InputSignal::$sio3))?, None),
};
&INFO
}
}
$(
// If the extra pins are set, implement QspiInstance
$crate::ignore!($sio2);
impl QspiInstance for crate::peripherals::[<SPI $num>] {}
)?
}
}
}
#[cfg(spi2)]
cfg_if::cfg_if! {
if #[cfg(esp32)] {
spi_instance!(2, HSPICLK, HSPID, HSPIQ, HSPICS0, HSPIWP, HSPIHD);
} else if #[cfg(any(esp32s2, esp32s3))] {
spi_instance!(2, FSPICLK, FSPID, FSPIQ, FSPICS0, FSPIWP, FSPIHD);
} else {
spi_instance!(2, FSPICLK_MUX, FSPID, FSPIQ, FSPICS0, FSPIWP, FSPIHD);
}
}
#[cfg(spi3)]
cfg_if::cfg_if! {
if #[cfg(esp32)] {
spi_instance!(3, VSPICLK, VSPID, VSPIQ, VSPICS0, HSPIWP, HSPIHD);
} else if #[cfg(esp32s3)] {
spi_instance!(3, SPI3_CLK, SPI3_D, SPI3_Q, SPI3_CS0, SPI3_WP, SPI3_HD);
} else {
spi_instance!(3, SPI3_CLK, SPI3_D, SPI3_Q, SPI3_CS0);
}
}
impl PeripheralInstance for super::AnySpi {
delegate::delegate! {
to match &self.0 {
super::AnySpiInner::Spi2(spi) => spi,
#[cfg(spi3)]
super::AnySpiInner::Spi3(spi) => spi,
} {
fn info(&self) -> &'static Info;
}
}
}
impl QspiInstance for super::AnySpi {}
#[doc(hidden)]
pub struct State {
waker: AtomicWaker,
}
#[cfg_attr(place_spi_driver_in_ram, ram)]
fn handle_async<I: Instance>(instance: I) {
let state = instance.state();
let info = instance.info();
let driver = Driver { info, state };
if driver.interrupts().contains(SpiInterrupt::TransferDone) {
state.waker.wake();
driver.enable_listen(SpiInterrupt::TransferDone.into(), false);
}
}
#[doc(hidden)]
pub trait Instance: PeripheralInstance {
fn state(&self) -> &'static State;
fn handler(&self) -> InterruptHandler;
}
macro_rules! master_instance {
($peri:ident) => {
impl Instance for $crate::peripherals::$peri {
fn state(&self) -> &'static State {
static STATE: State = State {
waker: AtomicWaker::new(),
};
&STATE
}
fn handler(&self) -> InterruptHandler {
#[$crate::handler]
#[cfg_attr(place_spi_driver_in_ram, ram)]
fn handle() {
handle_async(unsafe { $crate::peripherals::$peri::steal() })
}
handle
}
}
};
}
master_instance!(SPI2);
#[cfg(spi3)]
master_instance!(SPI3);
impl Instance for super::AnySpi {
delegate::delegate! {
to match &self.0 {
super::AnySpiInner::Spi2(spi) => spi,
#[cfg(spi3)]
super::AnySpiInner::Spi3(spi) => spi,
} {
fn state(&self) -> &'static State;
fn handler(&self) -> InterruptHandler;
}
}
}
struct SpiFuture<'a> {
driver: &'a Driver,
}
impl<'a> SpiFuture<'a> {
fn setup(driver: &'a Driver) -> impl Future<Output = Self> {
// Make sure this is called before starting an async operation. On the ESP32,
// calling after may cause the interrupt to not fire.
core::future::poll_fn(move |cx| {
driver.state.waker.register(cx.waker());
driver.clear_interrupts(SpiInterrupt::TransferDone.into());
driver.enable_listen(SpiInterrupt::TransferDone.into(), true);
Poll::Ready(Self { driver })
})
}
}
use core::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
impl Future for SpiFuture<'_> {
type Output = ();
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
if self
.driver
.interrupts()
.contains(SpiInterrupt::TransferDone)
{
self.driver
.clear_interrupts(SpiInterrupt::TransferDone.into());
return Poll::Ready(());
}
Poll::Pending
}
}
impl Drop for SpiFuture<'_> {
fn drop(&mut self) {
self.driver
.enable_listen(SpiInterrupt::TransferDone.into(), false);
}
}