Sensor organ
Now that you have learned how to play musical scales,
it’s time to program an actual musical instrument.
YOU WILL NEED
› KosmoDuino in the interaction board
› Motion sensor
#include <KosmoBits_Pins.h>
const int sensorPin = KOSMOBITS_SENSOR_PIN;
const int buzzerPin = KOSMOBITS_BUZZER_PIN;
const int buttonPin = KOSMOBITS_BUTTON_2_PIN;
const float scale[] = {1.f, 9.f/8, 5.f/4, 4.f/3,
3.f/2, 5.f/3, 15.f/8, 2.f};
const int freqRoot = 220;
// This is the
// note A.
const int measurementMin = 300;
const int measurementMax = 400;
const int scaling = (measurementMax -
measurementMin) / 9;
const int N = 10;
// Number of values that
// are averaged.
int values[N] = {};
// Here is where the last
// 10 values are stored.
int index = 0;
This is where each of the pin modes is set.
void setup() {
pinMode(sensorPin, INPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
// Reads a new value from the sensor and
// saves it in values[].
values[index] = analogRead(sensorPin);
First, you will define a few constants for sensor pin,
buzzer pin, and button pin. Then, as you did in the last
project, you will apply an array for the scale as well as a
constant for the root chord.
With the
measurementMin
and
measurementMax
constants, you will be regulating how far the controller
has to be tipped in order to play the highest or the lowest
note. You can adjust these values to suit your own
preferences later on. You will be using the
scaling
constant later on to determine the pitch from a
measurement reading, dividing practically the entire
measurement range into 9 portions.
The motion sensor is quite sensitive, so the readings will
fluctuate a little. To keep the pitch from wavering too
much, you won’t be taking the last reading to measure the
pitch. Instead, you will be calculating the average of 10
readings. The last 10 measurement readings will be saved
in the
values[]
array for this purpose. All values in it will
first be set to 0 by
int values[N] = {};
.
With the
index
variable, the array will be run through,
starting with 0 as usual.
THE PLAN
You will produce musical notes at the push of a button.
The pitch of the note can be changed by moving the
interaction board. With a little practice, you can play an
actual melody this way.
</>
THE PROGRAM
You will start by taking a new measurement reading and
saving it in the
values
array at the
index
position. To
ensure that the next measurement reading is saved at the
subsequent position,
++index;
raises the
index
by 1. If
the value of
N
is reached, the
if
instruction sets
index
44
PROJECT 14
CodeGamer manual inside english.indd 44
7/19/16 12:32 PM