728x90

728x90

Saturday, November 22, 2025

STM32 Blue Pill HSPI1 and ST7735 128x160 TFT LCD

I have a 1.8 inches 128x160 TFT display module from Ali-Express years ago. It uses the ST7735 controller. It's very popular with Arduino board. This LCD module is available from many manufacturers with the ST7735 LCD controller or its compatible. However we can use other MCU to interface with this LCD via its 4-wire SPI interface. Most of manufacturers of this LCD module have datasheet and example code for various micro-controllers for instance, lcdwiki.com or buydisplay.com.

STM32 Blue Pill HSPI1 and ST7735 128x160 TFT LCD

 

I found some sample code from those manufacturers that was written in C that can be ported to many MCU with some code modification. However I want to use an STM32 Blue Pill I posses due to their popularity, high speed and their rich of peripheral. 

We can use the MCU hardware SPI or even a software bit-banging to control this LCD module. Using a software bit-banging is easy and it could fit to any other MCU since it use only micro-controller digital I/O pins. However it's very slow speed.

Using the hardware SPI is very straight forward in STM32CubeIDE with its code generator wizard. The STM32F103C8T6 supports up to 16Mbits per second baud rate that's fast enough to send a bulk raw graphic data to the LCD module.

The MCU clock frequency is set to 64MHz sources from its 8MHz HSI and PLL to get its maximum frequency.

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
Clock Configuration

The SPI baud rate is 16MHz transmit only mode or even master transmit.

