raspikeyer/src/morse.cpp
2024-02-29 09:27:59 +01:00

68 lines
No EOL
1.4 KiB
C++

#include <cstdio>
#include <cstring>
#include "pico/stdio.h"
#include "morse.h"
MorseCode::MorseCode() { buildMap(); }
bool MorseCode::charToMorse(const unsigned char ch, char *morseSymbols)
{
size_t index {0};
if (ch != ' ' && morseMap[ch] == nullptr) {
return false;
}
if (ch == ' ') {
morseSymbols[index++] = 'w';
} else {
for (unsigned int i = 0; i < strlen(morseMap[ch]); i++) {
char m = morseMap[ch][i];
morseSymbols[index++] = m;
if (i < strlen(morseMap[ch]) - 1) {
morseSymbols[index++] = 'i';
}
}
morseSymbols[index++] = 'c';
}
morseSymbols[index] = '\0';
return true;
}
void MorseCode::sendCharacter(const char ch)
{
char morseSymbols[32] {0};
if (!charToMorse(ch, morseSymbols)) {
return;
}
for (unsigned int i = 0; i < strlen(morseSymbols); i++) {
printf("%c", morseSymbols[i]);
}
}
void MorseCode::buildMap()
{
for (size_t i = 0; i < 256; i++) {
if (i == '\"')
morseMap[i] = morseTable[0];
else if (i == '$')
morseMap[i] = morseTable[1];
else if (i == '\'')
morseMap[i] = morseTable[2];
else if (i == '(')
morseMap[i] = morseTable[3];
else if (i == ')')
morseMap[i] = morseTable[4];
else if (i >= '+' && i <= ']')
morseMap[i] = morseTable[i - 0x26];
}
}