PComp_3_SuperMarioTime

During the PComp Lab_03, although as struggling as usual, I found it very enjoyable to make the speaker speak! Such a lovely moment, probably as exciting as finding the existence of fire. And I even made a short Super Mario music, sweet!

PComp_Lab_MarioTime! from JHCLaura on Vimeo.

But I found it really difficult, when me and Billy tried to adjust the volume of speaker and also to make chords(two tunes speak at the same time).

For the volume

#include "pitches.h"

int lastButtonState = LOW;
boolean switchIsOn = false;

const int threshold = 10;
const int speakerPinNum = 8;
const int noteDuration = 20;

const int potenPinNum = 5;
int volumeAnalogValue = 0;
int volume = 0;

int note[] = {NOTE_C4, NOTE_E4, NOTE_G4};

void setup() {
  Serial.begin(9600);
}

void loop() {

  int buttonState = digitalRead(2);
  volumeAnalogValue = analogRead(potenPinNum);

  volume = map(volumeAnalogValue, 0, 1023, 0, 490);
  Serial.println(volume);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      switchIsOn = !switchIsOn;
    }
  }

  lastButtonState = buttonState;

  if (switchIsOn == true) {

    analogWrite(speakerPinNum, volume);
    Serial.println(volume);

    for (int i=0; i<2; i++) {
      int noteRead = analogRead(i);

      if(noteRead > threshold) {
        tone(speakerPinNum, note[i], noteDuration);
      }
    }
  }
}

My original idea was

  1. connecting speaker to digital pin #8, and potentiometer to analog pin #A5
  2. mapping the analogInput from  0~1023 to 0~490, setting it as volume
  3. analogWrite it into pin #8

But it failed  :/

Luckily, I bumped into my 2nd year buddy Andy and bothered him a couple of minutes and his advice simply blown my mind. He suggested using the potentiometer directly between digital pin #8 and the speaker, and adjust it directly without writing any codes! Wow. How I’ve never thought about this? And it worked! It simply proved that I’ve not thought it through totally. Hmmmm so much work to do, fighting 🙂

VolumeAdjust

New codes!

#include "pitches.h"

int lastButtonState = LOW;
boolean switchIsOn = false;

const int threshold = 10;
const int speakerPinNum = 8;
const int noteDuration = 20;

const int potenPinNum = 5;
int volumeAnalogValue = 0;
int volume = 0;

int note[] = {
  NOTE_C4, NOTE_E4, NOTE_G4};

void setup() {
  Serial.begin(9600);

}

void loop() {

  int buttonState = digitalRead(2);
  volumeAnalogValue = analogRead(potenPinNum);

  volume = map(volumeAnalogValue, 0, 1023, 0, 490);
  Serial.println(volume);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      switchIsOn = !switchIsOn;
    }
  }

  lastButtonState = buttonState;

  if (switchIsOn == true) {

    for (int i=0; i<2; i++) {
      int noteRead = analogRead(i);
      Serial.println(noteRead);
      if(noteRead > threshold) {
        tone(speakerPinNum, note[i], noteDuration);
      }
    }
  }
}

Leave a Comment.