From f1d78e488e3e090cb3d05bf6e92afeaf85dc490d Mon Sep 17 00:00:00 2001 From: ajs123 Date: Tue, 3 Aug 2021 20:09:34 -0400 Subject: [PATCH] Added readCPUTemperature() --- cores/nRF5/wiring.c | 41 +++++++++++++++++++++++++++++++++++++++++ cores/nRF5/wiring.h | 6 ++++++ 2 files changed, 47 insertions(+) diff --git a/cores/nRF5/wiring.c b/cores/nRF5/wiring.c index 134ee539..5fa08608 100644 --- a/cores/nRF5/wiring.c +++ b/cores/nRF5/wiring.c @@ -143,3 +143,44 @@ void systemOff(uint32_t pin, uint8_t wake_logic) NRF_POWER->SYSTEMOFF = 1; } } + + +float readCPUTemperature() +{ + // These are defined simply to make the ensuing code easier to read. Ready and triggers are 0x01, and not ready is 0x00. + // Many other library functions use a literal 0x00 to reset flags and a literal 0x01 for triggers, and test "done" + // flags for nonzero. In this function, we used the defined constants. Using 0x00 and 0x01 would probably be fine + // because they're unlikely to ever change. + const uint32_t temp_ready = ( (TEMP_EVENTS_DATARDY_EVENTS_DATARDY_Generated << TEMP_EVENTS_DATARDY_EVENTS_DATARDY_Pos) + && TEMP_EVENTS_DATARDY_EVENTS_DATARDY_Msk ); + + const uint32_t temp_not_ready = ( (TEMP_EVENTS_DATARDY_EVENTS_DATARDY_NotGenerated << TEMP_EVENTS_DATARDY_EVENTS_DATARDY_Pos) + && TEMP_EVENTS_DATARDY_EVENTS_DATARDY_Msk ); + + const uint32_t temp_trigger = ( (TEMP_TASKS_START_TASKS_START_Trigger << TEMP_TASKS_STOP_TASKS_STOP_Pos) + && TEMP_TASKS_START_TASKS_START_Msk ); + + const uint32_t temp_stop = ( (TEMP_TASKS_STOP_TASKS_STOP_Trigger << TEMP_TASKS_STOP_TASKS_STOP_Pos) + && TEMP_TASKS_STOP_TASKS_STOP_Msk ); + + uint8_t en; + int32_t temp; + (void) sd_softdevice_is_enabled(&en); + if (en) + { + sd_temp_get(&temp); + } + else + { + NRF_TEMP->EVENTS_DATARDY = temp_not_ready; // Only needed in case another function is also looking at this event flag + NRF_TEMP->TASKS_START = temp_trigger; + + bool done = false; + while (NRF_TEMP->EVENTS_DATARDY != temp_ready); + temp = NRF_TEMP->TEMP; // Per anomaly 29 (unclear whether still applicable), TASKS_STOP will clear the TEMP register. + + NRF_TEMP->TASKS_STOP = temp_stop; // Per anomaly 30 (unclear whether still applicable), the temp peripheral needs to be shut down + NRF_TEMP->EVENTS_DATARDY = temp_not_ready; + } + return temp / 4.0F; +} diff --git a/cores/nRF5/wiring.h b/cores/nRF5/wiring.h index a557f547..279abfcf 100644 --- a/cores/nRF5/wiring.h +++ b/cores/nRF5/wiring.h @@ -42,6 +42,12 @@ static inline bool isInISR(void) return (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0 ; } +/* + * \brief Reads the on-chip temperature sensor, returning the temperature in degrees C + * with a resolution of 0.25 degrees. +*/ +float readCPUTemperature(); + #ifdef __cplusplus } #endif