Air105 包含五組普通SPI, 可以以半/全雙工, 同步, 序列的方式通訊. 可以被設定成主模式併為從裝置提供時鐘(SCK), 還能以多主設定方式工作. 這裡不介紹QSPI(高速SPI).
包含2個獨立的深度為16的收發FIFO
以驅動 MAX7219 為例, 初始化 SPI0 的程式碼, 使用 GPIO_PinRemapConfig
複用後, 不需要再單獨進行GPIO初始化
#define MAX7219_SPIx SPIM0
#define MAX7219_CS_PORT GPIOC
#define MAX7219_CS_PIN GPIO_Pin_13
#define MAX7219_SPIx_PORT GPIOC
#define MAX7219_SPIx_PINS GPIO_Pin_12|GPIO_Pin_14|GPIO_Pin_15
#define MAX7219_SPIx_REMAP GPIO_Remap_2
void MAX7219_SPI_Init(void)
{
SPI_InitTypeDef SPI_InitStructure;
SYSCTRL_APBPeriphClockCmd(SYSCTRL_APBPeriph_GPIO | SYSCTRL_APBPeriph_SPI0, ENABLE);
SYSCTRL_APBPeriphResetCmd(SYSCTRL_APBPeriph_SPI0, ENABLE);
//SPI0
GPIO_PinRemapConfig(MAX7219_SPIx_PORT, MAX7219_SPIx_PINS, MAX7219_SPIx_REMAP);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_0;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
// 這兩項不能省略, 否則 SPI_Init 初始化會阻塞
SPI_InitStructure.SPI_RXFIFOFullThreshold = SPI_RXFIFOFullThreshold_1;
SPI_InitStructure.SPI_TXFIFOEmptyThreshold = SPI_TXFIFOEmptyThreshold_10;
SPI_Init(MAX7219_SPIx, &SPI_InitStructure);
SPI_Cmd(MAX7219_SPIx, ENABLE);
}
CS使用主動控制, 因此PC13單獨初始化GPIO
void MAX7219_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
SYSCTRL_APBPeriphClockCmd(SYSCTRL_APBPeriph_GPIO, ENABLE);
GPIO_InitStruct.GPIO_Pin = MAX7219_CS_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Remap = GPIO_Remap_1;
GPIO_Init(MAX7219_CS_PORT, &GPIO_InitStruct);
}
通過呼叫SPI_SendData
和SPI_ReceiveData
完成
uint8_t MAX7219_SendByte(uint8_t byte)
{
uint8_t data;
SPI_SendData(MAX7219_SPIx, byte);
while (RESET == SPI_GetFlagStatus(MAX7219_SPIx, SPI_FLAG_RXNE));
data = SPI_ReceiveData(MAX7219_SPIx);
return data;
}
又到了喜聞樂見的點燈環節. MAX7219 8x8的LED點陣是最簡單的SPI裝置了
PIN腳的具體位置, 檢視 https://wiki.luatos.com/_static/bom/Air105.html
* 3.3V -> VCC
* GND -> GND
* PC12 SPI0_CLK -> CLK
* PC13 CS -> CS
* PC14 SPI0_MOSI -> DIN
初始化需要的命令
#define DECODE_MODE 0x09
#define INTENSITY 0x0A
#define SCAN_LIMIT 0x0B
#define SHUT_DOWN 0x0C
#define DISPLAY_TEST 0x0F
片選指令
void MAX7219_ChipSelect(int state)
{
if (state)
{
GPIO_SetBits(MAX7219_CS_PORT, MAX7219_CS_PIN);
}
else
{
GPIO_ResetBits(MAX7219_CS_PORT, MAX7219_CS_PIN);
}
}
MAX7219通訊的基礎方法
void MAX7219_Write(uint8_t addr, uint8_t dat)
{
MAX7219_ChipSelect(0);
MAX7219_SendByte(addr);
MAX7219_SendByte(dat);
MAX7219_ChipSelect(1);
}
初始化程式碼
void MAX7219_Init(void)
{
MAX7219_Write(SHUT_DOWN, 0x01); // 0x00:shutdown, 0x01:normal
MAX7219_Write(DECODE_MODE, 0x00); // Bypass code B decoder, no-decode operation
MAX7219_Write(SCAN_LIMIT, 0x07); // Scan-limit, 0:1-digit, 1:2-digits, ... 7:8-digits
MAX7219_Write(INTENSITY, 0x01); // 0x00:min, 0xFF:max
MAX7219_Write(DISPLAY_TEST, 0x00); // 0x00:normal, 0x01:test mode
}
完整程式碼從這裡下載
https://gitee.com/iosetting/air105_project/tree/master/Demos/SPI/SPI_MAX7219_8x8LED