spi_master_example_main.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /* SPI Master example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <inttypes.h>
  11. #include "freertos/FreeRTOS.h"
  12. #include "freertos/task.h"
  13. #include "esp_system.h"
  14. #include "driver/spi_master.h"
  15. #include "driver/gpio.h"
  16. #include "pretty_effect.h"
  17. /*
  18. This code displays some fancy graphics on the 320x240 LCD on an ESP-WROVER_KIT board.
  19. This example demonstrates the use of both spi_device_transmit as well as
  20. spi_device_queue_trans/spi_device_get_trans_result and pre-transmit callbacks.
  21. Some info about the ILI9341/ST7789V: It has an C/D line, which is connected to a GPIO here. It expects this
  22. line to be low for a command and high for data. We use a pre-transmit callback here to control that
  23. line: every transaction has as the user-definable argument the needed state of the D/C line and just
  24. before the transaction is sent, the callback will set this line to the correct state.
  25. */
  26. #ifdef CONFIG_IDF_TARGET_ESP32
  27. #define LCD_HOST HSPI_HOST
  28. #define PIN_NUM_MISO 25
  29. #define PIN_NUM_MOSI 23
  30. #define PIN_NUM_CLK 19
  31. #define PIN_NUM_CS 22
  32. #define PIN_NUM_DC 21
  33. #define PIN_NUM_RST 18
  34. #define PIN_NUM_BCKL 5
  35. #elif defined CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  36. #define LCD_HOST SPI2_HOST
  37. #define PIN_NUM_MISO 37
  38. #define PIN_NUM_MOSI 35
  39. #define PIN_NUM_CLK 36
  40. #define PIN_NUM_CS 45
  41. #define PIN_NUM_DC 4
  42. #define PIN_NUM_RST 5
  43. #define PIN_NUM_BCKL 6
  44. #elif defined CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C6
  45. #define LCD_HOST SPI2_HOST
  46. #define PIN_NUM_MISO 2
  47. #define PIN_NUM_MOSI 7
  48. #define PIN_NUM_CLK 6
  49. #define PIN_NUM_CS 10
  50. #define PIN_NUM_DC 9
  51. #define PIN_NUM_RST 4
  52. #define PIN_NUM_BCKL 5
  53. #elif defined CONFIG_IDF_TARGET_ESP32H2
  54. #define LCD_HOST SPI2_HOST
  55. #define PIN_NUM_MISO 0
  56. #define PIN_NUM_MOSI 5
  57. #define PIN_NUM_CLK 4
  58. #define PIN_NUM_CS 1
  59. #define PIN_NUM_DC 10
  60. #define PIN_NUM_RST 11
  61. #define PIN_NUM_BCKL 12
  62. #endif
  63. //To speed up transfers, every SPI transfer sends a bunch of lines. This define specifies how many. More means more memory use,
  64. //but less overhead for setting up / finishing transfers. Make sure 240 is dividable by this.
  65. #define PARALLEL_LINES 16
  66. /*
  67. The LCD needs a bunch of command/argument values to be initialized. They are stored in this struct.
  68. */
  69. typedef struct {
  70. uint8_t cmd;
  71. uint8_t data[16];
  72. uint8_t databytes; //No of data in data; bit 7 = delay after set; 0xFF = end of cmds.
  73. } lcd_init_cmd_t;
  74. typedef enum {
  75. LCD_TYPE_ILI = 1,
  76. LCD_TYPE_ST,
  77. LCD_TYPE_MAX,
  78. } type_lcd_t;
  79. //Place data into DRAM. Constant data gets placed into DROM by default, which is not accessible by DMA.
  80. DRAM_ATTR static const lcd_init_cmd_t st_init_cmds[]={
  81. /* Memory Data Access Control, MX=MV=1, MY=ML=MH=0, RGB=0 */
  82. {0x36, {(1<<5)|(1<<6)}, 1},
  83. /* Interface Pixel Format, 16bits/pixel for RGB/MCU interface */
  84. {0x3A, {0x55}, 1},
  85. /* Porch Setting */
  86. {0xB2, {0x0c, 0x0c, 0x00, 0x33, 0x33}, 5},
  87. /* Gate Control, Vgh=13.65V, Vgl=-10.43V */
  88. {0xB7, {0x45}, 1},
  89. /* VCOM Setting, VCOM=1.175V */
  90. {0xBB, {0x2B}, 1},
  91. /* LCM Control, XOR: BGR, MX, MH */
  92. {0xC0, {0x2C}, 1},
  93. /* VDV and VRH Command Enable, enable=1 */
  94. {0xC2, {0x01, 0xff}, 2},
  95. /* VRH Set, Vap=4.4+... */
  96. {0xC3, {0x11}, 1},
  97. /* VDV Set, VDV=0 */
  98. {0xC4, {0x20}, 1},
  99. /* Frame Rate Control, 60Hz, inversion=0 */
  100. {0xC6, {0x0f}, 1},
  101. /* Power Control 1, AVDD=6.8V, AVCL=-4.8V, VDDS=2.3V */
  102. {0xD0, {0xA4, 0xA1}, 1},
  103. /* Positive Voltage Gamma Control */
  104. {0xE0, {0xD0, 0x00, 0x05, 0x0E, 0x15, 0x0D, 0x37, 0x43, 0x47, 0x09, 0x15, 0x12, 0x16, 0x19}, 14},
  105. /* Negative Voltage Gamma Control */
  106. {0xE1, {0xD0, 0x00, 0x05, 0x0D, 0x0C, 0x06, 0x2D, 0x44, 0x40, 0x0E, 0x1C, 0x18, 0x16, 0x19}, 14},
  107. /* Sleep Out */
  108. {0x11, {0}, 0x80},
  109. /* Display On */
  110. {0x29, {0}, 0x80},
  111. {0, {0}, 0xff}
  112. };
  113. DRAM_ATTR static const lcd_init_cmd_t ili_init_cmds[]={
  114. /* Power contorl B, power control = 0, DC_ENA = 1 */
  115. {0xCF, {0x00, 0x83, 0X30}, 3},
  116. /* Power on sequence control,
  117. * cp1 keeps 1 frame, 1st frame enable
  118. * vcl = 0, ddvdh=3, vgh=1, vgl=2
  119. * DDVDH_ENH=1
  120. */
  121. {0xED, {0x64, 0x03, 0X12, 0X81}, 4},
  122. /* Driver timing control A,
  123. * non-overlap=default +1
  124. * EQ=default - 1, CR=default
  125. * pre-charge=default - 1
  126. */
  127. {0xE8, {0x85, 0x01, 0x79}, 3},
  128. /* Power control A, Vcore=1.6V, DDVDH=5.6V */
  129. {0xCB, {0x39, 0x2C, 0x00, 0x34, 0x02}, 5},
  130. /* Pump ratio control, DDVDH=2xVCl */
  131. {0xF7, {0x20}, 1},
  132. /* Driver timing control, all=0 unit */
  133. {0xEA, {0x00, 0x00}, 2},
  134. /* Power control 1, GVDD=4.75V */
  135. {0xC0, {0x26}, 1},
  136. /* Power control 2, DDVDH=VCl*2, VGH=VCl*7, VGL=-VCl*3 */
  137. {0xC1, {0x11}, 1},
  138. /* VCOM control 1, VCOMH=4.025V, VCOML=-0.950V */
  139. {0xC5, {0x35, 0x3E}, 2},
  140. /* VCOM control 2, VCOMH=VMH-2, VCOML=VML-2 */
  141. {0xC7, {0xBE}, 1},
  142. /* Memory access contorl, MX=MY=0, MV=1, ML=0, BGR=1, MH=0 */
  143. {0x36, {0x28}, 1},
  144. /* Pixel format, 16bits/pixel for RGB/MCU interface */
  145. {0x3A, {0x55}, 1},
  146. /* Frame rate control, f=fosc, 70Hz fps */
  147. {0xB1, {0x00, 0x1B}, 2},
  148. /* Enable 3G, disabled */
  149. {0xF2, {0x08}, 1},
  150. /* Gamma set, curve 1 */
  151. {0x26, {0x01}, 1},
  152. /* Positive gamma correction */
  153. {0xE0, {0x1F, 0x1A, 0x18, 0x0A, 0x0F, 0x06, 0x45, 0X87, 0x32, 0x0A, 0x07, 0x02, 0x07, 0x05, 0x00}, 15},
  154. /* Negative gamma correction */
  155. {0XE1, {0x00, 0x25, 0x27, 0x05, 0x10, 0x09, 0x3A, 0x78, 0x4D, 0x05, 0x18, 0x0D, 0x38, 0x3A, 0x1F}, 15},
  156. /* Column address set, SC=0, EC=0xEF */
  157. {0x2A, {0x00, 0x00, 0x00, 0xEF}, 4},
  158. /* Page address set, SP=0, EP=0x013F */
  159. {0x2B, {0x00, 0x00, 0x01, 0x3f}, 4},
  160. /* Memory write */
  161. {0x2C, {0}, 0},
  162. /* Entry mode set, Low vol detect disabled, normal display */
  163. {0xB7, {0x07}, 1},
  164. /* Display function control */
  165. {0xB6, {0x0A, 0x82, 0x27, 0x00}, 4},
  166. /* Sleep out */
  167. {0x11, {0}, 0x80},
  168. /* Display on */
  169. {0x29, {0}, 0x80},
  170. {0, {0}, 0xff},
  171. };
  172. /* Send a command to the LCD. Uses spi_device_polling_transmit, which waits
  173. * until the transfer is complete.
  174. *
  175. * Since command transactions are usually small, they are handled in polling
  176. * mode for higher speed. The overhead of interrupt transactions is more than
  177. * just waiting for the transaction to complete.
  178. */
  179. void lcd_cmd(spi_device_handle_t spi, const uint8_t cmd, bool keep_cs_active)
  180. {
  181. esp_err_t ret;
  182. spi_transaction_t t;
  183. memset(&t, 0, sizeof(t)); //Zero out the transaction
  184. t.length=8; //Command is 8 bits
  185. t.tx_buffer=&cmd; //The data is the cmd itself
  186. t.user=(void*)0; //D/C needs to be set to 0
  187. if (keep_cs_active) {
  188. t.flags = SPI_TRANS_CS_KEEP_ACTIVE; //Keep CS active after data transfer
  189. }
  190. ret=spi_device_polling_transmit(spi, &t); //Transmit!
  191. assert(ret==ESP_OK); //Should have had no issues.
  192. }
  193. /* Send data to the LCD. Uses spi_device_polling_transmit, which waits until the
  194. * transfer is complete.
  195. *
  196. * Since data transactions are usually small, they are handled in polling
  197. * mode for higher speed. The overhead of interrupt transactions is more than
  198. * just waiting for the transaction to complete.
  199. */
  200. void lcd_data(spi_device_handle_t spi, const uint8_t *data, int len)
  201. {
  202. esp_err_t ret;
  203. spi_transaction_t t;
  204. if (len==0) return; //no need to send anything
  205. memset(&t, 0, sizeof(t)); //Zero out the transaction
  206. t.length=len*8; //Len is in bytes, transaction length is in bits.
  207. t.tx_buffer=data; //Data
  208. t.user=(void*)1; //D/C needs to be set to 1
  209. ret=spi_device_polling_transmit(spi, &t); //Transmit!
  210. assert(ret==ESP_OK); //Should have had no issues.
  211. }
  212. //This function is called (in irq context!) just before a transmission starts. It will
  213. //set the D/C line to the value indicated in the user field.
  214. void lcd_spi_pre_transfer_callback(spi_transaction_t *t)
  215. {
  216. int dc=(int)t->user;
  217. gpio_set_level(PIN_NUM_DC, dc);
  218. }
  219. uint32_t lcd_get_id(spi_device_handle_t spi)
  220. {
  221. // When using SPI_TRANS_CS_KEEP_ACTIVE, bus must be locked/acquired
  222. spi_device_acquire_bus(spi, portMAX_DELAY);
  223. //get_id cmd
  224. lcd_cmd(spi, 0x04, true);
  225. spi_transaction_t t;
  226. memset(&t, 0, sizeof(t));
  227. t.length=8*3;
  228. t.flags = SPI_TRANS_USE_RXDATA;
  229. t.user = (void*)1;
  230. esp_err_t ret = spi_device_polling_transmit(spi, &t);
  231. assert( ret == ESP_OK );
  232. // Release bus
  233. spi_device_release_bus(spi);
  234. return *(uint32_t*)t.rx_data;
  235. }
  236. //Initialize the display
  237. void lcd_init(spi_device_handle_t spi)
  238. {
  239. int cmd=0;
  240. const lcd_init_cmd_t* lcd_init_cmds;
  241. //Initialize non-SPI GPIOs
  242. gpio_config_t io_conf = {};
  243. io_conf.pin_bit_mask = ((1ULL<<PIN_NUM_DC) | (1ULL<<PIN_NUM_RST) | (1ULL<<PIN_NUM_BCKL));
  244. io_conf.mode = GPIO_MODE_OUTPUT;
  245. io_conf.pull_up_en = true;
  246. gpio_config(&io_conf);
  247. //Reset the display
  248. gpio_set_level(PIN_NUM_RST, 0);
  249. vTaskDelay(100 / portTICK_PERIOD_MS);
  250. gpio_set_level(PIN_NUM_RST, 1);
  251. vTaskDelay(100 / portTICK_PERIOD_MS);
  252. //detect LCD type
  253. uint32_t lcd_id = lcd_get_id(spi);
  254. int lcd_detected_type = 0;
  255. int lcd_type;
  256. printf("LCD ID: %08"PRIx32"\n", lcd_id);
  257. if ( lcd_id == 0 ) {
  258. //zero, ili
  259. lcd_detected_type = LCD_TYPE_ILI;
  260. printf("ILI9341 detected.\n");
  261. } else {
  262. // none-zero, ST
  263. lcd_detected_type = LCD_TYPE_ST;
  264. printf("ST7789V detected.\n");
  265. }
  266. #ifdef CONFIG_LCD_TYPE_AUTO
  267. lcd_type = lcd_detected_type;
  268. #elif defined( CONFIG_LCD_TYPE_ST7789V )
  269. printf("kconfig: force CONFIG_LCD_TYPE_ST7789V.\n");
  270. lcd_type = LCD_TYPE_ST;
  271. #elif defined( CONFIG_LCD_TYPE_ILI9341 )
  272. printf("kconfig: force CONFIG_LCD_TYPE_ILI9341.\n");
  273. lcd_type = LCD_TYPE_ILI;
  274. #endif
  275. if ( lcd_type == LCD_TYPE_ST ) {
  276. printf("LCD ST7789V initialization.\n");
  277. lcd_init_cmds = st_init_cmds;
  278. } else {
  279. printf("LCD ILI9341 initialization.\n");
  280. lcd_init_cmds = ili_init_cmds;
  281. }
  282. //Send all the commands
  283. while (lcd_init_cmds[cmd].databytes!=0xff) {
  284. lcd_cmd(spi, lcd_init_cmds[cmd].cmd, false);
  285. lcd_data(spi, lcd_init_cmds[cmd].data, lcd_init_cmds[cmd].databytes&0x1F);
  286. if (lcd_init_cmds[cmd].databytes&0x80) {
  287. vTaskDelay(100 / portTICK_PERIOD_MS);
  288. }
  289. cmd++;
  290. }
  291. ///Enable backlight
  292. gpio_set_level(PIN_NUM_BCKL, 0);
  293. }
  294. /* To send a set of lines we have to send a command, 2 data bytes, another command, 2 more data bytes and another command
  295. * before sending the line data itself; a total of 6 transactions. (We can't put all of this in just one transaction
  296. * because the D/C line needs to be toggled in the middle.)
  297. * This routine queues these commands up as interrupt transactions so they get
  298. * sent faster (compared to calling spi_device_transmit several times), and at
  299. * the mean while the lines for next transactions can get calculated.
  300. */
  301. static void send_lines(spi_device_handle_t spi, int ypos, uint16_t *linedata)
  302. {
  303. esp_err_t ret;
  304. int x;
  305. //Transaction descriptors. Declared static so they're not allocated on the stack; we need this memory even when this
  306. //function is finished because the SPI driver needs access to it even while we're already calculating the next line.
  307. static spi_transaction_t trans[6];
  308. //In theory, it's better to initialize trans and data only once and hang on to the initialized
  309. //variables. We allocate them on the stack, so we need to re-init them each call.
  310. for (x=0; x<6; x++) {
  311. memset(&trans[x], 0, sizeof(spi_transaction_t));
  312. if ((x&1)==0) {
  313. //Even transfers are commands
  314. trans[x].length=8;
  315. trans[x].user=(void*)0;
  316. } else {
  317. //Odd transfers are data
  318. trans[x].length=8*4;
  319. trans[x].user=(void*)1;
  320. }
  321. trans[x].flags=SPI_TRANS_USE_TXDATA;
  322. }
  323. trans[0].tx_data[0]=0x2A; //Column Address Set
  324. trans[1].tx_data[0]=0; //Start Col High
  325. trans[1].tx_data[1]=0; //Start Col Low
  326. trans[1].tx_data[2]=(320)>>8; //End Col High
  327. trans[1].tx_data[3]=(320)&0xff; //End Col Low
  328. trans[2].tx_data[0]=0x2B; //Page address set
  329. trans[3].tx_data[0]=ypos>>8; //Start page high
  330. trans[3].tx_data[1]=ypos&0xff; //start page low
  331. trans[3].tx_data[2]=(ypos+PARALLEL_LINES)>>8; //end page high
  332. trans[3].tx_data[3]=(ypos+PARALLEL_LINES)&0xff; //end page low
  333. trans[4].tx_data[0]=0x2C; //memory write
  334. trans[5].tx_buffer=linedata; //finally send the line data
  335. trans[5].length=320*2*8*PARALLEL_LINES; //Data length, in bits
  336. trans[5].flags=0; //undo SPI_TRANS_USE_TXDATA flag
  337. //Queue all transactions.
  338. for (x=0; x<6; x++) {
  339. ret=spi_device_queue_trans(spi, &trans[x], portMAX_DELAY);
  340. assert(ret==ESP_OK);
  341. }
  342. //When we are here, the SPI driver is busy (in the background) getting the transactions sent. That happens
  343. //mostly using DMA, so the CPU doesn't have much to do here. We're not going to wait for the transaction to
  344. //finish because we may as well spend the time calculating the next line. When that is done, we can call
  345. //send_line_finish, which will wait for the transfers to be done and check their status.
  346. }
  347. static void send_line_finish(spi_device_handle_t spi)
  348. {
  349. spi_transaction_t *rtrans;
  350. esp_err_t ret;
  351. //Wait for all 6 transactions to be done and get back the results.
  352. for (int x=0; x<6; x++) {
  353. ret=spi_device_get_trans_result(spi, &rtrans, portMAX_DELAY);
  354. assert(ret==ESP_OK);
  355. //We could inspect rtrans now if we received any info back. The LCD is treated as write-only, though.
  356. }
  357. }
  358. //Simple routine to generate some patterns and send them to the LCD. Don't expect anything too
  359. //impressive. Because the SPI driver handles transactions in the background, we can calculate the next line
  360. //while the previous one is being sent.
  361. static void display_pretty_colors(spi_device_handle_t spi)
  362. {
  363. uint16_t *lines[2];
  364. //Allocate memory for the pixel buffers
  365. for (int i=0; i<2; i++) {
  366. lines[i]=heap_caps_malloc(320*PARALLEL_LINES*sizeof(uint16_t), MALLOC_CAP_DMA);
  367. assert(lines[i]!=NULL);
  368. }
  369. int frame=0;
  370. //Indexes of the line currently being sent to the LCD and the line we're calculating.
  371. int sending_line=-1;
  372. int calc_line=0;
  373. while(1) {
  374. frame++;
  375. for (int y=0; y<240; y+=PARALLEL_LINES) {
  376. //Calculate a line.
  377. pretty_effect_calc_lines(lines[calc_line], y, frame, PARALLEL_LINES);
  378. //Finish up the sending process of the previous line, if any
  379. if (sending_line!=-1) send_line_finish(spi);
  380. //Swap sending_line and calc_line
  381. sending_line=calc_line;
  382. calc_line=(calc_line==1)?0:1;
  383. //Send the line we currently calculated.
  384. send_lines(spi, y, lines[sending_line]);
  385. //The line set is queued up for sending now; the actual sending happens in the
  386. //background. We can go on to calculate the next line set as long as we do not
  387. //touch line[sending_line]; the SPI sending process is still reading from that.
  388. }
  389. }
  390. }
  391. void app_main(void)
  392. {
  393. esp_err_t ret;
  394. spi_device_handle_t spi;
  395. spi_bus_config_t buscfg={
  396. .miso_io_num=PIN_NUM_MISO,
  397. .mosi_io_num=PIN_NUM_MOSI,
  398. .sclk_io_num=PIN_NUM_CLK,
  399. .quadwp_io_num=-1,
  400. .quadhd_io_num=-1,
  401. .max_transfer_sz=PARALLEL_LINES*320*2+8
  402. };
  403. spi_device_interface_config_t devcfg={
  404. #ifdef CONFIG_LCD_OVERCLOCK
  405. .clock_speed_hz=26*1000*1000, //Clock out at 26 MHz
  406. #else
  407. .clock_speed_hz=10*1000*1000, //Clock out at 10 MHz
  408. #endif
  409. .mode=0, //SPI mode 0
  410. .spics_io_num=PIN_NUM_CS, //CS pin
  411. .queue_size=7, //We want to be able to queue 7 transactions at a time
  412. .pre_cb=lcd_spi_pre_transfer_callback, //Specify pre-transfer callback to handle D/C line
  413. };
  414. //Initialize the SPI bus
  415. ret=spi_bus_initialize(LCD_HOST, &buscfg, SPI_DMA_CH_AUTO);
  416. ESP_ERROR_CHECK(ret);
  417. //Attach the LCD to the SPI bus
  418. ret=spi_bus_add_device(LCD_HOST, &devcfg, &spi);
  419. ESP_ERROR_CHECK(ret);
  420. //Initialize the LCD
  421. lcd_init(spi);
  422. //Initialize the effect displayed
  423. ret=pretty_effect_init();
  424. ESP_ERROR_CHECK(ret);
  425. //Go do nice stuff.
  426. display_pretty_colors(spi);
  427. }