Using HX711 for Weight Measurement

Table of Contents

1. Introduction to HX711

2. Module Operating Principle

3. Code Implementation

4. Conclusion

01

Introduction to HX711

Kimi, start!

Using HX711 for Weight Measurement

In summary, HX711 is essentially an ADC.

02

Module Operating Principle

The internal structure diagram of HX711 is as follows:

Using HX711 for Weight Measurement

The working principle of HX711 is as follows:

Using HX711 for Weight Measurement

Inside HX711, there is a controller, and during use, the MCU pins receive data in a timed sequence.

03

Code Implementation

(1)hx711.h

#ifndef _HX711_H_
#define _HX711_H_

#include "reg52.h"
#include "intrins.h"
#define HX711_DATA  P10 // Assume connected to P1.0
#define HX711_CLK   P11 // Assume connected to P1.1

unsigned long Read_HX711(void);
unsigned long Get_weight(void);
unsigned long Get_1kg_weight(void);
void delay_ms(unsigned char ms);
void delay_us(unsigned char us);

#endif

(2)hx711.c

#include "hx711.h"
 
unsigned int weight_1kg = 0;

void delay_ms(unsigned char ms)
{
 {
  unsigned char i, j;
  _nop_();
  _nop_();
  _nop_();
  i = 11;
  j = 190;
do
  {
   while (--j);
  } while (--i);
 }while(ms--);
}


void delay_us(unsigned char us)
{
 {
  _nop_();
  _nop_();
 }while(us--);
}


unsigned long Get_1kg_weight(void) // Call this function after placing a 1 kg object on the platform
{
 weight_1kg =  Read_HX711();
return weight_1kg;
}

unsigned long Get_weight(void)
{
 unsigned int weight = 0;
 weight = Read_HX711();
 weight /= weight_1kg;
return weight;
}

unsigned long Read_HX711(void) // CLK is 25, input channel A
{
    unsigned long count;
    unsigned char i;

    HX711_CLK = 0;
    count = 0;

    while(HX711_DATA);  // Wait for DATA to go low

    for (i = 0; i < 24; i++) {
        HX711_CLK = 1;   // CLK goes high, ready to read data bit
        count = count << 1;  // Shift left by one bit to make room for the next data bit
        HX711_CLK = 0;   // CLK goes low, actually read data bit on the rising edge

        if (HX711_DATA)
            count++;
    }

    HX711_CLK = 1;     // Send an extra pulse to set the gain for the next read
    count = count ^ 0x800000; // Can convert to negative if needed
    HX711_CLK = 0;

    return (count);
}

void main(void) {
    unsigned long weight;

    // Perform any necessary initialization
    // ...

    while(1) {
        weight = Read_HX711();
        // Use the read weight value
        // ...
    }
}

First call the Get_1kg_weight function, then call the Get_weight function.

04

Conclusion

Using HX711 is quite simple, mainly focusing on the output of the measurement completion signal.

Leave a Comment