I was trying to build a basic theremin with my Arduino for didactic purpose.
My idea was reading a potentiometer for the volume and a photoresistor for the pitch.
My code right now is:
int piezoPin = 5;
int sensorPin = 1;
int potPin = 2;
int sogliaMinima = 20;
int sogliaMassima = 160;
void setup () {
pinMode (piezoPin, OUTPUT);
Serial.begin (9600);
}
void loop () {
// first block of code working
int potLevel = analogRead (potPin);
int levelVolume = map (potLevel, 0, 1022, 0, 170);
analogWrite (piezoPin, levelVolume);
// second block of code working
int sensorValue = analogRead (sensorPin);
int pitchLevel = map (sensorValue, sogliaMinima, sogliaMassima, 100, 1000);
tone (piezoPin, pitchLevel);
}
This is not working, and it’s a software issue not a circuit mistake. Both first block and second block are working if commenting one of them, but don’t work together. So my question is: can I use tone() and analogWrite on the same pin?
You are correct. You can’t use both functions on the same pin. The two functions analogWrite and tone both attempt to control the pin with a PWM signal. Doing both in sequence changes their defaults. For analogWrite, the tone is 490Hz.