bigbat 发表于 2024-3-14 14:11

【STM32U5A5ZJ开发板】 SPI总线接口及SSD1306 OLED测试

<p>STM32U5A5ZJ开发板的SPI总线测试使用SPI 接口的OLED SSD1306芯片进行测试,SSD1306芯片只使用了SPI的输出功能,所以不能反应出SPI总线的全面特性,本来这次想使用DMA操作SPI接口,但是经过几次尝试STM32CUBE都无法生成DMA的初始化代码,所以只能使用普通模式测试SPI总线了。</p>

<p>SSD1306 是一款SPI/I2C双接口的芯片,可以通过引脚配置接口模式,但是成品的OLED屏是固定的接口设置。</p>

<p> &nbsp;</p>

<p>SPI设置的主要接口为D0、D1、DC、VCC、GND、CS、RES 主要接口,</p>

<p>D0&nbsp; &nbsp;---------------- SPI CLK</p>

<p>D1&nbsp; &nbsp;---------------- SPI MOSI</p>

<p>DC&nbsp; ---------------- 数据/命令选择</p>

<p>VCC --------------- 3.3V电源</p>

<p>GND---------------- 电源地</p>

<p>CS ----------------- 芯片使能</p>

<p>RES --------------- 复位信号</p>

<p>其中CS为选择信号,其它为必须的信号。</p>

<p>1、首先设置必要的系统时钟</p>

<p>&nbsp; 将系统时钟设为160MHZ,SPI总线是使用标准的系统总线时钟,所以不需要额外的其它设置</p>

<p>2、SPI设置和SSD1306控制引脚设置</p>

<p>物理连接为:SPI1接口,D0 CLK&nbsp; PA5,&nbsp;D1 MOSI PA7,DC PF12,RES PD15</p>

<p>&nbsp; SPI设置中需要将数据的长度修改为8位,其它的默认即可。设置完成后生成代码。</p>

<p>3、SSD驱动程序</p>

<p>主要的程序逻辑为:</p>

<p>&nbsp; &nbsp; &nbsp; &nbsp; ssd1306_SetCursor(0, 0);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;ssd1306_WriteString(timerStr, Font_11x18, White);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;ssd1306_UpdateScreen();</p>

<p>以上三个函数,设置光标,输出图形、更新设置。</p>

<pre>
<code class="language-cpp">/* USER CODE BEGIN Header */
/**
******************************************************************************
* @File : main.c
* @brief : Main program body
******************************************************************************
* @attention *
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "ssd1306.h"
#include "ssd1306_fonts.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

I2C_HandleTypeDef hi2c1;

UART_HandleTypeDef hlpuart1;
UART_HandleTypeDef huart1;
DMA_HandleTypeDef handle_LPDMA1_Channel0;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim8;
DMA_NodeTypeDef Node_GPDMA1_Channel0;
DMA_QListTypeDef List_GPDMA1_Channel0;
DMA_HandleTypeDef handle_GPDMA1_Channel0;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void SystemPower_Config(void);
static void MX_GPIO_Init(void);
static void MX_GPDMA1_Init(void);
static void MX_LPDMA1_Init(void);
static void MX_ICACHE_Init(void);
static void MX_LPUART1_UART_Init(void);
static void MX_TIM8_Init(void);
static void MX_TIM2_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_I2C1_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
* @briefThe application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
char timerStr[] = {"STM32U5 "};
/* USER CODE END 1 */

/* MCU Configuration--------------------------------------------------------*/

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

/* USER CODE BEGIN Init */

/* USER CODE END Init */

/* Configure the system clock */
SystemClock_Config();

/* Configure the System Power */
SystemPower_Config();

/* USER CODE BEGIN SysInit */

/* USER CODE END SysInit */

/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_GPDMA1_Init();
MX_LPDMA1_Init();
MX_ICACHE_Init();
MX_LPUART1_UART_Init();
MX_TIM8_Init();
MX_TIM2_Init();
MX_USART1_UART_Init();
MX_I2C1_Init();
/* USER CODE BEGIN 2 */
ssd1306_Init();
        ssd1306_Fill(Black);
        ssd1306_UpdateScreen();
/* USER CODE END 2 */

/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
    /* USER CODE END WHILE */
                ssd1306_SetCursor(0, 0);
                ssd1306_WriteString(timerStr, Font_11x18, White);
                ssd1306_UpdateScreen();
                HAL_GPIO_TogglePin(LED1_GPIO_Port,LED1_Pin);
                HAL_Delay(500);
    /* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}

/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

/** Configure the main internal regulator output voltage
*/
if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
{
    Error_Handler();
}

