Testing and learning¶
Potentiometer¶
/*
* Read a value from a potentiometer and display it on the serial monitor
*/
const int potPin = A0;
void setup() {
Serial.begin(9600);
pinMode(potPin, INPUT);
}
void loop() {
int potValue = analogRead(potPin);
Serial.println(potValue);
}
Speaker¶
/*
* Play a note on a speaker
*/
const int speakerPin = 9;
void setup() {
pinMode(speakerPin, OUTPUT);
}
void loop() {
tone(speakerPin, 440); // Play the note A
}
Potentiometer and Speaker¶
/*
* Read a value from the potentiometer and map it to the speaker
*/
const int speakerPin = 9;
const int potPin = A0;
void setup() {
Serial.begin(9600);
pinMode(potPin, INPUT);
pinMode(speakerPin, OUTPUT);
}
void loop() {
// map the value given by the potentiometer to a value understadood as hertz for the speaker
int potValue = analogRead(potPin);
int speakerValue = map(potValue, 0, 1023, 400, 3000);
Serial.print("Value:");
Serial.println(potValue);
Serial.print("Volume:");
Serial.println(speakerValue);
tone(speakerPin, speakerValue);
}
Play a melody on a buzzer with a button¶
/*
* Play a melody on a buzzer if a button is pushed ON.
*/
const int speakerPin = 12;
const int buttonPin = 2;
void setup() {
pinMode(speakerPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
// Read the button status
int buttonStatus = digitalRead(buttonPin);
// Play if the button is ON.
if (buttonStatus == 1) {
tone(speakerPin, 392); // Play the note G
delay(200);
tone(speakerPin, 392);
delay(200);
tone(speakerPin, 392);
delay(200);
tone(speakerPin, 440); // Play the note A
delay(200);
tone(speakerPin, 493.88); // Play the note B
delay(400);
tone(speakerPin, 440);
delay(400);
tone(speakerPin, 392);
delay(200);
tone(speakerPin, 493.88);
delay(200);
tone(speakerPin, 440);
delay(200);
tone(speakerPin, 440);
delay(200);
tone(speakerPin, 392);
delay(800);
noTone(speakerPin);
delay(5000);
}
}
Warning
I'm concerned about the timing of a project: multi-threading isn't allowed with Arduino. Jonah told me about "interrupt" and I'm gonna look at some options.
Last update: January 28, 2022