577
// Start DS18B20 communication and check response unsigned char ds18b20_start(void) { unsigned char response; DS18B20_TRIS = 0; // Set as output DS18B20_PIN = 0; // Send reset pulse __delay_us(500); // Hold for 500us DS18B20_TRIS = 1; // Set as input __delay_us(100); // Wait for response response = DS18B20_PIN; // Read response __delay_us(400); // Wait 400us return !response; // Return TRUE if sensor detected } // Write a single bit to DS18B20 void ds18b20_write_bit(unsigned char bit) { DS18B20_TRIS = 0; // Set as output DS18B20_PIN = 0; // Pull low __delay_us(2); if(bit) DS18B20_PIN = 1; // Send bit __delay_us(80); // Hold for 80us DS18B20_TRIS = 1; // Release line __delay_us(2); } // Write a byte to DS18B20 void ds18b20_write_byte(unsigned char byte) { for(unsigned char i = 0; i < 8; i++) { ds18b20_write_bit(byte & 0x01); byte >>= 1; } } // Read a single bit from DS18B20 unsigned char ds18b20_read_bit(void) { unsigned char bit; DS18B20_TRIS = 0; // Set as output DS18B20_PIN = 0; // Pull low __delay_us(2); DS18B20_TRIS = 1; // Release line __delay_us(5); // Wait 5us bit = DS18B20_PIN; // Read bit __delay_us(100); // Wait 100us return bit; } // Read a byte from DS18B20 unsigned char ds18b20_read_byte(void) { unsigned char byte = 0; for(unsigned char i = 0; i < 8; i++) { byte >>= 1; if(ds18b20_read_bit()) byte |= 0x80; } return byte; } // Read temperature from DS18B20 unsigned char ds18b20_read(signed int *raw_temp_value) { unsigned char temp_l, temp_h; if(!ds18b20_start()) return 0; ds18b20_write_byte(0xCC); // Skip ROM command ds18b20_write_byte(0x44); // Start conversion while(!ds18b20_read_byte()); // Wait for conversion if(!ds18b20_start()) return 0; ds18b20_write_byte(0xCC); // Skip ROM command ds18b20_write_byte(0xBE); // Read scratchpad temp_l = ds18b20_read_byte(); // LSB temp_h = ds18b20_read_byte(); // MSB *raw_temp_value = (temp_h << 8) | temp_l; return 1; }