#include "ds18b20.h" #include #define OW_DDR DDRB #define OW_PORT PORTB #define OW_PIN PINB #define OW_BIT PB0 static void ow_drive_low(void) { OW_DDR |= (1 << OW_BIT); OW_PORT &= ~(1 << OW_BIT); } static void ow_release(void) { OW_DDR &= ~(1 << OW_BIT); OW_PORT |= (1 << OW_BIT); } static uint8_t ow_read(void) { return (OW_PIN & (1 << OW_BIT)) ? 1 : 0; } void ds18b20_init(void) { OW_DDR &= ~(1 << OW_BIT); OW_PORT |= (1 << OW_BIT); } uint8_t ow_reset(void) { uint8_t presence; ow_drive_low(); _delay_us(480); ow_release(); _delay_us(70); presence = !ow_read(); _delay_us(410); return presence; } void ow_write_bit(uint8_t bit) { ow_drive_low(); if (bit) { _delay_us(6); ow_release(); _delay_us(64); } else { _delay_us(60); ow_release(); _delay_us(10); } } uint8_t ow_read_bit(void) { uint8_t bit; ow_drive_low(); _delay_us(6); ow_release(); _delay_us(9); bit = ow_read(); _delay_us(55); return bit; } void ow_write_byte(uint8_t byte) { for (uint8_t i = 0; i < 8; i++) { ow_write_bit(byte & 0x01); byte >>= 1; } } uint8_t ow_read_byte(void) { uint8_t byte = 0; for (uint8_t i = 0; i < 8; i++) { byte >>= 1; if (ow_read_bit()) byte |= 0x80; } return byte; } int16_t ds18b20_read_temp(void) { if (!ow_reset()) return -1000; ow_write_byte(0xCC); // Skip ROM ow_write_byte(0x44); // Convert T for (uint16_t i = 0; i < 750; i++) { _delay_ms(1); if (ow_read()) break; } if (!ow_reset()) return -1000; ow_write_byte(0xCC); // Skip ROM ow_write_byte(0xBE); // Read Scratchpad uint8_t temp_l = ow_read_byte(); uint8_t temp_h = ow_read_byte(); return (temp_h << 8) | temp_l; }