With the switch in one position, pressing the button will play the theme song from Super Mario. With the switch in the other position, turning the potentiometer will turn the servo.
- Potentiometer
- Servo
- Switch
- Button
- Piezo
Code Used:
- analogRead
- If statement
- digitalRead
- Map function
#include <Servo.h>
/* Diyode CodeShield Constants */
#define ENCODER_A 14
#define ENCODER_B 15
#define ENCODER_PORT PINC
#define SWITCH 13
#define BUTTON 12
#define RGB_RED 11
#define RGB_GREEN 10
#define RGB_BLUE 9
#define LED 6
#define SERVO 5
#define PIEZO 3
#define RELAY 2
#define POT 2
#define HALL 3
#define THERMISTOR 4
#define PHOTOCELL 5
/* Note Definitions */
#define C 1911
#define C1 1804
#define D 1703
#define Eb 1607
#define E 1517
#define F 1432
#define F1 1352
#define G 1276
#define Ab 1204
#define A 1136
#define Bb 1073
#define B 1012
#define cc 955
#define c1 902
#define d 851
#define eb 803
#define e 758
#define f 716
#define f1 676
#define g 638
#define ab 602
#define a 568
#define bb 536
#define b 506
#define pause 0 //pause
long vel = 24000;
int servoOn = 0;
Servo myservo; // create servo object to control a servo
void setup() {
pinMode(PIEZO, OUTPUT);
pinMode(RGB_RED, OUTPUT);
pinMode(RGB_GREEN, OUTPUT);
pinMode(RGB_BLUE, OUTPUT);
pinMode(SWITCH, INPUT);
pinMode(BUTTON, INPUT);
delay(200);
digitalWrite(RGB_RED, LOW);
digitalWrite(RGB_GREEN, LOW);
digitalWrite(RGB_BLUE, HIGH);
}
int melody[] = {e, e, e, cc, e, g, G, cc, G, E, A, B, Bb, A, G, e, g, a, f, g, e, cc, d, B, cc};
int rhythm[] = {6, 12, 12, 6, 12, 24, 24, 18, 18, 18, 12, 12, 6, 12, 8, 8, 8, 12, 6, 12, 12, 6, 6, 6, 12};
void loop() {
if (digitalRead(SWITCH) == HIGH) {
if (servoOn == 0) {
myservo.attach(SERVO);
servoOn = 1;
digitalWrite(RGB_RED, HIGH);
digitalWrite(RGB_GREEN, LOW);
digitalWrite(RGB_BLUE, LOW);
}
setServo();
} else {
if (servoOn == 1) {
myservo.detach();
servoOn = 0;
digitalWrite(RGB_RED, LOW);
digitalWrite(RGB_GREEN, LOW);
digitalWrite(RGB_BLUE, HIGH);
}
if (digitalRead(BUTTON) == HIGH) {
playSong();
}
}
delay(10);
}
void playSong() {
int len = sizeof(rhythm) / 2;
digitalWrite(RGB_GREEN, HIGH);
delay(200);
for (int i=0; i<len; i++) {
int tone = melody[i];
int tempo = rhythm[i];
long tvalue = tempo * vel;
playNote(tone, tvalue);
delay(30); //pausa entre notas!
if (digitalRead(SWITCH) == HIGH || digitalRead(BUTTON) == HIGH) {
digitalWrite(RGB_GREEN, LOW);
delay(500);
break;
}
}
digitalWrite(PIEZO, LOW);
}
void playNote(int tone, long totalLength) {
long currentLength = 0;
while (currentLength < totalLength) {
digitalWrite(PIEZO, HIGH);
delayMicroseconds(tone / 2);
digitalWrite(PIEZO, LOW);
delayMicroseconds(tone/2);
currentLength += tone;
}
}
void setServo() {
int potval = analogRead(POT);
int angle = map(potval, 0, 1023, 0, 179);
myservo.write(angle);
delay(20);
}