Embedded C Code Design Review

A detailed analysis of `morse_test.c` for Raspberry Pi Zero

Source Code (`morse_test.c`)


#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pigpio.h>
#include <ctype.h> // For toupper()

// Pin definitions (BCM numbering)
#define BUZZER_PIN 23
#define GREEN_LED_PIN 22

// Morse code timing and frequency
#define TONE_FREQUENCY 700   // Hz
#define TIME_UNIT_S 0.100 // Base time unit (dot duration) in seconds
#define DASH_DURATION_S (3 * TIME_UNIT_S)
#define ELEMENT_PAUSE_S TIME_UNIT_S       // Pause between dots/dashes in a letter
#define CHARACTER_PAUSE_S (3 * TIME_UNIT_S) // Pause between letters in a word
#define WORD_PAUSE_S (7 * TIME_UNIT_S) // Pause between words

// Global flag to handle program termination
volatile sig_atomic_t running = 1;

// --- Morse Code Data Structures ---
typedef struct {
    char character;
    const char* pattern;
} MorseMapping;

// Lookup table for International Morse Code
MorseMapping morse_table[] = {
    {'A', ".-"},   {'B', "-..."}, {'C', "-.-."}, {'D', "-.."},  {'E', "."},
    {'F', "..-."}, {'G', "--."},  {'H', "...."}, {'I', ".."},   {'J', ".---"},
    {'K', "-.-"},  {'L', ".-.."}, {'M', "--"},   {'N', "-."},   {'O', "---"},
    {'P', ".--."}, {'Q', "--.-"}, {'R', ".-."},  {'S', "..."},  {'T', "-"},
    {'U', "..-"},  {'V', "...-"}, {'W', ".--"},  {'X', "-..-"}, {'Y', "-.--"},
    {'Z', "--.."}, {'1', ".----"},{'2', "..---"},{'3', "...--"},{'4', "....-"},
    {'5', "....."},{'6', "-...."},{'7', "--..."},{'8', "---.."},{'9', "----."},
    {'0', "-----"}
};
int morse_table_size = sizeof(morse_table) / sizeof(morse_table[0]);

// Function to handle Ctrl+C (SIGINT)
void cleanup_and_exit(int signum) {
    printf("\nCaught signal %d, cleaning up and exiting...\n", signum);
    running = 0; // Signal the main loop to exit
}

// Function to clean up GPIO resources
void cleanup_gpio() {
    // The pigpio functions are safe to call here. In this program's logic,
    // this function is only called after a successful gpioInitialise().
    gpioPWM(BUZZER_PIN, 0);
    gpioWrite(GREEN_LED_PIN, 0);
    gpioTerminate();
    printf("GPIO cleaned up.\n");
}

// Function to play a tone
void play_tone(int frequency, double duration) {
    if (!running) return;
    gpioSetPWMfrequency(BUZZER_PIN, frequency);
    gpioPWM(BUZZER_PIN, 128); // 50% duty cycle for a clear tone
    time_sleep(duration);
}

// Function for silence
void play_silence(double duration) {
    if (!running) return;
    gpioPWM(BUZZER_PIN, 0); // Turn off buzzer
    time_sleep(duration);
}

// --- Morse Code Engine ---

// Plays the Morse pattern for a single character
void play_character(char c) {
    // Find the character in the lookup table (case-insensitive)
    for (int i = 0; i < morse_table_size; i++) {
        if (morse_table[i].character == toupper(c)) {
            const char* pattern = morse_table[i].pattern;
            printf("Playing '%c' (%s)\n", toupper(c), pattern);

            // Iterate through the dot/dash pattern
            for (int j = 0; pattern[j] != '\0' && running; j++) {
                if (pattern[j] == '.') {
                    play_tone(TONE_FREQUENCY, TIME_UNIT_S);
                } else if (pattern[j] == '-') {
                    play_tone(TONE_FREQUENCY, DASH_DURATION_S);
                }
                // Pause between elements of the same letter
                if (pattern[j+1] != '\0') {
                    play_silence(ELEMENT_PAUSE_S);
                }
            }
            return; // Character found and played
        }
    }
    // Handle space between words
    if (c == ' ') {
        printf("Playing word space\n");
        play_silence(WORD_PAUSE_S - CHARACTER_PAUSE_S); // The outer loop adds a character pause
    } else {
        printf("Skipping unsupported character: '%c'\n", c);
    }
}