/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMBOOST = RCC_PLLMBOOST_DIV1;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 10;
RCC_OscInitStruct.PLL.PLLP = 2;
RCC_OscInitStruct.PLL.PLLQ = 2;
RCC_OscInitStruct.PLL.PLLR = 1;
RCC_OscInitStruct.PLL.PLLRGE = RCC_PLLVCIRANGE_1;
RCC_OscInitStruct.PLL.PLLFRACN = 0;
if (HAL_RCC_OscConfig(&amp;RCC_OscInitStruct) != HAL_OK)
{
    Error_Handler();
}

/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_PCLK3;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB3CLKDivider = RCC_HCLK_DIV1;

if (HAL_RCC_ClockConfig(&amp;RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
{
    Error_Handler();
}
}

/**
* @brief Power Configuration
* @retval None
*/
static void SystemPower_Config(void)
{

/*
   * Disable the internal Pull-Up in Dead Battery pins of UCPD peripheral
   */
HAL_PWREx_DisableUCPDDeadBattery();

/*
   * Switch to SMPS regulator instead of LDO
   */
if (HAL_PWREx_ConfigSupply(PWR_SMPS_SUPPLY) != HAL_OK)
{
    Error_Handler();
}
/* USER CODE BEGIN PWR */
/* USER CODE END PWR */
}

/**
* @brief GPDMA1 Initialization Function
* @param None
* @retval None
*/
static void MX_GPDMA1_Init(void)
{

/* USER CODE BEGIN GPDMA1_Init 0 */

/* USER CODE END GPDMA1_Init 0 */

/* Peripheral clock enable */
__HAL_RCC_GPDMA1_CLK_ENABLE();

/* GPDMA1 interrupt Init */
    HAL_NVIC_SetPriority(GPDMA1_Channel0_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(GPDMA1_Channel0_IRQn);

/* USER CODE BEGIN GPDMA1_Init 1 */

/* USER CODE END GPDMA1_Init 1 */
/* USER CODE BEGIN GPDMA1_Init 2 */

/* USER CODE END GPDMA1_Init 2 */

}

/**
* @brief I2C1 Initialization Function
* @param None
* @retval None
*/
static void MX_I2C1_Init(void)
{

/* USER CODE BEGIN I2C1_Init 0 */

/* USER CODE END I2C1_Init 0 */

/* USER CODE BEGIN I2C1_Init 1 */

/* USER CODE END I2C1_Init 1 */
hi2c1.Instance = I2C1;
hi2c1.Init.Timing = 0x30909DEC;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&amp;hi2c1) != HAL_OK)
{
    Error_Handler();
}

/** Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&amp;hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
{
    Error_Handler();
}

/** Configure Digital filter
*/
if (HAL_I2CEx_ConfigDigitalFilter(&amp;hi2c1, 0) != HAL_OK)
{
    Error_Handler();
}
/* USER CODE BEGIN I2C1_Init 2 */

/* USER CODE END I2C1_Init 2 */

}

/**
* @brief ICACHE Initialization Function
* @param None
* @retval None
*/
static void MX_ICACHE_Init(void)
{

/* USER CODE BEGIN ICACHE_Init 0 */

/* USER CODE END ICACHE_Init 0 */

/* USER CODE BEGIN ICACHE_Init 1 */

/* USER CODE END ICACHE_Init 1 */

/** Enable instruction cache in 1-way (direct mapped cache)
*/
if (HAL_ICACHE_ConfigAssociativityMode(ICACHE_1WAY) != HAL_OK)
{
    Error_Handler();
}
if (HAL_ICACHE_Enable() != HAL_OK)
{
    Error_Handler();
}
/* USER CODE BEGIN ICACHE_Init 2 */

/* USER CODE END ICACHE_Init 2 */

}

