Library for working with the HYCON HY3116/8 24-bit weigh-scales ADC series.
Diff: HY3116.cpp
- Revision:
- 0:80768ca5d5ff
- Child:
- 1:1967c3f48465
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HY3116.cpp Wed May 11 12:11:43 2016 +0000 @@ -0,0 +1,93 @@ +#include "HY3116.h" + +// Define I2C pins (SDA,SCL) +static I2C i2c(p30,p7); // nRF51-DK + +// Single-byte write helper function +void HY3116::writeByte(uint8_t address, uint8_t subAddress, uint8_t data) +{ + char data_write[2]; + data_write[0]=subAddress; // I2C sends MSB first. Namely >>|subAddress|>>|data| + data_write[1]=data; + i2c.write(address,data_write,2,0); // i2c.write(int address, char* data, int length, bool repeated=false); +} + +// Function to send the reset command +void HY3116::resetChip() +{ + char data_write[1]; + data_write[0]=RESET; + i2c.write(HY3116_ADDRESS,data_write,1,0); // i2c.write(int address, char* data, int length, bool repeated=false); +} + +// Multi-byte read helper function +void HY3116::readBytes(uint8_t address, uint8_t subAddress, uint8_t byteNum, uint8_t* dest, bool alreadyRead) +{ + char data[14],data_write[1]; + data_write[0]=subAddress; + if (!alreadyRead) { + i2c.write(address,data_write,1,1); + } + i2c.read(address,data,byteNum,0); + for(int i=0;i<byteNum;i++) // equate the addresses + dest[i]=data[i]; +} + +// Dedicated ADC-output read, check & format function +int32_t HY3116::readAdc(bool alreadyRead) +{ + uint8_t rawData[3]; + bool newReading = 0; + int32_t adcReading = 0; + + readBytes(HY3116_ADDRESS, ADO, 3, &rawData[0], alreadyRead); + + if (rawData[2] & 0b00000001) { + newReading = 1; + } + else { + newReading = 0; + } + + adcReading += rawData[0] << 15; + adcReading += rawData[1] << 7; + adcReading += rawData[2] >> 1; + + // Account for twos complement polarity + if (rawData[0] & 0b10000000) { + adcReading ^= 0xFF800000; + } + + return adcReading; +} + +// Initialise the HY3116 with the following config.: +// +void HY3116::init() +{ + // Set the I2C clock frequency + i2c.frequency(100000); + + // Set-up the SYS register + writeByte(HY3116_ADDRESS, SYS, 0b00011100); // Enable the ADC & LDO + wait_ms(100); // wait 100 ms to stabilize + + // Set-up the ADC1 register + writeByte(HY3116_ADDRESS, ADC1, 0b00001000); // Set inputs to AIN1 & AIN2 + wait_ms(100); // wait 100 ms to stabilize + + // Set-up the ADC2 register + writeByte(HY3116_ADDRESS, ADC2, 0b01010000); // Set pos. ref. voltage to VDDA, neg. ref. to VSSA, DC offset to 0VRef + wait_ms(100); // wait 100 ms to stabilize + + // Set-up the ADC3 register + writeByte(HY3116_ADDRESS, ADC3, 0b01111100); // Set to int. osc. 327kHz, full ref. range, PGA to 32x, pre-amp to 1x + wait_ms(100); // wait 100 ms to stabilize + + // Set-up the ADC4 register + writeByte(HY3116_ADDRESS, ADC4, 0b01011110); // Set LDO to 3.0V, REFO = 1.2V, conv. rate = 327kHz, SPS = 40 + wait_ms(100); // wait 100 ms to stabilize + + resetChip(); + wait_ms(500); +} \ No newline at end of file