STM32 Blue Pill HSPI1 and SN74HC595N LED Example
SPI and GPIO Setting

 I use the lcdwiki C LCD and graphic library. It contain some LCD configurations, English and Chinese fonts, and raw image.

  1. /* USER CODE BEGIN Header */
  2. /**
  3. ******************************************************************************
  4. * @file : main.c
  5. * @brief : Main program body
  6. ******************************************************************************
  7. * @attention
  8. *
  9. * <h2><center>&copy; Copyright (c) 2025 STMicroelectronics.
  10. * All rights reserved.</center></h2>
  11. *
  12. * This software component is licensed by ST under BSD 3-Clause license,
  13. * the "License"; You may not use this file except in compliance with the
  14. * License. You may obtain a copy of the License at:
  15. * opensource.org/licenses/BSD-3-Clause
  16. *
  17. ******************************************************************************
  18. */
  19. /* USER CODE END Header */
  20. /* Includes ------------------------------------------------------------------*/
  21. #include "main.h"


  22. /* Private variables ---------------------------------------------------------*/
  23. SPI_HandleTypeDef hspi1;


  24. /* Private function prototypes -----------------------------------------------*/
  25. void SystemClock_Config(void);
  26. static void MX_GPIO_Init(void);
  27. static void MX_SPI1_Init(void);
  28. /* USER CODE BEGIN PFP */

  29. /**
  30. * @brief The application entry point.
  31. * @retval int
  32. */
  33. #include "lcd.h"
  34. #include "test.h"



  35. int main(void)
  36. {

  37. /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  38. HAL_Init();

  39. /* Configure the system clock */
  40. SystemClock_Config();


  41. /* Initialize all configured peripherals */
  42. MX_GPIO_Init();
  43. MX_SPI1_Init();
  44. /* USER CODE BEGIN 2 */

  45. /* USER CODE END 2 */

  46. /* Infinite loop */
  47. /* USER CODE BEGIN WHILE */
  48. HAL_SPI_Init(&hspi1);

  49. HAL_Delay(1000);
  50. LCD_Init();

  51. LCD_Clear(WHITE);

  52. Gui_StrCenter(0,0,BLUE,BLUE,"HELLO WORLD!",16,1);
  53. Gui_StrCenter(0,16,RED,BLUE,"STM32F103C8T6",16,1);
  54. Gui_StrCenter(0,32,BLACK,YELLOW,"STM32CubeIDE",16,0);
  55. Gui_StrCenter(0,48,WHITE,BLUE,"ST7735R TFT LCD",16,0);
  56. Gui_StrCenter(0,64,BLUE,GREEN,"SPI1 Half-Duplex",16,0);
  57. Gui_StrCenter(0,80,BLUE,BLUE,"Sat/22/11/2025",16,1);
  58. Gui_StrCenter(0,96,BLUE,BLUE,"MCU: +3.3VDC",16,1);
  59. Gui_StrCenter(0,112,BLUE,BLUE,"LCD: +5.0VDC",16,1);
  60. Gui_StrCenter(0,128,BLACK,BLUE,"HAL Example",16,1);
  61. uint8_t counter=0,msg[16];
  62. while (1)
  63. {
  64. /* USER CODE END WHILE */
  65. //main_test();
  66. sprintf(msg," Counter: %3d ",counter);
  67. Gui_StrCenter(0,144,YELLOW,RED,msg,16,0);
  68. counter++;
  69. HAL_Delay(100);
  70. /* USER CODE BEGIN 3 */
  71. }
  72. /* USER CODE END 3 */
  73. }

  74. /**
  75. * @brief System Clock Configuration
  76. * @retval None
  77. */
  78. void SystemClock_Config(void)
  79. {
  80. RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  81. RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  82. /** Initializes the RCC Oscillators according to the specified parameters
  83. * in the RCC_OscInitTypeDef structure.
  84. */
  85. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  86. RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  87. RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  88. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  89. RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  90. RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  91. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  92. {
  93. Error_Handler();
  94. }
  95. /** Initializes the CPU, AHB and APB buses clocks
  96. */
  97. RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  98. |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  99. RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  100. RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  101. RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  102. RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  103. if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  104. {
  105. Error_Handler();
  106. }
  107. }

  108. /**
  109. * @brief SPI1 Initialization Function
  110. * @param None
  111. * @retval None
  112. */
  113. static void MX_SPI1_Init(void)
  114. {

  115. /* USER CODE BEGIN SPI1_Init 0 */

  116. /* USER CODE END SPI1_Init 0 */

  117. /* USER CODE BEGIN SPI1_Init 1 */

  118. /* USER CODE END SPI1_Init 1 */
  119. /* SPI1 parameter configuration*/
  120. hspi1.Instance = SPI1;
  121. hspi1.Init.Mode = SPI_MODE_MASTER;
  122. hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  123. hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  124. hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  125. hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  126. hspi1.Init.NSS = SPI_NSS_SOFT;
  127. hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
  128. hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  129. hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  130. hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  131. hspi1.Init.CRCPolynomial = 10;
  132. if (HAL_SPI_Init(&hspi1) != HAL_OK)
  133. {
  134. Error_Handler();
  135. }
  136. /* USER CODE BEGIN SPI1_Init 2 */

  137. /* USER CODE END SPI1_Init 2 */

  138. }

  139. /**
  140. * @brief GPIO Initialization Function
  141. * @param None
  142. * @retval None
  143. */
  144. static void MX_GPIO_Init(void)
  145. {
  146. GPIO_InitTypeDef GPIO_InitStruct = {0};

  147. /* GPIO Ports Clock Enable */
  148. __HAL_RCC_GPIOA_CLK_ENABLE();

  149. /*Configure GPIO pin Output Level */
  150. HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2|GPIO_PIN_3|GPIO_PIN_4, GPIO_PIN_RESET);

  151. /*Configure GPIO pins : PA2 PA3 PA4 */
  152. GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3|GPIO_PIN_4;
  153. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  154. GPIO_InitStruct.Pull = GPIO_NOPULL;
  155. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  156. HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  157. }

  158. /* USER CODE BEGIN 4 */

  159. /* USER CODE END 4 */

  160. /**
  161. * @brief This function is executed in case of error occurrence.
  162. * @retval None
  163. */
  164. void Error_Handler(void)
  165. {
  166. /* USER CODE BEGIN Error_Handler_Debug */
  167. /* User can add his own implementation to report the HAL error return state */
  168. __disable_irq();
  169. while (1)
  170. {
  171. }
  172. /* USER CODE END Error_Handler_Debug */
  173. }

  174. #ifdef USE_FULL_ASSERT
  175. /**
  176. * @brief Reports the name of the source file and the source line number
  177. * where the assert_param error has occurred.
  178. * @param file: pointer to the source file name
  179. * @param line: assert_param error line source number
  180. * @retval None
  181. */
  182. void assert_failed(uint8_t *file, uint32_t line)
  183. {
  184. /* USER CODE BEGIN 6 */
  185. /* User can add his own implementation to report the file name and line number,
  186. ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  187. /* USER CODE END 6 */
  188. }
  189. #endif /* USE_FULL_ASSERT */

  190. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

