lz菜鸟,最近在想用spi和外部芯片通信,搞半天没弄出来。贴出代码,大家看看有什么问题。#include <spi.h>
void Spi2_4438_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
/* 使能gpio时钟和SPI2 */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
/* Enable SCK, MOSI, MISO and NSS GPIO clocks using RCC_AHB1PeriphClockCmd()*/
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); //?
/* Connect PB12 to SPI2_SCK */
GPIO_PinAFConfig(GPIOB, GPIO_PinSource12, GPIO_AF_SPI2);
/* Connect PB14 to SPI2_MISO */
GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_SPI2);
/* Connect PB15 to SPI2_MOSI */
GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_SPI2);
/* Configure SPI2 pins as alternate function (No need to
configure PB13 since NSS will be managed by software) */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_14|GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
/*spi CONFIGURATION*/
SPI_Cmd(SPI2, DISABLE); //使能SPI2
SPI_InitStructure.SPI_Direction =SPI_Direction_2Lines_FullDuplex; //双线输入输出全双工模式
SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //设置为SPI的主机模式
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //SPI数据大小:发送8位帧数据结构
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //设备空闲状态时同步时钟SCK的状态,High表示高电平,Low表示低电平
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //时钟相位,1表示在同步时钟SCK的奇数沿边采样,2表示偶数沿边采样
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //NSS由软件控件片选
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;//时钟的预分频值
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //MSB高位在前
SPI_InitStructure.SPI_CRCPolynomial = 7; //CRC较验和的多项式
SPI_Init(SPI2, &SPI_InitStructure); //初始化SPI2的配置项
SPI_Cmd(SPI2, ENABLE); //使能SPI2
}
void main(void)
{
// init_gpled(); //亮灯
// 初始化spi
uint16_t tmp;
tmp=5;
Spi2_4438_Init();
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET)
{
}
SPI_I2S_SendData(SPI2,0);
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET)
{
}
SPI_I2S_ReceiveData(SPI2);
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET)
{
}
SPI_I2S_SendData(SPI2,0x0c);
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET)
{
}
tmp=SPI_I2S_ReceiveData(SPI2);
if(tmp!=0)
{
init_gpled();
}
}
单步调试到 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET)
{
}
这步的时候就卡主了,也不知道是什么原因,不知道是不是初始化的时钟没有配置好还是什么地。求大神帮帮忙 |