int main() {
    // Initialize pigpio library
    if (gpioInitialise() < 0) {
        fprintf(stderr, "pigpio initialisation failed. Is the pigpiod daemon running?\n");
        return 1;
    }

    // Set up signal handler for graceful shutdown on Ctrl+C
    signal(SIGINT, cleanup_and_exit);

    // Set pin modes
    gpioSetMode(GREEN_LED_PIN, PI_OUTPUT);
    gpioSetMode(BUZZER_PIN, PI_OUTPUT);

    printf("Start morse_test.c\n");
    printf("Playing 'SOS' in Morse code.\n");
    printf("Green LED is ON during transmission.\n");
    printf("(Ctrl-C to EXIT)\n\n");

    const char* message_to_play = "VVV CQ CQ DE JA1RLD JA1RLD K";

    // Turn the green LED on for the duration of the test
    gpioWrite(GREEN_LED_PIN, 1);

    // Loop through the message string and play each character
    for (int i = 0; message_to_play[i] != '\0' && running; i++) {
        play_character(message_to_play[i]);
        // Pause between letters, but not after the last one
        if (message_to_play[i+1] != '\0' && message_to_play[i] != ' ') {
            play_silence(CHARACTER_PAUSE_S);
        }
    }

    // Cleanup and exit
    cleanup_gpio();
    printf("Program finished.\n");

    return 0;
}
                

Design Review Report (English)

This report provides an analysis of the provided C code, focusing on its design, strengths, and areas for improvement for an embedded application on a Raspberry Pi Zero.

Overall Impression

The code is well-structured and demonstrates a solid understanding of embedded programming fundamentals. The use of a data-driven approach for the Morse code lookup table is an excellent design choice that makes the code modular and easy to extend. The inclusion of a signal handler for graceful shutdown is a critical and highly commendable practice for robust embedded systems. This is a great foundation for a beginner project.

Strengths of the Design

  • Data-Driven Morse Code: The use of the `morse_table` array is a very effective design pattern. Instead of using a complex `switch` statement or a series of `if/else` blocks, the code relies on a simple lookup table. This makes adding new characters (like punctuation) or modifying existing patterns straightforward without altering the core logic of the `play_character` function.
  • Modularity and Abstraction: Functions like `play_tone`, `play_silence`, and `play_character` effectively abstract away the low-level hardware control. This improves readability and makes the main loop (`main`) very easy to follow. If you were to switch from a buzzer to a different audio output method, you would only need to change the `play_tone` function, not the entire program.
  • Robust Error Handling (GPIO): The check for `gpioInitialise()`'s return value is a great practice. It prevents the program from crashing and provides a clear error message to the user if the pigpiod daemon is not running, which is a common issue for beginners.
  • Graceful Shutdown: The `cleanup_and_exit` signal handler is a crucial feature. By catching `SIGINT` (the signal sent by Ctrl+C), the program can properly call `cleanup_gpio()` to turn off the LED and buzzer before terminating. This prevents the GPIO pins from being left in an unknown state, which could lead to unexpected behavior or hardware issues.

Areas for Improvement and Recommendations

  • Hardcoded Message: The message `const char* message_to_play = "VVV CQ CQ DE JA1RLD JA1RLD K";` is hardcoded directly in the `main` function.

    Recommendation: Consider passing the message as a command-line argument or reading it from a file. This makes the program more reusable without requiring a recompile for every new message.

  • Morse Timing and WPM: The Morse code timing is defined by several constants (`TIME_UNIT_S`, `DASH_DURATION_S`, etc.). If you wanted to change the speed (Words Per Minute), you would have to adjust all of these values.

    Recommendation: Define a single constant for the target **WPM** (e.g., `const int WPM = 15;`) and then calculate all the other timing constants from it. This makes the code much more flexible and easier to adjust.

  • Function Separation and Logic: The `play_character` function has two distinct responsibilities: playing a character's pattern and handling a space character.

    Recommendation: Consider refactoring the main loop to handle spaces directly. This simplifies the `play_character` function and makes the main loop's logic clearer.

  • Error Checking on GPIO Calls: While `gpioInitialise` is checked, other pigpio function calls like `gpioSetMode` and `gpioWrite` do not have their return values checked. In a production-level application, it's a good habit to check these functions as well.

    Recommendation: For a more robust application, add checks for the return values of all pigpio functions to ensure they succeed.