/**
* @brief LPDMA1 Initialization Function
* @param None
* @retval None
*/
static void MX_LPDMA1_Init(void)
{

/* USER CODE BEGIN LPDMA1_Init 0 */

/* USER CODE END LPDMA1_Init 0 */

/* Peripheral clock enable */
__HAL_RCC_LPDMA1_CLK_ENABLE();

/* LPDMA1 interrupt Init */
    HAL_NVIC_SetPriority(LPDMA1_Channel0_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(LPDMA1_Channel0_IRQn);

/* USER CODE BEGIN LPDMA1_Init 1 */

/* USER CODE END LPDMA1_Init 1 */
/* USER CODE BEGIN LPDMA1_Init 2 */

/* USER CODE END LPDMA1_Init 2 */

}

/**
* @brief LPUART1 Initialization Function
* @param None
* @retval None
*/
static void MX_LPUART1_UART_Init(void)
{

/* USER CODE BEGIN LPUART1_Init 0 */

/* USER CODE END LPUART1_Init 0 */

/* USER CODE BEGIN LPUART1_Init 1 */

/* USER CODE END LPUART1_Init 1 */
hlpuart1.Instance = LPUART1;
hlpuart1.Init.BaudRate = 115200;
hlpuart1.Init.WordLength = UART_WORDLENGTH_8B;
hlpuart1.Init.StopBits = UART_STOPBITS_1;
hlpuart1.Init.Parity = UART_PARITY_NONE;
hlpuart1.Init.Mode = UART_MODE_TX_RX;
hlpuart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
hlpuart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
hlpuart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
hlpuart1.FifoMode = UART_FIFOMODE_DISABLE;
if (HAL_UART_Init(&amp;hlpuart1) != HAL_OK)
{
    Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&amp;hlpuart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
    Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&amp;hlpuart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
    Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&amp;hlpuart1) != HAL_OK)
{
    Error_Handler();
}
/* USER CODE BEGIN LPUART1_Init 2 */

/* USER CODE END LPUART1_Init 2 */

}

/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{

/* USER CODE BEGIN USART1_Init 0 */

/* USER CODE END USART1_Init 0 */

/* USER CODE BEGIN USART1_Init 1 */

/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&amp;huart1) != HAL_OK)
{
    Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&amp;huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
    Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&amp;huart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
    Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&amp;huart1) != HAL_OK)
{
    Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */

/* USER CODE END USART1_Init 2 */

}

/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{

/* USER CODE BEGIN TIM2_Init 0 */

/* USER CODE END TIM2_Init 0 */

TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};

/* USER CODE BEGIN TIM2_Init 1 */

/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 159;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 2000000;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&amp;htim2) != HAL_OK)
{
    Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&amp;htim2, &amp;sMasterConfig) != HAL_OK)
{
    Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 1000000;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&amp;htim2, &amp;sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
    Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */

/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&amp;htim2);

}

/**
* @brief TIM8 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM8_Init(void)
{

/* USER CODE BEGIN TIM8_Init 0 */

/* USER CODE END TIM8_Init 0 */

TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};

/* USER CODE BEGIN TIM8_Init 1 */

/* USER CODE END TIM8_Init 1 */
htim8.Instance = TIM8;
htim8.Init.Prescaler = 159;
htim8.Init.CounterMode = TIM_COUNTERMODE_UP;
htim8.Init.Period = 1000;
htim8.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim8.Init.RepetitionCounter = 0;
htim8.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_PWM_Init(&amp;htim8) != HAL_OK)
{
    Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterOutputTrigger2 = TIM_TRGO2_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&amp;htim8, &amp;sMasterConfig) != HAL_OK)
{
    Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 500;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_PWM_ConfigChannel(&amp;htim8, &amp;sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
    Error_Handler();
}
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.BreakFilter = 0;
sBreakDeadTimeConfig.BreakAFMode = TIM_BREAK_AFMODE_INPUT;
sBreakDeadTimeConfig.Break2State = TIM_BREAK2_DISABLE;
sBreakDeadTimeConfig.Break2Polarity = TIM_BREAK2POLARITY_HIGH;
sBreakDeadTimeConfig.Break2Filter = 0;
sBreakDeadTimeConfig.Break2AFMode = TIM_BREAK_AFMODE_INPUT;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if (HAL_TIMEx_ConfigBreakDeadTime(&amp;htim8, &amp;sBreakDeadTimeConfig) != HAL_OK)
{
    Error_Handler();
}
/* USER CODE BEGIN TIM8_Init 2 */

/* USER CODE END TIM8_Init 2 */
HAL_TIM_MspPostInit(&amp;htim8);

}

/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */

/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();

/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
* @briefThis function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}

#ifdefUSE_FULL_ASSERT
/**
* @briefReports the name of the source file and the source line number
*         where the assert_param error has occurred.
* @paramfile: pointer to the source file name
* @paramline: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
   ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
</code></pre>

<p>主要程序较为简单,主要是驱动程序。</p>

<pre>
<code class="language-cpp">#include "ssd1306.h"

#if defined(SSD1306_USE_I2C)

void ssd1306_Reset(void) {
        /* for I2C - do nothing */
}

// Send a byte to the command register
void ssd1306_WriteCommand(uint8_t byte) {
        HAL_I2C_Mem_Write(&amp;SSD1306_I2C_PORT, SSD1306_I2C_ADDR, 0x00, 1, &amp;byte, 1, HAL_MAX_DELAY);
}

