/*
This Project is modeled after a 4 Hole Ocarina using the
ATTiny 85 where the buttons are used as binary switches
that are combined to equal a value that is then mapped to
a tone.
There is a fifth hole which controls whether sound is
produced but has no bearing on the pitch.
*/
#include <TinyDebug.h>
//Define Constant value for speaker pin.
#define SPEAKER_PIN 0
//Define Valid Button Value Array.
const uint8_t arrayBtnValues[] = { 0, 1, 8, 10, 12, 13, 14, 15 };
//Define Valid Tone Value Array.
const int arrayToneValues [] = { 1046, 988, 880, 784, 698, 659, 587, 523 };
//Get Number of values in arrayToneValues.
const int numTones = sizeof(arrayToneValues) / sizeof(arrayToneValues[0]);
//Define Button Pins.
int btn1pin = 5; //Green
int btn2pin = 1; //Blue
int btn3pin = 2; //Yellow
int btn4pin = 4; //Red
int btn5pin = 3; //Grey
//Set Initial Values for Variables used in program.
int btnValue = 0;
int btnLoc = 0;
int pitch = 0;
int makeSound = 0;
void beep (unsigned char speakerPin, int frequencyInHertz)
{
int x;
long delayAmount = (long)(1000000 / frequencyInHertz);
pinMode(speakerPin, OUTPUT);
digitalWrite(speakerPin, HIGH);
delayMicroseconds(delayAmount);
digitalWrite(speakerPin, LOW);
delayMicroseconds(delayAmount);
pinMode(speakerPin, INPUT);
}
void setup() {
//Set PinModes for Button Pins; Set to INPUT_PULLUP to avoid interference.
pinMode(btn1pin, INPUT_PULLUP); //Green
pinMode(btn2pin, INPUT_PULLUP); //White
pinMode(btn3pin, INPUT_PULLUP); //Yellow
pinMode(btn4pin, INPUT_PULLUP); //Blue
pinMode(btn5pin, INPUT_PULLUP); //Grey
}
void loop() {
//Reset variables
btnValue = 0;
pitch = 0;
makeSound = 0;
//Set makeSound to true if Button 5 is pressed. Controls if sound is made.
if (digitalRead(btn5pin) == LOW) {
makeSound = 1;
}
//Increase btnValue.
if (digitalRead(btn1pin) == LOW) {
btnValue = btnValue + 1;
}
//Increase btnValue.
if (digitalRead(btn2pin) == LOW) {
btnValue = btnValue + 2;
}
//Increase btnValue.
if (digitalRead(btn3pin) == LOW) {
btnValue = btnValue + 4;
}
//Increase btnValue.
if (digitalRead(btn4pin) == LOW) {
btnValue = btnValue + 8;
}
//Check for makeSound True/False.
if (makeSound) {
//Check each value of arrayBtnValue for match to btnValue.
for (uint8_t i = 0; i < numTones; i++) {
//If match is found, set pitch varialble from arrayToneValues.
if (arrayBtnValues[i] == btnValue) {
pitch = arrayToneValues[i];
//This line is left in to produce a solid smooth sound.
Debug.println (pitch);
}
}
}
//If pitch is set, play a tone else don't play a tone.
if (pitch) {
beep(SPEAKER_PIN,pitch);
}
}