設計レビューレポート (日本語)

このレポートは、提供されたC言語のコードについて、Raspberry Pi Zeroでの組み込みアプリケーションとしての設計、強み、および改善点を分析するものです。

全体的な印象

コードはよく構成されており、組み込みプログラミングの基礎をしっかりと理解していることがわかります。モールス符号のルックアップテーブルにデータ駆動型のアプローチを使用しているのは、コードをモジュール化し、拡張しやすくするための優れた設計です。正常なシャットダウンのためのシグナルハンドラを含めていることは、堅牢な組み込みシステムにとって不可欠であり、非常に称賛に値する習慣です。これは初心者向けのプロジェクトとして素晴らしい基盤です。

設計の強み

  • データ駆動型のモールス符号: `morse_table`配列の使用は、非常に効果的な設計パターンです。複雑な`switch`文や一連の`if/else`ブロックを使用する代わりに、シンプルなルックアップテーブルに依存しています。これにより、新しい文字(句読点など)の追加や既存のパターンの修正が、`play_character`関数のコアロジックを変更することなく簡単に行えます。
  • モジュール性と抽象化: `play_tone`、`play_silence`、`play_character`のような関数は、低レベルのハードウェア制御を効果的に抽象化しています。これにより、可読性が向上し、メインループ(`main`)が非常に読みやすくなります。ブザーから別の音声出力方法に切り替える場合でも、プログラム全体ではなく`play_tone`関数のみを変更すればよくなります。
  • 堅牢なエラー処理 (GPIO): `gpioInitialise()`の戻り値をチェックしていることは、素晴らしい習慣です。これにより、pigpiodデーモンが実行されていないという初心者によくある問題が発生した場合でも、プログラムがクラッシュすることなく、明確なエラーメッセージをユーザーに提供できます。
  • 正常なシャットダウン: `cleanup_and_exit`シグナルハンドラは、非常に重要な機能です。`SIGINT`(Ctrl+Cで送信されるシグナル)をキャッチすることで、プログラムは終了する前に`cleanup_gpio()`を適切に呼び出し、LEDとブザーをオフにすることができます。これにより、GPIOピンが不明な状態のままになるのを防ぎ、予期せぬ動作やハードウェアの問題を回避できます。

改善点と推奨事項

  • ハードコードされたメッセージ: メッセージ`const char* message_to_play = "VVV CQ CQ DE JA1RLD JA1RLD K";`が`main`関数に直接ハードコードされています。

    推奨事項: メッセージをコマンドライン引数として渡すか、ファイルから読み込むことを検討してください。これにより、新しいメッセージごとに再コンパイルする必要がなくなり、プログラムの再利用性が向上します。

  • モールス符号のタイミングとWPM: モールス符号のタイミングは、いくつかの定数(`TIME_UNIT_S`、`DASH_DURATION_S`など)で定義されています。速度(1分あたりの単語数、WPM)を変更したい場合、これらすべての値を調整する必要があります。

    推奨事項: 目標とする**WPM**の単一の定数(例:`const int WPM = 15;`)を定義し、そこから他のすべてのタイミング定数を計算するようにしてください。これにより、コードの柔軟性が大幅に向上し、調整が簡単になります。

  • 関数の分離とロジック: `play_character`関数は、文字のパターンを再生することとスペース文字を処理することの2つの異なる責任を負っています。

    推奨事項: メインループでスペースを直接処理するようにリファクタリングすることを検討してください。これにより、`play_character`関数が単純化され、メインループのロジックがより明確になります。

  • GPIOコールでのエラーチェック: `gpioInitialise`はチェックされていますが、`gpioSetMode`や`gpioWrite`のような他のpigpio関数の戻り値はチェックされていません。本番レベルのアプリケーションでは、これらの関数も成功していることを確認するためにチェックするのが良い習慣です。

    推奨事項: より堅牢なアプリケーションにするため、すべてのpigpio関数の戻り値にチェックを追加し、それらが成功していることを確認してください。