STM32的SPI查詢方式傳輸測試
主機:WIN7
本文引用地址:http://www.ex-cimer.com/article/201611/318263.htm開發(fā)環(huán)境: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);
發(fā)送代碼:
//SPI發(fā)送一個字節(jié)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讀取一個字節(jié)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腳拉低,開始發(fā)送數據void NtrxSSN_Lo( void ){GPIO_ResetBits( NTRX_SSN_PORT, NTRX_SSN_PIN ) ;}//SSN腳置高,結束發(fā)送數據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電平.
評論