From 1a0264a5259193e977101533342a6684d226626e Mon Sep 17 00:00:00 2001 From: HampusM Date: Tue, 17 May 2022 12:53:14 +0200 Subject: refactor(minion): improve reading temperature sensor --- minion/src/temperature.cpp | 22 +++++++++++++++------- minion/src/temperature.hpp | 7 ++++++- 2 files changed, 21 insertions(+), 8 deletions(-) (limited to 'minion') diff --git a/minion/src/temperature.cpp b/minion/src/temperature.cpp index 1231e24..46c6300 100644 --- a/minion/src/temperature.cpp +++ b/minion/src/temperature.cpp @@ -22,13 +22,15 @@ auto TemperatureSensor::read_temperature() noexcept -> TemperatureSensorStatus // The sensor sends a LOW signal and keeps it for 80us if (!_wait_read(LOW, TemperatureSensorTiming::RESPONSE_SIGNAL_TIME_MICROS)) { - return TemperatureSensorStatus::TIMEOUT; + _restore_pin(); + return TemperatureSensorStatus::LOW_RESPONSE_SIGNAL_TIMEOUT; } // The sensor sends a HIGH signal and keeps it for 80us if (!_wait_read(HIGH, TemperatureSensorTiming::RESPONSE_SIGNAL_TIME_MICROS)) { - return TemperatureSensorStatus::TIMEOUT; + _restore_pin(); + return TemperatureSensorStatus::HIGH_RESPONSE_SIGNAL_TIMEOUT; } uint8_t data_bytes[TEMPERATURE_SENSOR_RESPONSE_DATA_BYTE_CNT] = { 0U, @@ -50,14 +52,16 @@ auto TemperatureSensor::read_temperature() noexcept -> TemperatureSensorStatus TemperatureSensorTiming::START_TO_TRANSMIT_SIGNAL_TIME_MICROS + 5U )) { - return TemperatureSensorStatus::TIMEOUT; + _restore_pin(); + return TemperatureSensorStatus::START_TO_TRANSMIT_SIGNAL_TIMEOUT; } const auto start_time = micros(); if (!_wait_read(HIGH, TemperatureSensorTiming::DATA_TRANSMIT_TIMEOUT_MICROS)) { - return TemperatureSensorStatus::TIMEOUT; + _restore_pin(); + return TemperatureSensorStatus::DATA_TRANSMIT_TIMEOUT; } // A voltage length greater than 40 means the bit is a 1 @@ -79,9 +83,7 @@ auto TemperatureSensor::read_temperature() noexcept -> TemperatureSensorStatus bit_index--; } - // Restore pin to initial state - pinMode(_pin, OUTPUT); - digitalWrite(_pin, HIGH); + _restore_pin(); _temperature = data_bytes[2]; @@ -115,3 +117,9 @@ auto TemperatureSensor::_wait_read(uint8_t level, size_t timeout_micros) noexcep return true; } + +void TemperatureSensor::_restore_pin() noexcept +{ + pinMode(_pin, OUTPUT); + digitalWrite(_pin, HIGH); +} diff --git a/minion/src/temperature.hpp b/minion/src/temperature.hpp index dcc213c..a4eea71 100644 --- a/minion/src/temperature.hpp +++ b/minion/src/temperature.hpp @@ -20,7 +20,10 @@ constexpr auto BITS_IN_BYTE = 8U; enum class TemperatureSensorStatus { OK, - TIMEOUT, + LOW_RESPONSE_SIGNAL_TIMEOUT, + HIGH_RESPONSE_SIGNAL_TIMEOUT, + START_TO_TRANSMIT_SIGNAL_TIMEOUT, + DATA_TRANSMIT_TIMEOUT, CHECKSUM_ERROR }; @@ -39,4 +42,6 @@ private: uint8_t _temperature{}; auto _wait_read(uint8_t level, size_t timeout_micros) noexcept -> bool; + + void _restore_pin() noexcept; }; -- cgit v1.2.3-18-g5258