此内容为逐步分析示例代码并写入注释笔记
hx711完整实例代码
#include "hx711.h"long HX711_Buffer = 0;
long Weight_Maopi = 0,Weight_Shiwu = 0;#define GapValue 430//****************************************************
//初始化HX711
//****************************************************
void Init_Hx711()
{pinMode(HX711_SCK, OUTPUT); //SCK脚设为输出pinMode(HX711_DT, INPUT);//DT脚设为输入
}//****************************************************
//获取毛皮重量
//****************************************************
void Get_Maopi()
{Weight_Maopi = HX711_Read();
} //****************************************************
//称重
//****************************************************
long Get_Weight()
{HX711_Buffer = HX711_Read();Weight_Shiwu = HX711_Buffer;Weight_Shiwu = Weight_Shiwu - Weight_Maopi; //获取实物的AD采样数值。Weight_Shiwu = (long)((float)Weight_Shiwu/GapValue); return Weight_Shiwu;
}//****************************************************
//读取HX711
//****************************************************
unsigned long HX711_Read(void) //输入通道A增益128
{unsigned long count; unsigned char i;bool Flag = 0;digitalWrite(HX711_DT, HIGH);//DT设为上拉输入,无输入时为高电平delayMicroseconds(1);//停1微秒digitalWrite(HX711_SCK, LOW);//SCK低电平输出,初始化delayMicroseconds(1);//停1微秒count=0; while(digitalRead(HX711_DT)); //DT为1时AD未准备完成,死循环for(i=0;i<24;i++)//读取24位数据,从高到低{ digitalWrite(HX711_SCK, HIGH); //一次脉冲delayMicroseconds(1);count=count<<1; //左移读取上一次数据digitalWrite(HX711_SCK, LOW); //脉冲完成delayMicroseconds(1);if(digitalRead(HX711_DT))//写入这次脉冲数据count++; } digitalWrite(HX711_SCK, HIGH); count ^= 0x800000;//最高位置1delayMicroseconds(1);digitalWrite(HX711_SCK, LOW); delayMicroseconds(1);return(count);
}