Devices & Components
Arduino Uno Rev3
16 x 2 LCD Display
ELEGOO HC-SR04 Ultrasonic Distance Sensor Kits
Breadboard (Regular)
Piezoelectric Buzzer
10K potentiometers
Jumper Wires
220 resistor
Software & Tools
Arduino IDE
Project description
Code
Arduino Theremin Code
cpp
1#include <LiquidCrystal.h> 2 3const int RS = 8; 4const int E = 9; 5const int DB4 = 10; 6const int DB5 = 11; 7const int DB6 = 12; 8const int DB7 = 13; 9 10auto lcd = LiquidCrystal(RS, E, DB4, DB5, DB6, DB7); 11 12const int PITCH_SENSOR_ECHO = 4; 13const int PITCH_SENSOR_TRIG = 5; 14 15long pitch_time; 16short pitch_distance; 17int pitch; 18 19const int SPEAKER = 6; 20 21const int LAG = 65; 22 23void setup() 24{ 25 Serial.begin(9600); 26 27 pinMode(PITCH_SENSOR_TRIG, OUTPUT); 28 pinMode(PITCH_SENSOR_ECHO, INPUT); 29 30 pinMode(SPEAKER, OUTPUT); 31 32 lcd.begin(16,2); 33 lcd.setCursor(0,0); 34 lcd.print("Pitch: "); 35} 36 37void loop() 38{ 39 40 //Calls a function to sense the distance (in time) to an object and stores it 41 pitch_time = senseDistance(PITCH_SENSOR_TRIG, PITCH_SENSOR_ECHO); 42 43 //Uses the time to calculate the distance in cm 44 pitch_distance = pitch_time / 58; 45 46 //Map the distance to the frequencies that you want to output 47 pitch = map(pitch_distance, 0, 355, 131, 523); 48 49 lcdDisplay(pitch); 50 51 tone(SPEAKER, pitch, 60); 52 53 delay(LAG); 54} 55 56//Function to sense distance 57long senseDistance(int triggerSensor, int echoSensor) { 58 59 digitalWrite(triggerSensor, HIGH); 60 delayMicroseconds(10); 61 digitalWrite(triggerSensor, LOW); 62 63 return pulseIn(echoSensor, HIGH); 64} 65 66//Function to output a display 67void lcdDisplay(int pitch) { 68 lcd.setCursor(7, 0); 69 lcd.print(pitch); 70 lcd.print("Hz "); 71 72}
Comments
Only logged in users can leave comments