user3817250
user3817250

Reputation: 1043

Converting error code to Morse Code in c

I'm trying to write a program that will (eventually) blink an LED to indicate an error code in morse code.

Right now I'm stuck (mostly) on figuring out how I can read the error code left to right.

At the moment I'm just trying to get the base of the program down. Call the function with an error code -> print the Morse code to the console.

Here is what I have:

#define LED_DIT '.'
#define LED_DAH '-'
#define LED_INTER_GAP "" /* Delays within a letter */
#define LED_SHORT_GAP " " /* Delay between letters */
#define LED_MEDIUM_GAP "\n" /* Delay between words */

#include <stdio.h>
#include <stdint.h>

char morseDigits[10][5] = {
    {LED_DAH, LED_DAH, LED_DAH, LED_DAH, LED_DAH}, // 0
    {LED_DIT, LED_DAH, LED_DAH, LED_DAH, LED_DAH}, // 1
    {LED_DIT, LED_DIT, LED_DAH, LED_DAH, LED_DAH}, // 2
    {LED_DIT, LED_DIT, LED_DIT, LED_DAH, LED_DAH}, // 3
    {LED_DIT, LED_DIT, LED_DIT, LED_DIT, LED_DAH}, // 4
    {LED_DIT, LED_DIT, LED_DIT, LED_DIT, LED_DIT}, // 5
    {LED_DAH, LED_DIT, LED_DIT, LED_DIT, LED_DIT}, // 6
    {LED_DAH, LED_DAH, LED_DIT, LED_DIT, LED_DIT}, // 7
    {LED_DAH, LED_DAH, LED_DAH, LED_DIT, LED_DIT}, // 8
    {LED_DAH, LED_DAH, LED_DAH, LED_DAH, LED_DIT} // 9
};

void LEDMorseDigit(uint8_t digit) {
    uint8_t i;

    for(i=0; i<5; i++) {
        printf(morseDigits[digit][i]);
        printf(LED_INTER_GAP);
    }
}

void LEDMorseCode(uint8_t errorCode) {

    uint8_t i = 0;

    // Play error sequence of digits, left to right
    while(*(errorCode + i)) {
        LEDMorseDigit(errorCode[i++]);
        printf(LED_SHORT_GAP);
    }
    printf(LED_MEDIUM_GAP);

}

int main(void) {
    LEDMorseCode(1);
    LEDMorseCode(23);
    LEDMorseCode(123);

    return 0;
}

The while(*(errorCode + i)) {...} is something I took from an example of reading a char* left to right. I'd really like to do this without creating new variables to hold the data.

I've considered just reading the number from right to left with modulo/division and calling the function with a reversed error code but I'd prefer not to as this would potentially lead to some confusion.

So how can I make a function that takes a u-int value and grabs each digit from left to right?

Am I better off just passing the value as a string and converting each char to an int?

Upvotes: 1

Views: 182

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126243

You need to convert the integer into a sequence of digits. You can do that with a simple recursive div/mod loop:

void LEDMorseCode(unsigned errorCode) {
    if (unsigned r = errorCode/10) {
        LEDMorseCode(r);
        printf(LED_SHORT_GAP); }
    LEDMorseDigit(errCode % 10);
}

or you can convert the number to an ASCII string with sprintf, and then emit those digits.

Upvotes: 1

Related Questions