I commented out some functions such as software bit-banging and touch sensor. 

STM32 Blue Pill HSPI1 and ST7735 128x160 TFT LCD
Proteus Simulation

Simulation this program in Proteus is slower than in physical hardware. 

STM32 Blue Pill HSPI1 and ST7735 128x160 TFT LCD

 

Click here to download its source file. 


 

 

Tuesday, November 18, 2025

STM32 Blue Pill and MCP23S17 16x4 LCD Example

In previous post I use the HSPI1 of the STM32F103C8T6 to interfaces with the MCP23S17 16-bit SPI I/O Expander chip. However this chip can interface with any digital I/O devices for instance a conventional HD44780 LCD or a matrix keypad.

STM32 Blue Pill and MCP23S17 16x4 LCD Example

 

In this example the MCP23S17 control an HD44780 compatible LCM at GPIOA and an 8-bit digital input switch at GPIOB. This 8-bit data reading will display on that character LCD in decimal, hexadecimal and binary format.

First we need to set the MCU parameter as follow.

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
Clock Configuration


STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
SPI Setting

I only use the baud rate of 4Mbits per second due to data missing at the MCU SPI master data reception. However the this master MCU can transmit data up to 16Mbits per second to the MCP23S17 chip without error. 

STM32 Blue Pill and MCP23S17 16x4 LCD Example
Schematic

The NSS (or SPI slave select) pin disabled here because it's activated for every one or two data bytes packet. It is not applicable here that use three data bytes packet, slave address, register address and data to be written (SPI sequential write mode).

The HSPI port can be map into GPIO Port A or GPIO Port B. 

