refactor: put tone generation code into dedicated file

This commit is contained in:
Fritz Heiden 2025-05-24 15:36:50 +02:00
parent fffd9c6b5d
commit 16cec914f8
3 changed files with 75 additions and 27 deletions

View File

@ -0,0 +1,54 @@
#include <Arduino.h>
#ifndef ANALAOG_OUTPUT_PIN
#define ANALOG_OUTPUT_PIN 3
#endif
namespace ToneGenerator
{
void handleToneGeneration(void *pvParameters);
bool tone_on = false;
int frequency = 220; // A4
void init()
{
pinMode(ANALOG_OUTPUT_PIN, OUTPUT);
xTaskCreate(handleToneGeneration, "handleToneGeneration", 2048, NULL, 1, NULL);
}
void handleToneGeneration(void *pvParameters)
{
int tone_duration = 100;
while (true)
{
if (tone_on)
{
// tone(ANALOG_OUTPUT_PIN, frequency, tone_duration);
delay(tone_duration);
tone_on = false;
}
delay(10);
}
}
void setToneOn(bool on)
{
tone_on = on;
}
bool isToneOn()
{
return tone_on;
}
void setFrequency(int freq)
{
frequency = freq;
}
int getFrequency()
{
return frequency;
}
}

View File

@ -0,0 +1,13 @@
#ifndef DRUMZ_AUDIO_TONE_GENERATOR_HPP
#define DRUMZ_AUDIO_TONE_GENERATOR_HPP
namespace ToneGenerator
{
void init();
void setToneOn(bool on);
bool isToneOn();
void setFrequency(int frequency);
int getFrequency();
}
#endif // DRUMZ_AUDIO_TONE_GENERATOR_HPP

View File

@ -1,8 +1,5 @@
#include <Arduino.h>
#include <ui/display.hpp>
#include <input/encoder.hpp>
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 240
@ -10,25 +7,24 @@
#define ENCODER_A_PIN = 12;
#define ENCODER_B_PIN = 13;
#define ANALOG_OUTPUT_PIN = 25;
#include <ui/display.hpp>
#include <input/encoder.hpp>
#include <audio/tone_generator.hpp>
const int ONBOARD_LED_PIN = 2;
const int ANALOG_INPUT_PIN = 34;
const int ANALOG_OUTPUT_PIN = 25;
void handleToneGeneration(void *pvParameters);
void handle_pad_inputs(void *pvParameters);
bool toneOn = false;
int frequency = 220; // A4
void setup()
{
Serial.begin(115200);
pinMode(ONBOARD_LED_PIN, OUTPUT);
pinMode(ANALOG_INPUT_PIN, INPUT);
pinMode(ANALOG_OUTPUT_PIN, OUTPUT);
xTaskCreate(handleToneGeneration, "handleToneGeneration", 2048, NULL, 1, NULL);
xTaskCreate(handle_pad_inputs, "handle_pad_inputs", 2048, NULL, 1, NULL);
Encoder::init();
@ -52,9 +48,9 @@ void handle_pad_inputs(void *pvParameters)
for (int i = 0; i < 100; i++)
{
int value = analogRead(ANALOG_INPUT_PIN);
if (!toneOn && value > 0)
if (!ToneGenerator::isToneOn() && value > 0)
{
toneOn = true;
ToneGenerator::setToneOn(true);
}
if (value > max)
{
@ -65,18 +61,3 @@ void handle_pad_inputs(void *pvParameters)
}
}
void handleToneGeneration(void *pvParameters)
{
int toneDuration = 100;
while (true)
{
if (toneOn)
{
// tone(ANALOG_OUTPUT_PIN, frequency, toneDuration);
delay(toneDuration);
toneOn = false;
}
delay(10);
}
}