Library to read out HX711 24-Bit Analog-to-Digital Converter (ADC) for Weigh Scales by AVIA Semiconductor. Tested with K22F with SCK pint at D13 and DT pin at D12

Dependents:   SmartCrutches

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers Hx711.cpp Source File

Hx711.cpp

00001 #include "mbed.h"
00002 #include "Hx711.h"
00003 
00004 void Hx711::set_gain(uint8_t gain) {
00005     switch (gain) {
00006         case 128:       // channel A, gain factor 128
00007             gain_ = 1;
00008             break;
00009         case 64:        // channel A, gain factor 64
00010             gain_ = 3;
00011             break;
00012         case 32:        // channel B, gain factor 32
00013             gain_ = 2;
00014             break;
00015     }
00016 
00017     sck_.write(LOW);
00018     read();
00019 }
00020 
00021 uint32_t Hx711::readRaw() {
00022     // wait for the chip to become ready
00023     // TODO: this is not ideal; the programm will hang if the chip never
00024     // becomes ready...
00025     while (!is_ready());
00026 
00027     uint32_t value = 0;
00028     uint8_t data[3] = { 0 };
00029     uint8_t filler = 0x00;
00030 
00031     // pulse the clock pin 24 times to read the data
00032     data[2] = shiftInMsbFirst();
00033     data[1] = shiftInMsbFirst();
00034     data[0] = shiftInMsbFirst();
00035 
00036     // set the channel and the gain factor for the next reading using the clock pin
00037     for (unsigned int i = 0; i < gain_; i++) {
00038         sck_.write(HIGH);
00039         sck_.write(LOW);
00040     }
00041 
00042     // Datasheet indicates the value is returned as a two's complement value
00043     // Flip all the bits
00044     data[2] = ~data[2];
00045     data[1] = ~data[1];
00046     data[0] = ~data[0];
00047 
00048     // Replicate the most significant bit to pad out a 32-bit signed integer
00049     if ( data[2] & 0x80 ) {
00050         filler = 0xFF;
00051     } else if ((0x7F == data[2]) && (0xFF == data[1]) && (0xFF == data[0])) {
00052         filler = 0xFF;
00053     } else {
00054         filler = 0x00;
00055     }
00056 
00057     // Construct a 32-bit signed integer
00058     value = ( static_cast<uint32_t>(filler)  << 24
00059             | static_cast<uint32_t>(data[2]) << 16
00060             | static_cast<uint32_t>(data[1]) << 8
00061             | static_cast<uint32_t>(data[0]) );
00062 
00063     // ... and add 1
00064     return static_cast<int>(++value);
00065 }
00066 
00067 
00068 uint8_t Hx711::shiftInMsbFirst() {
00069     uint8_t value = 0;
00070 
00071     for (uint8_t i = 0; i < 8; ++i) {
00072         sck_.write(HIGH);
00073         value |= dt_.read() << (7 - i);
00074         sck_.write(LOW);
00075     }
00076     return value;
00077 }