stm32f103zet6的HX711的驱动代码
时间: 2023-09-18 11:14:41 浏览: 101
HX711的驱动程序
以下是基于STM32F103系列的HX711驱动代码,使用的是GPIO和SPI接口:
```c
#include "hx711.h"
void HX711_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(HX711_SCK_GPIO_CLK | HX711_DOUT_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = HX711_SCK_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(HX711_SCK_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = HX711_DOUT_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(HX711_DOUT_GPIO_PORT, &GPIO_InitStructure);
}
void HX711_SPI_Config(void)
{
SPI_InitTypeDef SPI_InitStructure;
RCC_APB2PeriphClockCmd(HX711_SPI_CLK, ENABLE);
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_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(HX711_SPI, &SPI_InitStructure);
SPI_Cmd(HX711_SPI, ENABLE);
}
void HX711_Init(void)
{
HX711_GPIO_Config();
HX711_SPI_Config();
}
void HX711_Delay_us(uint32_t nus)
{
uint32_t temp;
SysTick->LOAD = 9 * nus;
SysTick->CTRL = 0x01;
SysTick->VAL = 0;
do{
temp = SysTick->CTRL;
}while ((temp & 0x01) && !(temp & (1 << 16)));
SysTick->CTRL = 0x00;
SysTick->VAL = 0;
}
void HX711_Delay_ms(uint32_t nms)
{
while (nms--)
{
HX711_Delay_us(1000);
}
}
uint8_t HX711_Read_Data(void)
{
uint8_t i;
uint8_t read = 0;
GPIO_ResetBits(HX711_SCK_GPIO_PORT, HX711_SCK_GPIO_PIN);
HX711_Delay_us(1);
for (i = 0; i < 8; i++)
{
GPIO_SetBits(HX711_SCK_GPIO_PORT, HX711_SCK_GPIO_PIN);
read <<= 1;
if (GPIO_ReadInputDataBit(HX711_DOUT_GPIO_PORT, HX711_DOUT_GPIO_PIN))
{
read++;
}
GPIO_ResetBits(HX711_SCK_GPIO_PORT, HX711_SCK_GPIO_PIN);
}
GPIO_SetBits(HX711_SCK_GPIO_PORT, HX711_SCK_GPIO_PIN);
read ^= 0x80;
GPIO_ResetBits(HX711_SCK_GPIO_PORT, HX711_SCK_GPIO_PIN);
return read;
}
int32_t HX711_Read_Weight(void)
{
uint32_t i;
uint32_t weight = 0;
uint8_t data;
for (i = 0; i < 200; i++)//采集200次
{
data = HX711_Read_Data();
weight += data;
HX711_Delay_us(1);
}
return weight - HX711_OFFSET;//减去零点偏移值
}
void HX711_Tare(uint32_t times)
{
uint32_t i;
int32_t sum = 0;
for (i = 0; i < times; i++)
{
sum += HX711_Read_Weight();
HX711_Delay_ms(10);
}
HX711_OFFSET = sum / times;
}
```
需要注意的是,在使用HX711之前,需要先进行HX711_Tare函数的操作,获得当前的零点偏移值,然后在读取数据时需要减去这个偏移值。
阅读全文