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: mbed-os-example-ble-WEIGHT-public
Hx711.cpp
- Committer:
- Eugene0469
- Date:
- 2019-06-26
- Revision:
- 6:8e564e9cde8d
- Parent:
- 5:16627e96c8de
File content as of revision 6:8e564e9cde8d:
#include "mbed.h" #include "Hx711.h" void Hx711::set_gain(uint8_t gain) { switch (gain) { case 128: // channel A, gain factor 128 gain_ = 1; break; case 64: // channel A, gain factor 64 gain_ = 3; break; case 32: // channel B, gain factor 32 gain_ = 2; break; } sck_.write(LOW); read(); } int32_t Hx711::readRaw() { // wait for the chip to become ready // TODO: this is not ideal; the programm will hang if the chip never // becomes ready... while (!is_ready()); printf("Chip is ready.\n"); uint32_t value = 0; uint8_t data[3] = { 0 }; uint8_t filler = 0x00; // pulse the clock pin 24 times to read the data data[2] = shiftInMsbFirst(); data[1] = shiftInMsbFirst(); data[0] = shiftInMsbFirst(); printf("Data has been read.\n"); // set the channel and the gain factor for the next reading using the clock pin for (unsigned int i = 0; i < gain_; i++) { sck_.write(HIGH); sck_.write(LOW); } // Datasheet indicates the value is returned as a two's complement value // Flip all the bits data[2] = ~data[2]; data[1] = ~data[1]; data[0] = ~data[0]; // printf("Data[2]: %d\n",data[2]); // printf("Data[1]: %d\n",data[1]); // printf("Data[0]: %d\n",data[0]); // Replicate the most significant bit to pad out a 32-bit signed integer if ( data[2] & 0x80 ) { filler = 0xFF; } else if ((0x7F == data[2]) && (0xFF == data[1]) && (0xFF == data[0])) { filler = 0xFF; } else { filler = 0x00; } // printf("Filler: %d\n",filler); // Construct a 32-bit signed integer value = ( static_cast<uint32_t>(filler) << 24 | static_cast<uint32_t>(data[2]) << 16 | static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]) ); // printf("32-bit signed integer has been constructed:%d\n",value); // ... and add 1. Thiscompletes the conversion of the 2's complement value. value = ++value; // printf("32-bit after adding 1: %d\n",value); value = static_cast<int32_t>(value); printf("32-bit after typecasting: %d\n",value); return value; } uint8_t Hx711::shiftInMsbFirst() { uint8_t value = 0; for (uint8_t i = 0; i < 8; ++i) { sck_.write(HIGH); value |= dt_.read() << (7 - i); sck_.write(LOW); } // printf("8-bit raw value: %d\n",value); return value; }