我一直在使用STM32F103C8,尝试了一段时间来获得SPI接口。一直在使用 Atollic TrueStudio。我还是新手,所以如果这是一个愚蠢的问题,我希望你能原谅我。
无论我尝试什么,我似乎都无法在 SPI 接口上传输任何东西。我浏览了手册,我认为我做的一切都是正确的,但显然不是。从我读到的,它似乎是:
- 在 RCC APB2ENR 中启用 SPI 时钟
- 配置 SPI CR1 寄存器
- 使用 SPE 位启用 SPI
- 通过将数据加载到 SPI-> DR 寄存器来发送
- 通过从 SPI-> DR 寄存器读取数据来接收,因为有一个发送和一个接收缓冲区链接到 SPI->DR
我尝试将 MOSI 引脚循环回 MISO 引脚并进行写入,但一无所获。然后我连接了一个逻辑分析仪,SPI时钟引脚甚至没有做任何事情。下面的相关代码,如果有人可以提供帮助,那就太好了:
void PrintStrToUART(char str[])
{
char *pointertostr;
for (pointertostr = &str[0]; *pointertostr != '\0'; pointertostr++){
USART1 -> DR = (*pointertostr & USART_DR_DR);
while ((USART1 -> SR & USART_SR_TXE) == 0){
;
}
}
}
void PrintCharArrayToUART(unsigned char str[], int arraysize){
int j;
unsigned char buffer[((5*arraysize)-2)];
unsigned char *positionpointer = &buffer[0];
for(j=0; j <= (arraysize-1); j++){
if(j){
positionpointer += sprintf(positionpointer, ", ");
}
positionpointer += sprintf(positionpointer, "%d", str[j]);
}
int newarrayend;
newarrayend = (positionpointer - &buffer[0]);
PrintStrToUART("[");
for(j = 0; j <= newarrayend; j++){
USART1 -> DR = (buffer[j] & USART_DR_DR);
while ((USART1 -> SR & USART_SR_TXE) == 0){
;
}
}
PrintStrToUART("]\n\r");
}
void SelfSPIInit(void){ //because the Mx one is not working
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN; //Enable SPI clock
//Set baud prescaler
SPI1->CR1 = SPI_CR1_BR; //Slowest SPI I can have
//CPHA CPOL
SPI1-> CR1 &= ~(SPI_CR1_CPOL | SPI_CR1_CPHA);
//8 bit data format
SPI1->CR1 &= ~(SPI_CR1_DFF);
//Full duplex mode
SPI1->CR1 &= ~(SPI_CR1_BIDIMODE);
SPI1->CR1 &= ~(SPI_CR1_RXONLY);
//MSB first
SPI1->CR1 &= ~(SPI_CR1_LSBFIRST);
//Master mode
SPI1->CR1 |= SPI_CR1_MSTR;
//Software NSS mode off
SPI1->CR1 |= SPI_CR1_SSM | SPI_CR1_SSI;
//Enable
SPI1->CR1 |= SPI_CR1_SPE;
//Enable the SPI GPIO pins
}
int main(void)
{
int i;
HAL_Init();
/* Configure the system clock */
SystemClock_Config(); //config to run at the correct speed
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_I2C1_Init();
MX_TIM1_Init();
MX_USART1_UART_Init();
MX_TIM2_Init();
MX_CRC_Init();
MX_USART2_UART_Init();
MX_ADC1_Init();
MX_TIM3_Init();
//MX_SPI1_Init();
SelfSPIInit();
TIM1 -> CR1 |= TIM_CR1_CEN;
TIM2 -> CR1 |= TIM_CR1_CEN;
I2C1 -> CR1 |= I2C_CR1_PE; //peripheral enable
SPI1 -> CR1 |= SPI_CR1_SPE;
unsigned char newchararray[21] = {0x41};
unsigned char *pnewchararray = &newchararray[0];
unsigned char recarray[7] = {127};
unsigned char *precarray = &recarray[0];
while (1)
{
GPIOC -> BSRR |= GPIO_BSRR_BR13;
GPIOA -> BSRR |= GPIO_BSRR_BR6;
MilliSecondDelay(500);
GPIOC -> BSRR |= GPIO_BSRR_BS13;
GPIOA -> BSRR |= GPIO_BSRR_BS6;
MilliSecondDelay(500);
SPI1->DR = *pnewchararray;
while((SPI1->SR & SPI_SR_TXE) == 0){
//while transmit buffer not empty, wait
;
}
while((SPI1->SR & SPI_SR_RXNE) == 0){
;//while receive buffer not empty
}
*precarray = SPI1->DR;
PrintCharArrayToUART(precarray, 7);
}
}
对缩进感到抱歉,正如我所说,我对此仍然很陌生,但这就是编译和运行的代码。任何帮助表示赞赏,谢谢!
编辑:不确定我是否应该包含 USART 功能,这只是为了打印到我的笔记本电脑上,这样我就可以看到 SPI 数据寄存器有什么。但我想如果我把它包括在内,这个程序会更有意义。