- Starting the lab by locating a 100-ohm resistor. (figure 1)
figure 1 - Realizing there will be a lot of components in this lab, so I connected the breadboard utilizing the whole board instead of half of it like in the previous labs. (figure 2)
figure 2 - Adding the first force-sensing resistor. (figure 3)
figure 3 - Adding the second force-sensing resistor in serial with the first one. (figure 4)
figure 4 - Connecting the speaker to port 8. (figure 5)
figure 5 - With the following code, I check the range of the sensors output.
void setup() {
Serial.begin(9600);
}void loop() {
int analogValue = analogRead(A0);
Serial.println(analogValue);
} - The range of the sensor output is from 0 – 1023 according to the serial monitor. (figure 6, figure 7, figure 8)
figure 6 figure 7 figure 8 - Therefore, for the first exercise, to make the speaker sound with one tone, the code looks like this. Video 1 shows it at work.
void setup() {
// put your setup code here, to run once:}void loop() {
int sensorReading = analogRead(A0);
float frequency = map(sensorReading, 0, 1023, 100, 1000);
tone(8, frequency, 10);
}video 1
- The breadboard remains the same for the second exercise — A more complex example. I used nested for loops so it plays five times, giving me enough time to capture it on video. Note that after clicking the adding new tab, the prompt for file name shows up at the bottom of the Arduino App. That’s where I can copy and paste the array of variables of different notes. Video 2 shows the final result of this exercise.
# include “pitches.h”
int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_GS3, NOTE_G3, 0, NOTE_B3, NOTE_C4 };
int noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4};
void setup() {
for (int i = 0; i < 5; i++){
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000 / noteDurations [thisNote];
tone(8, melody[thisNote], noteDuration);
delay(noteDuration +30);
}
}
}void loop() {
// put your main code here, to run repeatedly:}
video 2 - For the next exercise, I changed the breadboard to have two sensors in parallel. The initial code looks like this with the threshold being 10. I only have two sensors, so I can only have two notes and thisSensor needs to be less than 2: they are at A0 and A1.
#include “pitche.h”const int threshold = 10;
const int speakerPin = 8;
const int noteDuration = 20;int notes[] = {NOTE_A4, NOTE_B4};
void setup() {
// put your setup code here, to run once:}
void loop() {
// put your main code here, to run repeatedly:
for (int thisSensor = 0; thisSensor < 2; thisSensor++){
int sensorReading = analogRead(thisSensor);
if (sensorReading > threshold) {
tone(speakerPin, notes[thisSensor], noteDuration);
}
}
} - It works. But with a constant noise. (video 3)
video 3 - Then I change the threshold value from 10 to 50. The noise is gone. (video 4)
video 4
Leave a Reply