对应的SPI3端口的配置程序如下所示:
static voidSPI3_Configuration(void)
{
hspi3.Instance = SPI3;
hspi3.Init.Mode = SPI_MODE_MASTER;
hspi3.Init.Direction = SPI_DIRECTION_2LINES;
hspi3.Init.DataSize = SPI_DATASIZE_8BIT;
hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi3.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi3.Init.NSS = SPI_NSS_SOFT;
hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi3.Init.TIMode = SPI_TIMODE_DISABLE;
hspi3.Init.CRCCalculation =SPI_CRCCALCULATION_DISABLE;
hspi3.Init.CRCPolynomial = 7;
if (HAL_SPI_Init(&hspi3) != HAL_OK)
{
Error_Handler();
}
}
接下来我们实现通过SPI3接口读取摸你脸个采集值得程序。
/*获取采集的物理量值,并作平滑处理*/
voidGetMeasuredValue(void)
{
float currentValue[2]={-1.0,-1.0};
CalcMeasuredValue(currentValue);
if(smoothIndex>=SmoothCount)
{
smoothIndex=0;
}
aPara.phyPara.o2Concentration=SmoothingFilter(currentValue[0],AD1Value,smoothIndex,SmoothCount,(O2RANGE-O2ZERO),2.0,0.2);
aPara.phyPara.h2Concentration=SmoothingFilter(currentValue[1],AD2Value,smoothIndex,SmoothCount,(H2RANGE-H2ZERO),2.0,0.2);
smoothIndex++;
}
/*计算测量值,将AD转换的值转为物理量的对应值*/
static voidCalcMeasuredValue(float *newValue)
{
uint16_t measuredValue=0;
/*转化通道1的值*/
ADDA_AD7705_ENABLE();//使能器件
Delayus(200);
measuredValue=GetAD7705ChannelValue(Channel1,SPIReadWriteByte,CheckDataIsReady);
ADDA_AD7705_DISABLE();//片选取消
newValue[0]=PowerNPolyfit(((float)(measuredValue-AD1Zero)/(float)(AD1Scale-AD1Zero)),ADFactor[0],3)*(O2RANGE-O2ZERO)+O2ZERO;
Delayms(1);
/*转化通道2的值*/
ADDA_AD7705_ENABLE();//使能器件
Delayus(200);
measuredValue=GetAD7705ChannelValue(Channel2,SPIReadWriteByte,CheckDataIsReady);
ADDA_AD7705_DISABLE();//片选取消
newValue[1]=PowerNPolyfit(((float)(measuredValue-AD2Zero)/(float)(AD2Scale-AD2Zero)),ADFactor[1],3)*(H2RANGE-H2ZERO)+H2ZERO;
Delayms(1);
}
/*对SPI端口读写一个字节*/
static uint8_tSPIReadWriteByte(uint8_t data)
{
uint8_t rxData=0;
HAL_SPI_TransmitReceive(&hspi3,&data,&rxData,1,1000);
return rxData;
}
/*检查数据是否准备好*/
static uint8_tCheckDataIsReady(void)
{
return (uint8_t)HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_7);
}
3、测试结果
程序下装后,运行正常可一看到2个通道的采集数据。如下图所示:
我们在测试时,采集了两个传感器输出,在实际使用时,我们只需要一路接传感器,而另外一路我们采集锂电池的电压信号。