MCP23S17 pin latches data at logic low of its CS pin. So at start up or inactive state the master MCU must set its CS pin to logic high. 

  1. /* USER CODE BEGIN Header */
  2. /**
  3. ******************************************************************************
  4. * @file : main.c
  5. * @brief : Main program body
  6. ******************************************************************************
  7. * @attention
  8. *
  9. * <h2><center>&copy; Copyright (c) 2025 STMicroelectronics.
  10. * All rights reserved.</center></h2>
  11. *
  12. * This software component is licensed by ST under BSD 3-Clause license,
  13. * the "License"; You may not use this file except in compliance with the
  14. * License. You may obtain a copy of the License at:
  15. * opensource.org/licenses/BSD-3-Clause
  16. *
  17. ******************************************************************************
  18. */
  19. /* USER CODE END Header */
  20. /* Includes ------------------------------------------------------------------*/
  21. #include "main.h"
  22. #include <stdio.h>

  23. /* Private includes ----------------------------------------------------------*/
  24. /* USER CODE BEGIN Includes */

  25. /* USER CODE END Includes */

  26. /* Private typedef -----------------------------------------------------------*/
  27. /* USER CODE BEGIN PTD */

  28. /* USER CODE END PTD */

  29. /* Private define ------------------------------------------------------------*/
  30. /* USER CODE BEGIN PD */
  31. /* USER CODE END PD */

  32. /* Private macro -------------------------------------------------------------*/
  33. /* USER CODE BEGIN PM */

  34. /* USER CODE END PM */

  35. /* Private variables ---------------------------------------------------------*/
  36. SPI_HandleTypeDef hspi1;

  37. /* USER CODE BEGIN PV */

  38. /* USER CODE END PV */

  39. /* Private function prototypes -----------------------------------------------*/
  40. void SystemClock_Config(void);
  41. static void MX_GPIO_Init(void);
  42. static void MX_SPI1_Init(void);
  43. /* USER CODE BEGIN PFP */

  44. /*mcp23x17 registers at bank0*/
  45. #define IODIRA_0 0x00
  46. #define IODIRB_0 0x01
  47. #define IPOLA_0 0x02
  48. #define IPOLB_0 0x03
  49. #define GPINTENA 0x04
  50. #define GPINTENB 0x05
  51. #define GPPUA_0 0x0C
  52. #define GPPUB_0 0x0D
  53. #define GPIOA_0 0x12
  54. #define GPIOB_0 0x13
  55. #define OLATA_0 0x14
  56. #define OLATB_0 0x15

  57. void mcp23s17_send(uint8_t address, uint8_t data){
  58. uint8_t temp[3];
  59. temp[0]=0x40;
  60. temp[1]=address;
  61. temp[2]=data;
  62. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,0);
  63. HAL_SPI_Transmit(&hspi1, temp, 3, 1);
  64. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,1);
  65. }

  66. uint8_t mcp23s17_receive(uint8_t addr){

  67. uint8_t temp[2], data=0;
  68. temp[0]=0x41;
  69. temp[1]=addr;

  70. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,0);
  71. HAL_SPI_Transmit(&hspi1, temp, 2, 1);
  72. HAL_SPI_Receive(&hspi1,&data,1,1);
  73. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,1);

  74. return data;
  75. }

  76. uint8_t DPORT;

  77. void delay1(uint16_t dTime){
  78. for(uint16_t i=0;i<dTime;i++);
  79. }

  80. void delay2(uint8_t dTime){
  81. for(uint8_t i=0;i<dTime;i++) delay1(5000);
  82. }

  83. void en(void){
  84. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);
  85. //delay1(10);
  86. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);
  87. //delay1(10);
  88. }

  89. void lcdCmd(uint8_t cmd){
  90. uint8_t temp=0x08;
  91. DPORT=temp|(cmd&0xF0);
  92. mcp23s17_send(OLATA_0,DPORT);
  93. en();
  94. //delay1(10);
  95. temp=0;
  96. DPORT=temp|(cmd&0xF0);
  97. mcp23s17_send(OLATA_0,DPORT);
  98. en();

  99. temp=0x08;
  100. DPORT=temp|(cmd<<4);
  101. mcp23s17_send(OLATA_0,DPORT);
  102. en();
  103. //delay1(10);
  104. temp=0;
  105. DPORT=temp|(cmd<<4);
  106. mcp23s17_send(OLATA_0,DPORT);
  107. en();
  108. }

  109. void lcdDat(uint8_t dat){
  110. uint8_t temp=0x0A;
  111. DPORT=temp|(dat&0xF0);
  112. mcp23s17_send(OLATA_0,DPORT);
  113. en();
  114. //delay1(10);
  115. temp=0x02;
  116. DPORT=temp|(dat&0xF0);
  117. mcp23s17_send(OLATA_0,DPORT);
  118. en();

  119. temp=0x0A;
  120. DPORT=temp|(dat<<4);
  121. mcp23s17_send(OLATA_0,DPORT);
  122. en();
  123. //delay1(10);
  124. temp=0x02;
  125. DPORT=temp|(dat<<4);
  126. mcp23s17_send(OLATA_0,DPORT);
  127. en();
  128. }

  129. void lcdInit(void){
  130. DPORT=0x00;
  131. delay1(2000);
  132. mcp23s17_send(IODIRA_0,0x00);
  133. lcdCmd(0x33);
  134. delay1(100);
  135. lcdCmd(0x32);
  136. delay1(100);
  137. lcdCmd(0x28);
  138. delay1(100);
  139. lcdCmd(0x0F);
  140. delay1(100);
  141. lcdCmd(0x01);
  142. delay2(100);
  143. lcdCmd(0x06);
  144. delay1(100);
  145. }

  146. void lcdStr(uint8_t *str){
  147. while(*str) lcdDat(*str++);
  148. }

  149. void lcdXY(uint8_t x,uint8_t y){
  150. // 20x4 LCD
  151. //uint8_t tbe[]={0x80,0xC0,0x94,0xD4};
  152. // 16x4 LCD
  153. uint8_t tbe[]={0x80,0xC0,0x90,0xD0};
  154. lcdCmd(tbe[y-1]+x-1);
  155. delay1(100);
  156. }

  157. void lcdClear(void){
  158. lcdCmd(0x01);
  159. delay2(100);
  160. }

  161. int main(void)
  162. {
  163. /* USER CODE BEGIN 1 */

  164. /* USER CODE END 1 */

  165. /* MCU Configuration--------------------------------------------------------*/

  166. /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  167. HAL_Init();

  168. /* USER CODE BEGIN Init */

  169. /* USER CODE END Init */

  170. /* Configure the system clock */
  171. SystemClock_Config();

  172. /* USER CODE BEGIN SysInit */

  173. /* USER CODE END SysInit */

  174. /* Initialize all configured peripherals */
  175. MX_GPIO_Init();
  176. MX_SPI1_Init();

  177. HAL_SPI_Init(&hspi1);
  178. /*GPIOB As Inputs With Pull Ups*/
  179. mcp23s17_send(IODIRB_0,0xFF);
  180. mcp23s17_send(GPPUB_0,0xFF);

  181. lcdInit();
  182. lcdClear();
  183. lcdCmd(0x0C);

  184. lcdXY(3,1);
  185. lcdStr("Hello World!");

  186. lcdXY(3,2);
  187. lcdStr("STM32F103C8T6 ");

  188. lcdXY(1,3);
  189. lcdStr("HSPI1 MCP23S17");

  190. lcdXY(1,4);
  191. lcdStr("TC1604A-01R LCD");

  192. HAL_Delay(3000);
  193. lcdClear();

  194. lcdXY(1,1);
  195. lcdStr("STM32CubeIDE");

  196. lcdXY(1,2);
  197. lcdStr("version 1.6.0");

  198. lcdXY(1,3);
  199. lcdStr("HAL Library...");

  200. lcdXY(1,4);
  201. lcdStr("18/11/2025");

  202. HAL_Delay(3000);
  203. lcdClear();

  204. char dec[3],hex[4],bin[8],input=0,input_old=1;
  205. lcdXY(1,1); lcdStr("GPB 8-Bit Input: ");
  206. lcdXY(1,2); lcdStr("Decimal: ");
  207. lcdXY(1,3); lcdStr("Hexadecimal:");
  208. lcdXY(1,4); lcdStr("Binary: ");
  209. while (1)
  210. {
  211. input = mcp23s17_receive(GPIOB_0);
  212. if(input!=input_old){
  213. sprintf(&dec, "%3d",input);
  214. lcdXY(13,2); lcdStr(dec);
  215. sprintf(&hex, "0x%02X",input);
  216. lcdXY(13,3); lcdStr(hex);
  217. for(int8_t i=0;i<8;i++){
  218. if((input&(1<<i))==0) bin[7-i]='0';
  219. else bin[7-i]='1';
  220. }
  221. lcdXY(9,4); lcdStr(bin);
  222. }
  223. input_old=input;
  224. }
  225. /* USER CODE END 3 */
  226. }

  227. /**
  228. * @brief System Clock Configuration
  229. * @retval None
  230. */
  231. void SystemClock_Config(void)
  232. {
  233. RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  234. RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  235. /** Initializes the RCC Oscillators according to the specified parameters
  236. * in the RCC_OscInitTypeDef structure.
  237. */
  238. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  239. RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  240. RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  241. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  242. RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  243. RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  244. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  245. {
  246. Error_Handler();
  247. }
  248. /** Initializes the CPU, AHB and APB buses clocks
  249. */
  250. RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  251. |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  252. RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  253. RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  254. RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  255. RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  256. if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  257. {
  258. Error_Handler();
  259. }
  260. }

  261. /**
  262. * @brief SPI1 Initialization Function
  263. * @param None
  264. * @retval None
  265. */
  266. static void MX_SPI1_Init(void)
  267. {

  268. /* USER CODE BEGIN SPI1_Init 0 */

  269. /* USER CODE END SPI1_Init 0 */

  270. /* USER CODE BEGIN SPI1_Init 1 */

  271. /* USER CODE END SPI1_Init 1 */
  272. /* SPI1 parameter configuration*/
  273. hspi1.Instance = SPI1;
  274. hspi1.Init.Mode = SPI_MODE_MASTER;
  275. hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  276. hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  277. hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  278. hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  279. hspi1.Init.NSS = SPI_NSS_SOFT;
  280. hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
  281. hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  282. hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  283. hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  284. hspi1.Init.CRCPolynomial = 10;
  285. if (HAL_SPI_Init(&hspi1) != HAL_OK)
  286. {
  287. Error_Handler();
  288. }
  289. /* USER CODE BEGIN SPI1_Init 2 */

  290. /* USER CODE END SPI1_Init 2 */

  291. }

  292. /**
  293. * @brief GPIO Initialization Function
  294. * @param None
  295. * @retval None
  296. */
  297. static void MX_GPIO_Init(void)
  298. {
  299. GPIO_InitTypeDef GPIO_InitStruct = {0};

  300. /* GPIO Ports Clock Enable */
  301. __HAL_RCC_GPIOA_CLK_ENABLE();

  302. /*Configure GPIO pin Output Level */
  303. HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);

  304. /*Configure GPIO pin : PA4 */
  305. GPIO_InitStruct.Pin = GPIO_PIN_4;
  306. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  307. GPIO_InitStruct.Pull = GPIO_NOPULL;
  308. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  309. HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  310. }

  311. /* USER CODE BEGIN 4 */

  312. /* USER CODE END 4 */

  313. /**
  314. * @brief This function is executed in case of error occurrence.
  315. * @retval None
  316. */
  317. void Error_Handler(void)
  318. {
  319. /* USER CODE BEGIN Error_Handler_Debug */
  320. /* User can add his own implementation to report the HAL error return state */
  321. __disable_irq();
  322. while (1)
  323. {
  324. }
  325. /* USER CODE END Error_Handler_Debug */
  326. }

  327. #ifdef USE_FULL_ASSERT
  328. /**
  329. * @brief Reports the name of the source file and the source line number
  330. * where the assert_param error has occurred.
  331. * @param file: pointer to the source file name
  332. * @param line: assert_param error line source number
  333. * @retval None
  334. */
  335. void assert_failed(uint8_t *file, uint32_t line)
  336. {
  337. /* USER CODE BEGIN 6 */
  338. /* User can add his own implementation to report the file name and line number,
  339. ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  340. /* USER CODE END 6 */
  341. }
  342. #endif /* USE_FULL_ASSERT */

  343. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

 

