Skip to content

Commit

Permalink
Implement serial control of velocity and throttle (#39)
Browse files Browse the repository at this point in the history
* Implement serial control of velocity and throttle

* Update naming/comments and refactor `run_inverter`

* Use smaller mutex.h include

---------

Co-authored-by: Taesung Hwang <[email protected]>
  • Loading branch information
samderanova and taesungh authored May 30, 2024
1 parent ec4e200 commit 4b5934c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pico_add_extra_outputs(${PROJECT_NAME})
# Link to pico_stdlib (gpio, time, etc. functions)
target_link_libraries(${PROJECT_NAME}
pico_stdlib
pico_multicore
)

# Enable usb output, disable uart output
Expand Down
51 changes: 44 additions & 7 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
#include <vector>

#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "pico/mutex.h"
#include "hardware/gpio.h"
#include "tusb.h"

Expand All @@ -18,6 +20,12 @@ const float OFFSET = 0.0411;

constexpr bool TEST_CIRCUIT = false;

// Value will be changed by other core, so prevent compiler from optimizing as constant
volatile static LimControlMessage lcm{ 0, 1 };
// Allow only one core at a time to access lcm
static mutex lcmMutex;


void initialize_pins()
{
const std::vector<unsigned> pins = TEST_CIRCUIT ?
Expand Down Expand Up @@ -103,6 +111,37 @@ int frequency_to_samples(float frequency)
return OPERATING_FREQUENCY / frequency - OFFSET;
}

// Secondary program to run on core 1
void monitor_serial()
{
while (true)
{
LimControlMessage message = read_control_message();

mutex_enter_blocking(&lcmMutex);
lcm.velocity = message.velocity;
lcm.throttle = message.throttle;
mutex_exit(&lcmMutex);
}
}

// Main program to run on core 0
void run_inverter()
{
while (true)
{
mutex_enter_blocking(&lcmMutex);
float frequency = calculate_frequency(lcm.velocity, lcm.throttle);
mutex_exit(&lcmMutex);

// TODO: disregard zero frequency

int N = frequency_to_samples(frequency);
// TODO: amplitude ratio
run_inverter_cycle(N, 1);
}
}

int main()
{
stdio_init_all();
Expand All @@ -113,13 +152,11 @@ int main()

initialize_pins();

while (true)
{
LimControlMessage message = read_control_message();
float frequency = calculate_frequency(message.velocity, message.throttle);
int N = frequency_to_samples(frequency);
run_inverter_cycle(N, 1);
}
mutex_init(&lcmMutex);

// Run inverter on core 0 while updating control parameters on core 1
multicore_launch_core1(monitor_serial);
run_inverter();

return 0;
}

0 comments on commit 4b5934c

Please sign in to comment.