Top of this document
Go directly to navigation
Go directly to page content

The Cuddle Bag's sound

Creating sound with arduino

Hybrid Wearable workshop, 19th to 21th February 2008. Creating the Cuddle Bag together with ...
My task was to create a switchable sound for arduino interface.

Here is the commentated Code for Cuddle Bag sound:

// Sound for Cuddle Bag, Hans-Gunter Lock 2008

#include <math.h>
#define speakerOut 11

int pitchval = 1;
int val = 0;
int j;
int k;
int l;
int m;
int freq,t;
int randomend;
int phase = 50;
int inputPin = 2; // choose the input pin (for a pushbutton)
int frequency = 100;
int frandstart = 1;
int frandstop = 5;
int randvalue = 3;

void setup() {
Serial.begin(9600);
pinMode(inputPin, INPUT); // declare pushbutton as input
pinMode(speakerOut, OUTPUT);

}
//MAIN FUNCTION*
// The main function reads out the information from the switch
// If the incoming value/voltage is LOW that the function glideswitch is executed

void loop() {

val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
phase = random(110,130);
digitalWrite(13, LOW); turn LED OFF

} else {
digitalWrite(13, HIGH); turn LED ON
//Serial.println("Glide");
glideswitch();
}
}

//ENDING SOUND***
// generates the end of the saound

void endsound() {
for (j=1;j<180;j++){
//for (m=1; m<200; m++){
freqout(frequency/j, t);
}
}

//REACTION CHOOSE***
// This function chooses, if switching causes a sound or not

void glideswitch() {
//for (m=0; m<randvalue; m++){
//loop();
//}
Serial.print (m);
m = m + 1;
if (m == randvalue) {
m = 0;
glide();
} else {
delay(200);
loop();
}
}

//*SOUND MODULATING
// modulates the sound with counters
// if this function is activated, a new random value is generated for
// reaction choose every 4th to 6th switching

void glide() {
randvalue = random(5,7);

for (k=0; k<phase; k++){
// k good between 100 and 200
frequency = k *random(frandstart,frandstop);
//delay(100);
freqout(frequency, t);
}
for (l=0; l<phase; l++){
randomend = (phase-l)*random(frandstart,frandstop);
//delay(100);
freqout(randomend, t);
if (l = phase) {
endsound();
}
}
}

//SOUND GENERAION***
// Thats the real sound generation code

//freqout code by Paul Badger (and hacked a bit by me)

void freqout(int freq, int t)
{
int hperiod; //calculate 1/2 period in us
long cycles, i;
t = random(1,freq);
// hperiod = (500000 / freq - 7) * random(1,randomend);
hperiod = 5000/freq;
//hperiod = random (5000, hperiod);
Serial.println(hperiod); subtract 7 us to make up for digitalWrite overhead - determined empirically
// calculate cycles
cycles = ((long)freq * (long)t) / 100; // calculate cycles

for (i=0; i<= cycles; i++){ // play note for t ms
digitalWrite(speakerOut, HIGH);
delayMicroseconds(hperiod);
digitalWrite(speakerOut, LOW);
delayMicroseconds(hperiod - 1); // - 1 to make up for fractional microsecond in digitaWrite overhead
}
}

Contributions 
Comments