Wednesday 4 April 2012

Rock the Square Wave Bass Synth

So today I spent tinkering with the good old Arduino and the tone() function which is great fun it is simple to set up and it goes beep. I have however decided to merge it with the serial function in Processing turning the computer keyboard in to a musical one. This code was hacked to together from the various tutorials on the Arduino and Processing sites.

You'll need a 8ohm Speaker (I used a 0.5w one) and 100ohm resistor, I have connected it to pin 8 just like in the diagram which I made using Fritzing.

There are two chunks of code one for the Arduino and one for Processing. You'll need to make sure you computer is sending stuff down the right serial port so it might take a bit of fiddling, before it all works. After installing the software on the Arduino you can check it is working by opening the Serial Monitor and typing either c,d,e,f,g,a,b or C.

The code works like this, Processing takes a key press i.e. "a" and sends the byte "c", the Arduino interprets this and plays the correct tone after receiving it. If nothing is being pressed and "Q" is sent, I use this code for loads of different projects. I didn't want to include too much in this example I leave it up to you to clutter.

Processing code // KEYSEND

import processing.serial.*;

Serial myPort;

void setup()
{
size(200, 200);
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}

void draw() {
background(0);

if (keyPressed == true) {

if (key == 'a') {
myPort.write('c');
}

else if (key == 's') {
myPort.write('d');
}

else if (key == 'd') {
myPort.write('e');
}

else if (key == 'f') {
myPort.write('f');
}

else if (key == 'g') {
myPort.write('g');
}

else if (key == 'h') {
myPort.write('a');
}

else if (key == 'j') {
myPort.write('b');
}

else if (key == 'k') {
myPort.write('C');
}

}

if (keyPressed == false) {
myPort.write('Q');

}
}

Arduino Code // SERIAL TONES

#include "pitches.h"

byte val = 0;
int serByte = -1;
int count = 0;

int melody[] = {NOTE_C1, NOTE_D1,NOTE_E1, NOTE_F1, NOTE_G1,NOTE_A1, NOTE_B1, NOTE_C2,0};
byte names[] ={'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'Q'};

int noteDurations[] = {4, 4, 4, 4, 4, 4, 4, 4 };

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

void loop() {

serByte = Serial.read();
if (serByte != -1) {
val = serByte;

}
for (count=0;count<=9;count++) {
if (names[count] == val) {
if (count<8){

int noteDuration = 1000/noteDurations[count];
tone(8, melody[count],noteDuration);

}
else {

noTone(8);
}

}
}


}

Arduino Code / pitches.h
//You'll need to make a new tab and call it pitches.h

#define NOTE_C1 33
#define NOTE_D1 37
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_G1 49
#define NOTE_A1 55
#define NOTE_B1 62
#define NOTE_C2 65

No comments:

Post a Comment