// Send data
void ssd1306_WriteData(uint8_t* buffer, size_t buff_size) {
        HAL_I2C_Mem_Write(&amp;SSD1306_I2C_PORT, SSD1306_I2C_ADDR, 0x40, 1, buffer, buff_size, HAL_MAX_DELAY);
}

#elif defined(SSD1306_USE_SPI)

void ssd1306_Reset(void) {
        // CS = High (not selected)
        HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_SET);

        // Reset the OLED
        HAL_GPIO_WritePin(SSD1306_Reset_Port, SSD1306_Reset_Pin, GPIO_PIN_RESET);
        HAL_Delay(10);
        HAL_GPIO_WritePin(SSD1306_Reset_Port, SSD1306_Reset_Pin, GPIO_PIN_SET);
        HAL_Delay(10);
}

// Send a byte to the command register
void ssd1306_WriteCommand(uint8_t byte) {
    HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_RESET); // select OLED
    HAL_GPIO_WritePin(SSD1306_DC_Port, SSD1306_DC_Pin, GPIO_PIN_RESET); // command
    HAL_SPI_Transmit(&amp;SSD1306_SPI_PORT, (uint8_t *) &amp;byte, 1, HAL_MAX_DELAY);
    HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_SET); // un-select OLED
}

// Send data
void ssd1306_WriteData(uint8_t* buffer, size_t buff_size) {
    HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_RESET); // select OLED
    HAL_GPIO_WritePin(SSD1306_DC_Port, SSD1306_DC_Pin, GPIO_PIN_SET); // data
    HAL_SPI_Transmit(&amp;SSD1306_SPI_PORT, buffer, buff_size, HAL_MAX_DELAY);
    HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_SET); // un-select OLED
}

#else
#error "You should define SSD1306_USE_SPI or SSD1306_USE_I2C macro"
#endif


// Screenbuffer
static uint8_t SSD1306_Buffer;

// Screen object
static SSD1306_t SSD1306;

// Initialize the oled screen
void ssd1306_Init(void) {
        // Reset OLED
        ssd1306_Reset();

    // Wait for the screen to boot
    HAL_Delay(100);
   
    // Init OLED
    ssd1306_WriteCommand(0xAE); //display off

    ssd1306_WriteCommand(0x20); //Set Memory Addressing Mode   
    ssd1306_WriteCommand(0x10); // 00,Horizontal Addressing Mode; 01,Vertical Addressing Mode;
                              // 10,Page Addressing Mode (RESET); 11,Invalid

    ssd1306_WriteCommand(0xB0); //Set Page Start Address for Page Addressing Mode,0-7

#ifdef SSD1306_MIRROR_VERT
    ssd1306_WriteCommand(0xC0); // Mirror vertically
#else
    ssd1306_WriteCommand(0xC8); //Set COM Output Scan Direction
#endif

    ssd1306_WriteCommand(0x00); //---set low column address
    ssd1306_WriteCommand(0x10); //---set high column address

    ssd1306_WriteCommand(0x40); //--set start line address - CHECK

    ssd1306_WriteCommand(0x81); //--set contrast control register - CHECK
    ssd1306_WriteCommand(0xFF);

#ifdef SSD1306_MIRROR_HORIZ
    ssd1306_WriteCommand(0xA0); // Mirror horizontally
#else
    ssd1306_WriteCommand(0xA1); //--set segment re-map 0 to 127 - CHECK
#endif

#ifdef SSD1306_INVERSE_COLOR
    ssd1306_WriteCommand(0xA7); //--set inverse color
#else
    ssd1306_WriteCommand(0xA6); //--set normal color
#endif

    ssd1306_WriteCommand(0xA8); //--set multiplex ratio(1 to 64) - CHECK
    ssd1306_WriteCommand(0x3F); //

    ssd1306_WriteCommand(0xA4); //0xa4,Output follows RAM content;0xa5,Output ignores RAM content

    ssd1306_WriteCommand(0xD3); //-set display offset - CHECK
    ssd1306_WriteCommand(0x00); //-not offset

    ssd1306_WriteCommand(0xD5); //--set display clock divide ratio/oscillator frequency
    ssd1306_WriteCommand(0xF0); //--set divide ratio

    ssd1306_WriteCommand(0xD9); //--set pre-charge period
    ssd1306_WriteCommand(0x22); //

    ssd1306_WriteCommand(0xDA); //--set com pins hardware configuration - CHECK
    ssd1306_WriteCommand(0x12);

    ssd1306_WriteCommand(0xDB); //--set vcomh
    ssd1306_WriteCommand(0x20); //0x20,0.77xVcc

    ssd1306_WriteCommand(0x8D); //--set DC-DC enable
    ssd1306_WriteCommand(0x14); //
    ssd1306_WriteCommand(0xAF); //--turn on SSD1306 panel

    // Clear screen
    ssd1306_Fill(Black);
   
    // Flush buffer to screen
    ssd1306_UpdateScreen();
   
    // Set default values for screen object
    SSD1306.CurrentX = 0;
    SSD1306.CurrentY = 0;
   
    SSD1306.Initialized = 1;
}

// Fill the whole screen with the given color
void ssd1306_Fill(SSD1306_COLOR color) {
    /* Set memory */
    uint32_t i;

    for(i = 0; i &lt; sizeof(SSD1306_Buffer); i++) {
      SSD1306_Buffer = (color == Black) ? 0x00 : 0xFF;
    }
}

// Write the screenbuffer with changed to the screen
void ssd1306_UpdateScreen(void) {
    uint8_t i;
    for(i = 0; i &lt; 8; i++) {
      ssd1306_WriteCommand(0xB0 + i);
      ssd1306_WriteCommand(0x00);
      ssd1306_WriteCommand(0x10);
      ssd1306_WriteData(&amp;SSD1306_Buffer,SSD1306_WIDTH);
    }
}

//    Draw one pixel in the screenbuffer
//    X =&gt; X Coordinate
//    Y =&gt; Y Coordinate
//    color =&gt; Pixel color
void ssd1306_DrawPixel(uint8_t x, uint8_t y, SSD1306_COLOR color) {
    if(x &gt;= SSD1306_WIDTH || y &gt;= SSD1306_HEIGHT) {
      // Don't write outside the buffer
      return;
    }
   
    // Check if pixel should be inverted
    if(SSD1306.Inverted) {
      color = (SSD1306_COLOR)!color;
    }
   
    // Draw in the right color
    if(color == White) {
      SSD1306_Buffer |= 1 &lt;&lt; (y % 8);
    } else {
      SSD1306_Buffer &amp;= ~(1 &lt;&lt; (y % 8));
    }
}

// Draw 1 char to the screen buffer
// ch         =&gt; char om weg te schrijven
// Font   =&gt; Font waarmee we gaan schrijven
// color   =&gt; Black or White
char ssd1306_WriteChar(char ch, FontDef Font, SSD1306_COLOR color) {
    uint32_t i, b, j;
   
    // Check remaining space on current line
    if (SSD1306_WIDTH &lt;= (SSD1306.CurrentX + Font.FontWidth) ||
      SSD1306_HEIGHT &lt;= (SSD1306.CurrentY + Font.FontHeight))
    {
      // Not enough space on current line
      return 0;
    }
   
    // Use the font to write
    for(i = 0; i &lt; Font.FontHeight; i++) {
      b = Font.data[(ch - 32) * Font.FontHeight + i];
      for(j = 0; j &lt; Font.FontWidth; j++) {
            if((b &lt;&lt; j) &amp; 0x8000){
                ssd1306_DrawPixel(SSD1306.CurrentX + j, (SSD1306.CurrentY + i), (SSD1306_COLOR) color);
            } else {
                ssd1306_DrawPixel(SSD1306.CurrentX + j, (SSD1306.CurrentY + i), (SSD1306_COLOR)!color);
            }
      }
    }
   
    // The current space is now taken
    SSD1306.CurrentX += Font.FontWidth;
   
    // Return written char for validation
    return ch;
}

// Write full string to screenbuffer
char ssd1306_WriteString(char* str, FontDef Font, SSD1306_COLOR color) {
    // Write until null-byte
    while (*str) {
      if (ssd1306_WriteChar(*str, Font, color) != *str) {
            // Char could not be written
            return *str;
      }
      
      // Next char
      str++;
    }
   
    // Everything ok
    return *str;
}

// Position the cursor
void ssd1306_SetCursor(uint8_t x, uint8_t y) {
    SSD1306.CurrentX = x;
    SSD1306.CurrentY = y;
}
</code></pre>

<p>驱动程序为从github上下载的程序。</p>

<p>测试过程:</p>

<p>运行程序就可以显示内容STM32U5,内容</p>

<p> &nbsp;</p>

freebsder 发表于 2024-3-14 15:13

<p>谢谢大佬分享</p>
页: [1]
查看完整版本: 【STM32U5A5ZJ开发板】 SPI总线接口及SSD1306 OLED测试