参考了《CC2640R2F BLE5.0 CC2640R2F SPI驱动实现》
该文章网址https://blog.csdn.net/leconiot/article/details/76808445;
初始化SPI的时候,使用函数SPI_Params_init(SPI_Params *params);
params的默认赋值为
* transferMode = SPI_MODE_BLOCKING
* transferTimeout = SPI_WAIT_FOREVER
* transferCallbackFxn = NULL
* mode = SPI_MASTER
* bitRate = 1000000 (Hz)
* dataSize = 8 (bits)
* frameFormat = SPI_POL0_PHA0
其中需要注意的是frameFormat,这是始终采样
SPI_POL0_PHA0 = 0, /*!< SPI mode Polarity 0 Phase 0 */
SPI_POL0_PHA1 = 1, /*!< SPI mode Polarity 0 Phase 1 */
SPI_POL1_PHA0 = 2, /*!< SPI mode Polarity 1 Phase 0 */
SPI_POL1_PHA1 = 3, /*!< SPI mode Polarity 1 Phase 1 */
SPI_TI = 4, /*!< TI mode (not supported on all
implementations) */
SPI_MW = 5 /*!< Micro-wire mode (not supported on all
implementations) */
根据外设的手册,选择对应的采样相位和极性,否则无法驱动起来硬件
其余的废话不多说,直接上代码:使用SPI一次发送一个字节的程序
SPI_Handle masterSpi;
SPI_Params spiParams;
SPI_Transaction transaction;
bool transferOK;
//SPI初始化
void SPI_open_init(){
/* Open SPI as master (default) */
SPI_Params_init(&spiParams);
spiParams.frameFormat = SPI_POL1_PHA1;
//spiParams.bitRate = 10000000;
masterSpi = SPI_open(Board_SPI_MASTER, &spiParams);
if (masterSpi == NULL) {
Display_printf(display, 0, 0, "Error initializing master SPI\n");
while (1);
}
else {
Display_printf(display, 0, 0, "Master SPI initialized\n");
}
}
//SPI发送
void SPI_WriteByte(uint8_t TxData){
uint8_t temp[2];
uint8_t temp1[2] = {0,0};
temp[0] = TxData;
transaction.count = 1;
transaction.txBuf = (void *) temp;
transaction.rxBuf = (void *) temp1;
/* Perform SPI transfer */
transferOK = SPI_transfer(masterSpi, &transaction);
if (transferOK) {
//Display_printf(display, 0, 0, "Master send: %x", temp[0]);
}
else {
//Display_printf(display, 0, 0, "Unsuccessful master SPI transfer");
}
}
//SPI接收
uint8_t SPI_ReadByte(){
uint8_t temp[2];
uint8_t temp1[2] = {0,0};
transaction.count = 1;
transaction.txBuf = (void *)temp1;
transaction.rxBuf = (void *) temp;
/* Perform SPI transfer */
transferOK = SPI_transfer(masterSpi, &transaction);
if (transferOK) {
//Display_printf(display, 0, 0, "Master received: %x", temp[0]);
}
else {
//Display_printf(display, 0, 0, "Unsuccessful master SPI transfer");
}
return temp[0];
}
其实写法大同小异,我看到有的文章说发送的时候可以给接收赋值为NULL;
transaction.txBuf = (void *) temp;
transaction.rxBuf = NULL;
不知道什么原因,如果这样写,我的外设就驱动不起来,