Project 14: Sensor Organ - Thames & Kosmos Code Gamer Experiment Manual

Coding workshop ? game with kosmobits
Table of Contents

Advertisement

PROJECT 14
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
THE PROGRAM
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
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
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
array for this purpose. All values in it will
values[]
first be set to 0 by
int values[N] = {};
With the
variable, the array will be run through,
index
starting with 0 as usual.
This is where each of the pin modes is set.
You will start by taking a new measurement reading and
saving it in the
values
ensure that the next measurement reading is saved at the
subsequent position,
++index;
the value of
is reached, the
N
44
CodeGamer manual inside english.indd 44
and
measurementMax
scaling
.
array at the
position. To
index
raises the
by 1. If
index
instruction sets
if
index
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.
#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;
// 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;
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);
</>
// This is the
7/19/16 12:32 PM

Advertisement

Table of Contents
loading

Table of Contents