raspikeyer/src/keyer.cpp

103 lines
2.3 KiB
C++
Raw Normal View History

2024-02-10 23:51:55 +01:00
#include <stdio.h>
#include "pico/stdlib.h"
2024-02-09 12:20:30 +01:00
#include "keyer.h"
2024-02-12 13:48:58 +01:00
extern const uint LED_PIN;
2024-02-10 23:51:55 +01:00
extern const uint LEFT_PADDLE_PIN;
2024-02-12 13:48:58 +01:00
extern const uint RIGHT_PADDLE_PIN;
2024-02-10 23:51:55 +01:00
bool left_paddle_pressed()
{
2024-02-11 15:45:12 +01:00
if (!gpio_get(LEFT_PADDLE_PIN))
2024-02-10 23:51:55 +01:00
{
return true;
}
return false;
}
2024-02-12 13:48:58 +01:00
bool right_paddle_pressed()
{
if (!gpio_get(RIGHT_PADDLE_PIN))
{
return true;
}
return false;
}
uint64_t calcElementDurationUs(uint8_t wpm)
{
uint64_t duration = static_cast<uint64_t>(1.2 / static_cast<uint64_t>(wpm) * 1000 * 1000);
return duration;
}
Keyer::Keyer(uint8_t wpm) : m_wpm(wpm)
{
m_elementDuration = calcElementDurationUs(m_wpm);
}
2024-02-09 12:20:30 +01:00
void Keyer::run()
{
2024-02-12 13:48:58 +01:00
auto timestamp = get_absolute_time();
2024-02-09 12:20:30 +01:00
switch (state)
{
2024-02-10 23:51:55 +01:00
case State::Wait:
2024-02-12 13:48:58 +01:00
if (left_paddle_pressed()) {
2024-02-11 16:26:55 +01:00
state = State::Dit;
2024-02-12 13:48:58 +01:00
} else if (right_paddle_pressed()) {
state = State::Dah;
}
2024-02-10 23:51:55 +01:00
break;
2024-02-11 16:26:55 +01:00
case State::Dit:
2024-02-12 13:48:58 +01:00
if (!m_currentlyKeying)
{
m_currentlyKeying = true;
m_keying_until = make_timeout_time_us(m_elementDuration);
gpio_put(LED_PIN, 1);
}
2024-02-11 15:45:12 +01:00
else
2024-02-11 16:26:55 +01:00
{
2024-02-12 13:48:58 +01:00
if (absolute_time_diff_us(timestamp, m_keying_until) <= 0)
{
m_currentlyKeying = false;
gpio_put(LED_PIN, 0);
m_previousState = State::Dit;
2024-02-11 16:26:55 +01:00
state = State::InterCharSpace;
2024-02-12 13:48:58 +01:00
}
2024-02-11 16:26:55 +01:00
}
break;
2024-02-12 13:48:58 +01:00
case State::Dah:
if(!m_currentlyKeying) {
m_currentlyKeying = true;
m_keying_until = make_timeout_time_us(m_elementDuration * 3);
gpio_put(LED_PIN, 1);
} else {
if (absolute_time_diff_us(timestamp, m_keying_until) <= 0)
{
m_currentlyKeying = false;
gpio_put(LED_PIN, 0);
m_previousState = State::Dah;
state = State::InterCharSpace;
}
2024-02-11 15:45:12 +01:00
2024-02-12 13:48:58 +01:00
}
break;
2024-02-11 15:45:12 +01:00
case State::InterCharSpace:
2024-02-12 13:48:58 +01:00
if (m_previousState != State::InterCharSpace)
{
m_pausing_until = make_timeout_time_us(m_elementDuration);
m_previousState = State::InterCharSpace;
}
2024-02-11 15:45:12 +01:00
2024-02-12 13:48:58 +01:00
if(absolute_time_diff_us(timestamp, m_pausing_until) <= 0) {
2024-02-11 15:45:12 +01:00
state = State::Wait;
2024-02-12 13:48:58 +01:00
}
2024-02-09 12:20:30 +01:00
break;
default:
break;
}
}