The simulation process in Proteus VSM is slow. However I think I can test this program in physical hardware whenever I have this SPI chip. 

 

STM32 Blue Pill and MCP23S17 16x4 LCD Example

STM32 Blue Pill and MCP23S17 16x4 LCD Example

STM32 Blue Pill and MCP23S17 16x4 LCD Example

STM32 Blue Pill and MCP23S17 16x4 LCD Example

STM32 Blue Pill and MCP23S17 16x4 LCD Example

Click here to download its source file. 


 

Monday, November 17, 2025

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example

The MCP23S17 is a 16-bit I/O expander chip that use the Serial Peripheral Interface (SPI). It has two 8-bit general purpose I/O port GPIOA and GPIOB. Its internal registers is similar to the MCP23017 that use the I2C interface. This chip a simple 28-Pin DIP or SMD package suitable for student or electronic hobbyists. For more detail about using this chip please visit this post.

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
Simulation Program

Since it's a general I/O port we can use this this chip to control LEDs, relays, input switches, matrix key pad, LCD etc.

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example

 

In this example I use the HSPI1 communication interface of the STM32F103C8T6 to read the input from from GPIOB and then send to the output port, GPIOA. This chip has internal programmable weak pull up resistors for both ports.

The micro-controller is 64MHz, driven from its internal 8MHz HSI and PLL.

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
Clock Configuration

