Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- uint8_t TM_DS18B20_Read(TM_OneWire_t* OneWire, uint8_t *ROM, float *destination) {
- uint16_t temperature;
- uint8_t resolution;
- int8_t digit, minus = 0;
- uint16_t decimal;
- uint8_t i = 0;
- uint8_t data[9];
- uint8_t crc;
- /* Check if device is DS18B20 */
- if (!TM_DS18B20_Is(ROM)) {
- return 0;
- }
- /* Check if line is released, if it is, then conversion is complete */
- if (!TM_OneWire_ReadBit(OneWire)) {
- /* Conversion is not finished yet */
- return 0;
- }
- /* Reset line */
- TM_OneWire_Reset(OneWire);
- /* Select ROM number */
- TM_OneWire_SelectWithPointer(OneWire, ROM);
- /* Read scratchpad command by onewire protocol */
- TM_OneWire_WriteByte(OneWire, ONEWIRE_CMD_RSCRATCHPAD);
- /* Get data */
- for (i = 0; i < 9; i++) {
- /* Read byte by byte */
- data[i] = TM_OneWire_ReadByte(OneWire);
- }
- /* Calculate CRC */
- crc = TM_OneWire_CRC8(data, 8);
- /* Check if CRC is ok */
- if (crc != data[8]) {
- /* CRC invalid */
- return 0;
- }
- /* First two bytes of scratchpad are temperature values */
- temperature = data[0] | (data[1] << 8);
- /* Reset line */
- TM_OneWire_Reset(OneWire);
- /* Check if temperature is negative */
- if (temperature & 0x8000) {
- /* Two's complement, temperature is negative */
- temperature = ~temperature + 1;
- minus = 1;
- }
- /* Get sensor resolution */
- resolution = ((data[4] & 0x60) >> 5) + 9;
- /* Store temperature integer digits and decimal digits */
- digit = temperature >> 4;
- digit |= ((temperature >> 8) & 0x7) << 4;
- /*Store decimal digits */
- switch (resolution) {
- case 9: {
- /*HERE IT GOES TO THE LOOP*/
- decimal = (float)((temperature >> 3) & 0x01);
- decimal = decimal * (float)DS18B20_DECIMAL_STEPS_9BIT;
- } break;
- case 10: {
- decimal = (temperature >> 2) & 0x03;
- decimal *= (float)DS18B20_DECIMAL_STEPS_10BIT;
- } break;
- case 11: {
- decimal = (temperature >> 1) & 0x07;
- decimal *= (float)DS18B20_DECIMAL_STEPS_11BIT;
- } break;
- case 12: {
- decimal = temperature & 0x0F;
- decimal *= (float)DS18B20_DECIMAL_STEPS_12BIT;
- } break;
- default: {
- decimal = 0xFF;
- digit = 0;
- }
- }
- /* Check for negative part */
- decimal = digit + decimal;
- if (minus) {
- decimal = 0 - decimal;
- }
- /* Set to pointer */
- *destination = decimal;
- /* Return 1, temperature valid */
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement