- UID
- 1029342
- 性别
- 男
|
环境:
主机:WIN7
开发环境:MDK4.23
MCU:STM32F103CBT6
说明:
软件设置NSS脚,利用查询方式传输
源代码:
初始化代码:
[cpp] view plaincopy
- //关闭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);
发送代码:
[cpp] view plaincopy
- //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 ) ;
- }
接收代码:
[cpp] view plaincopy
- //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脚电平设置:
[cpp] view plaincopy
- //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 ) ;
- }
示例代码:
[cpp] view plaincopy
- uint8 NtrxReadSingleSPI( uint8 Addr )
- {
- NtrxBufferType r ;
- NtrxSSN_Lo() ;
- SPI_ReadBytes( Addr, &r, 1 ) ;
- NtrxSSN_Hi() ;
- return r ;
- }
|
|