From 8a0b73cf3fad9e4c3face4d670f44315eb2154ec Mon Sep 17 00:00:00 2001 From: Sam Der Date: Thu, 30 May 2024 23:25:50 -0700 Subject: [PATCH] Add expiration time code --- include/pod_communication.hpp | 3 +++ src/main.cpp | 18 +++++++++++++----- src/pod_communication.cpp | 5 +---- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/include/pod_communication.hpp b/include/pod_communication.hpp index 5da773b..01d23c8 100644 --- a/include/pod_communication.hpp +++ b/include/pod_communication.hpp @@ -1,10 +1,13 @@ #ifndef POD_COMMUNICATION_HPP #define POD_COMMUNICATION_HPP +#include "pico/time.h" + struct LimControlMessage { float velocity; float throttle; + absolute_time_t messageTime; }; LimControlMessage read_control_message(); diff --git a/src/main.cpp b/src/main.cpp index 958df76..4b1f0f5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -11,8 +11,10 @@ const float OPERATING_FREQUENCY = 45552.3; const float OFFSET = 0.0411; -// Value will be changed by other core, so prevent compiler from optimizing as constant -volatile static LimControlMessage lcm{ 0, 1 }; +const unsigned EXPIRATION_TIME = 28; // milliseconds + +// Value may need to be volatile? +static LimControlMessage lcm{ 0, 1, get_absolute_time() }; // Allow only one core at a time to access lcm static mutex lcmMutex; @@ -71,8 +73,7 @@ void monitor_serial() LimControlMessage message = read_control_message(); mutex_enter_blocking(&lcmMutex); - lcm.velocity = message.velocity; - lcm.throttle = message.throttle; + lcm = message; mutex_exit(&lcmMutex); } } @@ -83,7 +84,14 @@ void run_inverter() while (true) { mutex_enter_blocking(&lcmMutex); - float frequency = calculate_frequency(lcm.velocity, lcm.throttle); + + // Calculate time difference in microseconds and check if the difference is + // greater than the expiration time. If so, set frequency to 0. Otherwise, + // set frequency to the data received. + int64_t timeDiff = absolute_time_diff_us(lcm.messageTime, get_absolute_time()); + bool hasExpired = timeDiff > EXPIRATION_TIME * 1000; + float frequency = hasExpired ? 0 : calculate_frequency(lcm.velocity, lcm.throttle); + mutex_exit(&lcmMutex); // Set pins to low if frequency is zero diff --git a/src/pod_communication.cpp b/src/pod_communication.cpp index fbf1076..410af3d 100644 --- a/src/pod_communication.cpp +++ b/src/pod_communication.cpp @@ -7,8 +7,5 @@ LimControlMessage read_control_message() float throttle; std::cin >> velocity >> throttle; - std::cout << "Received velocity: " << velocity << std::endl; - std::cout << "Received throttle: " << throttle << std::endl; - - return { velocity, throttle }; + return { velocity, throttle, get_absolute_time() }; }