Serial Musical Organ 1.0
Buzzer controller and musical organ
Loading...
Searching...
No Matches
Functions
organ.c File Reference

Implementation of tone generation functions for electronic organ. More...

#include "includes/CPU.h"
#include <avr/io.h>
#include <util/delay.h>
#include "includes/organ.h"
#include "includes/pinDefines.h"
Include dependency graph for organ.c:

Go to the source code of this file.

Functions

void playNote (uint16_t half_us, uint16_t duration_ms)
 Generates a musical tone with specific duration.
 
void rest (uint16_t duration)
 

Detailed Description

Implementation of tone generation functions for electronic organ.

Author
Roybel Carbonell Camejo
Date
2026-04-28

This file contains the implementation of functions required to generate musical tones using a piezoelectric buzzer.

Definition in file organ.c.

Function Documentation

◆ playNote()

void playNote ( uint16_t  half_us,
uint16_t  duration_ms 
)

Generates a musical tone with specific duration.

Play a musical tone.

Parameters
[in]half_usHalf period of the square wave in microseconds (1/(2*frequency))
[in]duration_msTotal note duration in milliseconds

This function generates a square wave on the buzzer pin to produce a musical tone. The tone is generated using the following formula:

  • Frequency (Hz) = 1,000,000 / (2 * half_us)
  • Total cycles = (frequency * duration_ms) / 1000
Algorithm:
The function toggles the buzzer pin between HIGH and LOW, with delays equal to the specified half period, thus generating a perfect square wave.
Example:
// Generate A4 (440 Hz) for 500 ms
// half_us = 1,000,000/(2*440) = 1136 us
play_note(1136, 500);
Note
The cycle calculation is performed as: cycles = (500000 / half_us) * duration_ms / 1000 This formula avoids integer overflow.
Warning
This function uses _delay_us() which is NOT accurate for delays > 768 us at 16 MHz. For half_us > 768, consider using hardware timers.
Delays are blocking; no other tasks can execute during note playback.
Precondition
The BUZZER_PIN must be configured as output on BUZZER_PORT before calling this function.
Postcondition
After playing the note, there is an additional 30ms delay to prevent "clicks" between notes.
See also
timer_generate_tone() For non-blocking implementation
play_song() For playing complete melodies

@bugs For very small half_us (< 10), the generated frequency may be inaccurate due to loop overhead.

Todo:

Implement hardware timer version for non-blocking playback

Add volume control using PWM modulation

Definition at line 66 of file organ.c.

References BUZZER_PIN, and BUZZER_PORT.

Referenced by main(), and play_twinkle_little_star().

Here is the caller graph for this function:

◆ rest()

void rest ( uint16_t  duration)

Definition at line 92 of file organ.c.

Referenced by main().

Here is the caller graph for this function: