环境:
主机:WIN7
开发环境:MDK4.23
MCU:STM32F103CBT6
阐明:
软件设置NSS脚,使用查询方法传输
源代码:
初始化代码:
//封闭SPISPI_Cmd(SPI1,DISABLE);//初始化SPI接口的SSN脚以及NTRX的RST脚NtrxCtrlInit();//初始化SPI时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1 | RCC_APB2Periph_GPIOA,ENABLE);//装备SPI1引脚:SCK, MISO and MOSIGPIO_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波特率分频设置:4MSPI_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 ) ;//发动SPISPI_Cmd(SPI1,ENABLE);
发送代码:
//SPI发送一个字节static uint8 SPI_SendByte(uint8 Data){// Loop while DR register in not empltywhile( SPI_I2S_GetFlagStatus( SPI1, SPI_I2S_FLAG_TXE ) == RESET ) ;// Send byte through the SPI1 peripheralSPI_I2S_SendData( SPI1, Data ) ;// Wait to receive a bytewhile( SPI_I2S_GetFlagStatus( SPI1, SPI_I2S_FLAG_RXNE ) == RESET ) ;// Return the byte read from the SPI busreturn 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电平.