A detailed analysis of `morse_test.c` for Raspberry Pi Zero
#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;
}
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.
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.
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.
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.
Recommendation: Consider refactoring the main loop to handle spaces directly. This simplifies the `play_character` function and makes the main loop's logic clearer.
Recommendation: For a more robust application, add checks for the return values of all pigpio functions to ensure they succeed.
このレポートは、提供されたC言語のコードについて、Raspberry Pi Zeroでの組み込みアプリケーションとしての設計、強み、および改善点を分析するものです。
コードはよく構成されており、組み込みプログラミングの基礎をしっかりと理解していることがわかります。モールス符号のルックアップテーブルにデータ駆動型のアプローチを使用しているのは、コードをモジュール化し、拡張しやすくするための優れた設計です。正常なシャットダウンのためのシグナルハンドラを含めていることは、堅牢な組み込みシステムにとって不可欠であり、非常に称賛に値する習慣です。これは初心者向けのプロジェクトとして素晴らしい基盤です。
推奨事項: メッセージをコマンドライン引数として渡すか、ファイルから読み込むことを検討してください。これにより、新しいメッセージごとに再コンパイルする必要がなくなり、プログラムの再利用性が向上します。
推奨事項: 目標とする**WPM**の単一の定数(例:`const int WPM = 15;`)を定義し、そこから他のすべてのタイミング定数を計算するようにしてください。これにより、コードの柔軟性が大幅に向上し、調整が簡単になります。
推奨事項: メインループでスペースを直接処理するようにリファクタリングすることを検討してください。これにより、`play_character`関数が単純化され、メインループのロジックがより明確になります。
推奨事項: より堅牢なアプリケーションにするため、すべてのpigpio関数の戻り値にチェックを追加し、それらが成功していることを確認してください。