vanderbiltrobotics / loadcell

0 stars 0 forks source link

Refactor read() #6

Open AWatk opened 6 years ago

AWatk commented 6 years ago

https://github.com/vanderbiltrobotics/loadcell/blob/a466c2e6b498ede84c17b5829522f91719adbeb6/HX711.cpp#L53-L81

This can change a lot to be optimized.

Don't really need to have three 8bit data bytes that get set with another function called shiftIn().

something like this should work and make it a bit more compact and readable

int32_t value = 0 //create the value that will eventually be returned and do everything with it

//read in 24 bits MSB first
for(int i = 0; i< 24; ++i){
  rc_gpio_set_value_mmap(pd_sck_, HIGH);
  usleep(5); //may not be necessary, used to even out the clock pulses
  value |= rc_gpio_get_value_mmap(dout_) << (24 -i);
  rc_gpio_set_value_mmap(pd_sck_, LOW);
  usleep(5); //may not be necessary, used to even out the clock pulses
}

// set the next read's mode
for(int i = 0; i < (int)mode_, ++i){
  rc_gpio_set_value_mmap(pd_sck_, HIGH);
  usleep(5); //may not be necessary, used to even out the clock pulses 
  rc_gpio_set_value_mmap(pd_sck_, LOW);
  usleep(5); //may not be necessary, used to even out the clock pulses
}

//pad the most significant 8 bits of value  with appropriate filler (due to 2's complement)
if(value & 0x00800000){
 value |= 0xFF000000
}
return value