Tone Output Using Arduino
My photoresistors broke because of my spectacular soldering work. I've ordered replacements.
In the meanwhile I followed through on the lab but my photoresistors broke so I ended up using buttons to implement the same feature.
I increased the threshold
to 20 otherwise there was random noise coming in.
Concern: For some reason the sound in the speaker comes out very low. Im curious about what the cause behind it is
#include "pitches.h"
const int threshold = 20; // minimum reading of the sensors that generates a note
const int speakerPin = 8; // pin number for the speaker
const int noteDuration = 20; // play notes for 20 ms
// notes to play, corresponding to the 3 sensors:
int notes[] = {
NOTE_A4, NOTE_B4,NOTE_C3 };
void setup() {
}
void loop() {
for (int thisSensor = 0; thisSensor < 2; thisSensor++) {
// get a sensor reading:
int sensorReading = analogRead(thisSensor) ;
// if the sensor is pressed hard enough:
if (sensorReading > threshold) {
// play the note corresponding to this sensor:
tone(speakerPin, notes[thisSensor], noteDuration);
}
}
}
Servo Motor Control
I was also able to get the servo motor working properly.
#include "pitches.h"
#include "Servo.h"
Servo servoMotor;
int servoPin = 2;
const int speakerPin = 8; // pin number for the speaker
const int threshold = 30; // minimum reading of the sensors that generates a note
const int noteDuration = 20; // play notes for 20 ms
// notes to play, corresponding to the 3 sensors:
int notes[] = {
NOTE_A4, NOTE_B4, NOTE_C3
};
void setup() {
Serial.begin(9600); // initialize serial communications
servoMotor.attach(servoPin);
}
int changing = 0;
void loop() {
int total = 0;
for (int thisSensor = 0; thisSensor < 2; thisSensor++) {
// // get a sensor reading:
int sensorReading = analogRead(thisSensor) ;
total = total + sensorReading;
}
// Control servo
int servoAngle = map(total, 0, 2047, 0, 90);
if (millis() % 500 < 2) {
// Log
Serial.print(total);
Serial.print("| ");
Serial.print(servoAngle);
Serial.println();
}
if (millis() % 20 < 2) {
// servoMotor.write(servoAngle);
servoMotor.write(changing);
}
if (millis() % 10 < 2) {
// changing = (changing + 20) % 180;
changing = servoAngle;
}
}