The SPI mode is set to Full Duplex Master Mode with NSS disabled. Since the NSS pin is activated every 8-bit clock pulse. In this situation the Chip Select (Active Low) pin is only active from Low to High every three 24 clock pulses or three data packets. Its baud rate is set to 4MBits per seconds since it has problem when receiving SPI data. It misses some data bits at higher baud rate. 

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
SPI Setting

 

Once transmission session contain three data bytes,

  1. Address of this chip (0x40 for writing and 0x41  for reading) since the address pins A2:A1 are wired to GND.
  2. Address of its internal register, for example the IODIRA locate at the address 0x00
  3. And data to be written to that registers, for instance writing 0x00 to IODIRA making GPIOA as digital output.

In this section I use the,

  1. HAL_SPI_Transmit
  2. HAL_SPI_Receive 

There are a lot of SPI function in the HAL libraries but I found these two functions very easy to handle. 

  1. /* USER CODE BEGIN Header */
  2. /**
  3. ******************************************************************************
  4. * @file : main.c
  5. * @brief : Main program body
  6. ******************************************************************************
  7. * @attention
  8. *
  9. * <h2><center>&copy; Copyright (c) 2025 STMicroelectronics.
  10. * All rights reserved.</center></h2>
  11. *
  12. * This software component is licensed by ST under BSD 3-Clause license,
  13. * the "License"; You may not use this file except in compliance with the
  14. * License. You may obtain a copy of the License at:
  15. * opensource.org/licenses/BSD-3-Clause
  16. *
  17. ******************************************************************************
  18. */
  19. /* USER CODE END Header */
  20. /* Includes ------------------------------------------------------------------*/
  21. #include "main.h"

  22. /* Private variables ---------------------------------------------------------*/
  23. SPI_HandleTypeDef hspi1;

  24. /* Private function prototypes -----------------------------------------------*/
  25. void SystemClock_Config(void);
  26. static void MX_GPIO_Init(void);
  27. static void MX_SPI1_Init(void);
  28. /* USER CODE BEGIN PFP */

  29. /*mcp23x17 registers at bank0*/
  30. #define IODIRA_0 0x00
  31. #define IODIRB_0 0x01
  32. #define IPOLA_0 0x02
  33. #define IPOLB_0 0x03
  34. #define GPINTENA 0x04
  35. #define GPINTENB 0x05
  36. #define GPPUA_0 0x0C
  37. #define GPPUB_0 0x0D
  38. #define GPIOA_0 0x12
  39. #define GPIOB_0 0x13
  40. #define OLATA_0 0x14
  41. #define OLATB_0 0x15

  42. void mcp23s17_send(uint8_t address, uint8_t data){
  43. uint8_t temp[3];
  44. temp[0]=0x40;
  45. temp[1]=address;
  46. temp[2]=data;
  47. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,0);
  48. HAL_SPI_Transmit(&hspi1, temp, 3, 1);
  49. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,1);
  50. }

  51. uint8_t mcp23s17_receive(uint8_t addr){

  52. uint8_t temp[2], data=0;
  53. temp[0]=0x41;
  54. temp[1]=addr;

  55. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,0);
  56. HAL_SPI_Transmit(&hspi1, temp, 2, 1);
  57. HAL_SPI_Receive(&hspi1,&data,1,1);
  58. HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,1);

  59. return data;
  60. }

  61. int main(void)
  62. {

  63. /* MCU Configuration--------------------------------------------------------*/

  64. /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  65. HAL_Init();

  66. /* Configure the system clock */
  67. SystemClock_Config();

  68. /* Initialize all configured peripherals */
  69. MX_GPIO_Init();
  70. MX_SPI1_Init();

  71. HAL_SPI_Init(&hspi1);

  72. uint8_t data;

  73. //HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,1);
  74. mcp23s17_send(IODIRA_0,0x00);
  75. mcp23s17_send(IODIRB_0,0xFF);
  76. mcp23s17_send(GPPUB_0,0xFF);

  77. for(uint8_t i=0;i<8;i++){
  78. static uint8_t data=0;
  79. data|=1<<i;
  80. mcp23s17_send(OLATA_0,data);
  81. HAL_Delay(100);
  82. }
  83. HAL_Delay(3000);
  84. while (1)
  85. {
  86. data = mcp23s17_receive(GPIOB_0);
  87. mcp23s17_send(OLATA_0,data);

  88. }
  89. /* USER CODE END 3 */
  90. }

  91. /**
  92. * @brief System Clock Configuration
  93. * @retval None
  94. */
  95. void SystemClock_Config(void)
  96. {
  97. RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  98. RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  99. /** Initializes the RCC Oscillators according to the specified parameters
  100. * in the RCC_OscInitTypeDef structure.
  101. */
  102. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  103. RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  104. RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  105. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  106. RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  107. RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  108. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  109. {
  110. Error_Handler();
  111. }
  112. /** Initializes the CPU, AHB and APB buses clocks
  113. */
  114. RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  115. |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  116. RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  117. RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  118. RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  119. RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  120. if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  121. {
  122. Error_Handler();
  123. }
  124. }

  125. /**
  126. * @brief SPI1 Initialization Function
  127. * @param None
  128. * @retval None
  129. */
  130. static void MX_SPI1_Init(void)
  131. {

  132. /* USER CODE BEGIN SPI1_Init 0 */

  133. /* USER CODE END SPI1_Init 0 */

  134. /* USER CODE BEGIN SPI1_Init 1 */

  135. /* USER CODE END SPI1_Init 1 */
  136. /* SPI1 parameter configuration*/
  137. hspi1.Instance = SPI1;
  138. hspi1.Init.Mode = SPI_MODE_MASTER;
  139. hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  140. hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  141. hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  142. hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  143. hspi1.Init.NSS = SPI_NSS_SOFT;
  144. hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
  145. hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  146. hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  147. hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  148. hspi1.Init.CRCPolynomial = 10;
  149. if (HAL_SPI_Init(&hspi1) != HAL_OK)
  150. {
  151. Error_Handler();
  152. }
  153. /* USER CODE BEGIN SPI1_Init 2 */

  154. /* USER CODE END SPI1_Init 2 */

  155. }

  156. /**
  157. * @brief GPIO Initialization Function
  158. * @param None
  159. * @retval None
  160. */
  161. static void MX_GPIO_Init(void)
  162. {
  163. GPIO_InitTypeDef GPIO_InitStruct = {0};

  164. /* GPIO Ports Clock Enable */
  165. __HAL_RCC_GPIOA_CLK_ENABLE();

  166. /*Configure GPIO pin Output Level */
  167. HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);

  168. /*Configure GPIO pin : PA4 */
  169. GPIO_InitStruct.Pin = GPIO_PIN_4;
  170. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  171. GPIO_InitStruct.Pull = GPIO_NOPULL;
  172. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  173. HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  174. }

  175. /* USER CODE BEGIN 4 */

  176. /* USER CODE END 4 */

  177. /**
  178. * @brief This function is executed in case of error occurrence.
  179. * @retval None
  180. */
  181. void Error_Handler(void)
  182. {
  183. /* USER CODE BEGIN Error_Handler_Debug */
  184. /* User can add his own implementation to report the HAL error return state */
  185. __disable_irq();
  186. while (1)
  187. {
  188. }
  189. /* USER CODE END Error_Handler_Debug */
  190. }

  191. #ifdef USE_FULL_ASSERT
  192. /**
  193. * @brief Reports the name of the source file and the source line number
  194. * where the assert_param error has occurred.
  195. * @param file: pointer to the source file name
  196. * @param line: assert_param error line source number
  197. * @retval None
  198. */
  199. void assert_failed(uint8_t *file, uint32_t line)
  200. {
  201. /* USER CODE BEGIN 6 */
  202. /* User can add his own implementation to report the file name and line number,
  203. ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  204. /* USER CODE END 6 */
  205. }
  206. #endif /* USE_FULL_ASSERT */

  207. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/



I just use the simulator since I don't have this chip in my own lab. It was release many years now that I could not find it at local store. It is available from some popular online store such as Ali-Express, E bay or Amazon. 

STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
Input Reading #1

 
STM32 Blue Pill HSPI1 and MCP23S17 GPIO Example
Input Reading #2

Click here to download its source file. 


 



320x50

Search This Blog

tyro-728x90