STM32的SPI查询方式传输测试
本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.
环境:
主机:WIN7
开发环境:MDK4.23
MCU:STM32F103CBT6
说明:
软件设置NSS脚,利用查询方式传输
源代码:
初始化代码:
//关闭SPI SPI_Cmd(SPI1,DISABLE); //初始化SPI接口的SSN脚以及NTRX的RST脚 NtrxCtrlInit(); //初始化SPI时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1 | RCC_APB2Periph_GPIOA,ENABLE); //配置SPI1引脚:SCK, MISO and MOSI GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP ; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz ; GPIO_Init( GPIOA, &GPIO_InitStructure ); // SPI1配置 SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex ; SPI_InitStructure.SPI_Mode = SPI_Mode_Master ; 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_Soft ; //SPI波特率分频设置:4M SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8 ; //SPI设置成LSB模式 SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_LSB ; SPI_InitStructure.SPI_CRCPolynomial = 7 ; SPI_Init( SPI1, &SPI_InitStructure ) ; //启动SPI SPI_Cmd(SPI1,ENABLE);
发送代码:
//SPI发送一个字节 static uint8 SPI_SendByte(uint8 Data) { // Loop while DR register in not emplty while( SPI_I2S_GetFlagStatus( SPI1, SPI_I2S_FLAG_TXE ) == RESET ) ; // Send byte through the SPI1 peripheral SPI_I2S_SendData( SPI1, Data ) ; // Wait to receive a byte while( SPI_I2S_GetFlagStatus( SPI1, SPI_I2S_FLAG_RXNE ) == RESET ) ; // Return the byte read from the SPI bus return SPI_I2S_ReceiveData( SPI1 ) ; }
接收代码:
//SPI读取一个字节 void SPI_ReadBytes( uint8 Addr, NtrxBufferPtr Buffer, uint8 Len ) { if( ( Len > 0x80 ) || ( Len == 0 ) ) Len = 1 ; SPI_SendByte( Len ) ; SPI_SendByte( Addr ) ; while( Len-- ) { *Buffer = SPI_SendByte( 0xFF ) ; Buffer ++ ; } }
NSS脚电平设置:
//SSN脚拉低,开始发送数据 void NtrxSSN_Lo( void ) { GPIO_ResetBits( NTRX_SSN_PORT, NTRX_SSN_PIN ) ; } //SSN脚置高,结束发送数据 void NtrxSSN_Hi( void ) { GPIO_SetBits( NTRX_SSN_PORT, NTRX_SSN_PIN ) ; }
示例代码:
uint8 NtrxReadSingleSPI( uint8 Addr ) { NtrxBufferType r ; NtrxSSN_Lo() ; SPI_ReadBytes( Addr, &r, 1 ) ; NtrxSSN_Hi() ; return r ; }
输出:
黄线为NSS脚电平,蓝线为CLK电平.