0% found this document useful (0 votes)
3 views59 pages

3.d. Arduino

The document provides an overview of interaction design using Arduino, focusing on the Arduino UNO board, its IDE, and how to acquire sensor data. It includes examples of coding for various sensors such as pushbuttons, potentiometers, and inertial measurement units, along with explanations of their working principles and schematics. The document serves as a guide for interfacing Arduino with different sensors and controlling outputs like LEDs.

Uploaded by

Thomas Fayard
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views59 pages

3.d. Arduino

The document provides an overview of interaction design using Arduino, focusing on the Arduino UNO board, its IDE, and how to acquire sensor data. It includes examples of coding for various sensors such as pushbuttons, potentiometers, and inertial measurement units, along with explanations of their working principles and schematics. The document serves as a guide for interfacing Arduino with different sensors and controlling outputs like LEDs.

Uploaded by

Thomas Fayard
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Interaction Design with Arduino

Summary

• The Arduino (UNO) board


• The Arduino IDE
• Structure of an Arduino sketch
• Acquiring sensor data with Arduino
• Interfacing with SuperCollider
• A couple of examples

Computer Music, Fabio Antonacci


The Arduino UNO board

Arduino is an open-source
electronic prototyping
platform.
Several boards have been
developed through the
years. We will consider
here the Arduino UNO.

Microcontroller (ATMega 328)


Clock: 16 MHz
SRAM: 2KB
EEPROM: 1 KB
Flash: 32 KB

Computer Music, Fabio Antonacci


The Arduino UNO board

Pinout:
• Power: 3.3 V, 5V, 3
Ground, Vin (power
input or output if power
is supplied through the
jack)
• Analog in: 6 pins,
resolution: 10 bits
• SPI interface for SPI
sensors
• 6 Pulse Width
Modulation outputs
• 2 pins for serial TX and
RX(0 and 1)
• 1 reset pin

Computer Music, Fabio Antonacci


The Arduino UNO board

USB connector for


interfacing with PC
(programming and serial
transmission) and power
input

Jack for external power


supply

Computer Music, Fabio Antonacci


The Arduino IDE

Commands
New sketch
Serial Monitor
Verify Upload

Editor

Message window

Computer Music, Fabio Antonacci


The Arduino IDE

• In order to interface Arduino with many sensors/devices,


libraries can be used. Menu: Sketch → Include Library
• New libraries can be added. Menu: Sketch → Include Library
→ Manage Libraries
• Many examples can be found directly in Arduino. Menu: File →
Examples
• The Arduino IDE can work with quite a few different boards.
Menu: Tools → Board
• There is a serial plotter to plot values transmitted on the serial
port. Menu: Tools → Serial Plotter

Computer Music, Fabio Antonacci


Examples: blinking a led

// the setup function runs once when you press reset or power
the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever


void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH
is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by
making the voltage LOW
delay(1000); // wait for a second
}

Computer Music, Fabio Antonacci


Examples: blinking a led

This sketch blinks a led on the pin 13. Connected to the pin 13 there is a
builtin led. When the pin is high the led is on.
The sketch is organized in two main functions: setup and loop.
• Setup runs once when the board is reset
o pinMode(pinNumber, mode) tells the pin identified by
pinNumber to work as input or output through the rest of
the sketch.
o LED_BUILTIN is a constant equal to 13
o mode can be either output or input
• Loop runs continuously.
o digitalWrite(pin, value) tells the pin to switch its level to value.
Value can be HIGH or LOW (predefined constants).
o delay (msec) puts the micro in idle mode for msec
milliseconds.

Computer Music, Fabio Antonacci


Breadboard

In order to easily develop pre-prototypes in Arduino, breadboards


are used.
Signal is copied on all the
pinholes on the two lines.
Typical use: 5V and ground
distribution

Signal is copied on all the


pinholes on the vertical lines
as well. Use: copy the pin
voltages of the sensors

Computer Music, Fabio Antonacci


Examples: controlling a led using PWM

• The resistor (220 Ω) prevents a short circuit on the series resistor and LED.
when the led is on. • The pin 9 is controlled using a PWM signal
• The output of the pin 9 controls the voltage

Computer Music, Fabio Antonacci


Examples: controlling a led using PWM

Pulse Width Modulation

Wikipedia: Pulse-width modulation (PWM), or pulse-duration modulation (PDM), is a


modulation technique used to encode a message into a pulsing signal.
The average value of voltage (and current) fed to the load is controlled by turning the switch
between supply and load on and off at a fast rate. The longer the switch is on compared to
the off periods, the higher the total power supplied to the load.
The term duty cycle describes the proportion of 'on' time to the regular interval or 'period'
of time; a low duty cycle corresponds to low power, because the power is off for most of
the time. Duty cycle is expressed in percent, 100% being fully on.

Computer Music, Fabio Antonacci


Examples: controlling a led using PWM

Schematics of the circuit:

Computer Music, Fabio Antonacci


Examples: controlling a LED using PWM

int led = 9; // the PWM // change the brightness for next


pin the LED is attached to time through the loop:
int brightness = 0; // how brightness = brightness +
bright the LED is fadeAmount;
int fadeAmount = 5; // how many
points to fade the LED by // reverse the direction of the
fading at the ends of the fade:
// the setup routine runs once when if (brightness <= 0 || brightness
you press reset: >= 255) {
void setup() { fadeAmount = -fadeAmount;
// declare pin 9 to be an output: }
pinMode(led, OUTPUT); // wait for 30 milliseconds to
} see the dimming effect
delay(30);
// the loop routine runs over and }
over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);

Computer Music, Fabio Antonacci


Acquiring sensor data with Arduino

• Arduino has digital and analog inputs to be interfaced with a variety


of sensors.
• In addition, also I2C interface is available, which enables the
connection of multiple devices on the same port.
• In this brief introduction we will cover the following types of sensors:
o Pushbutton
o Tilt ball switch
o Potentiometer
o Photoresistor
o Inertial Measurement Unit (IMU, Accelerometer + gyroscope)
o Ultrasonic transceiver
o PIR motion sensor

Computer Music, Fabio Antonacci


Pushbutton
Working principle

The pushbutton is the simplest sensor we can use.


It detects the pressure on a button. Pins A-C and B-D are
connected together. When the button is pressed, the four pins
share the same voltage

Computer Music, Fabio Antonacci


Pushbutton
Schematics

Example of a circuit in Arduino using a pushbutton

When the button is pressed, the pin 2 switches to high. The function
digitalRead can be used to measure the voltage on pin 2. In the next
example, when the button is pressed the builtin led is switched on.

Computer Music, Fabio Antonacci


Pushbutton
Code

const int buttonPin = 2; // the number of the pushbutton pin


const int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}

void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed. If it is, the buttonState is HIGH:


if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

Computer Music, Fabio Antonacci


Tilt ball switch
Working principle

Tilt sensors allow you to detect the


inclination or orientation.
Sensors of this sort are made of a cavity
with a conductive free mass inside, such as
a ball of mercury (not in modern ones), or a
rolling ball. One end of the cavity has two
poles. When the conducting element lies on
this end, it shorts the two poles.

Computer Music, Fabio Antonacci


Tilt ball switch
Schematics

Schematics of the circuit

Computer Music, Fabio Antonacci


Tilt ball switch
Code

const int tiltPin = 6; // Sensor PIN


const int ledPin = 13; // LED Pin
int tiltState = 0; // Sensor state variable

void setup()
{
pinMode(ledPin, OUTPUT); // LED Pin initialization
pinMode(tiltPin, INPUT); // Tsensor Pin initialization
}

void loop()
{
// Reading sensor state
tiltState = digitalRead(tiltPin);

if (tiltState == HIGH)
digitalWrite(ledPin, HIGH); // LED on
else
digitalWrite(ledPin, LOW); // LED off
}

Computer Music, Fabio Antonacci


Potentiometer
Working Principle

A potentiometer is a mechanical
device that provides a varying
amount of resistance when its
shaft is turned. By passing voltage
through a potentiometer and into
an analog input, it is possible to
measure the amount of resistance
produced by a potentiometer as
an analog value.
Note: With respect to the previous
examples, the potentiometer is an
analog sensor

Computer Music, Fabio Antonacci


Potentiometer
Schematics

Very simple schematics of a potentiometer connected to Arduino

Computer Music, Fabio Antonacci


Potentiometer
Code

/*
AnalogReadSerial

Reads an analog input on pin 0, prints the result to the Serial Monitor.
Graphical representation is available using Serial Plotter (Tools > Serial Plotter
menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and
ground.

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/AnalogReadSerial
*/

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

void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}

Computer Music, Fabio Antonacci


Photoresistors
Working principle

The photocell is a light


dependent resistor. It acts as a
resistor, except that the
resistance changes in
response to how much light
impinges on them.
In order to convert this value
into an input, it needs to be
converted into a voltage. The
simplest way to do so is to
combine it with a fixed resistor.

Computer Music, Fabio Antonacci


Photoresistors
Schematics

Example of circuit

Computer Music, Fabio Antonacci


Photoresistors
Code

Blinks a led with a period determined by the photoresistor input


int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
}

void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
}

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Working principle

• Inertial Measurement Units are used to measure orientation,


track movements, detect violent accelerations etc.
• IMU sensors consist of two or more parts among
accelerometer, gyroscope. Possibly also magnetometer and
altimeter are present.
• The GY-521 is one of the most cheap and common IMUs
available on the market. It accommodates a 3-axes
accelerometer, and a gyroscope, both MEMS. It gives six
values as output.
o Both sensors exploit the piezoelectric effect.
o Output is digital with 16 bits of resolution.
o I2C interface is used.

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
SPI interface

I2C is a simplified version of the SPI


protocol. Features:
• 7-bits slave addresses: each device
connected to the bus has got such a
unique address;
• data divided into 8-bit bytes;
• a few control bits for controlling the
communication start, end, direction
and for an acknowledgment
mechanism.
• The data rate has to be chosen
between 100 kbps, 400 kbps and 3.4
Mbps, respectively called standard
mode, fast mode and high speed
mode. Some I²C variants include 10
kbps (low speed mode) and 1 Mbps
(fast mode +) as valid speeds.

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Schematics

Top view of the IMU For its basic use, only the pins
VCC; GND; SCL and SDA are
used.
• VCC is the power input (either
3.3 or 5V is fine);
• GND is the ground;
• SCL

X,Y and Z axes measure the pitch,


roll and yaw, respectively.

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Schematics

Schematics and drawing

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Code

Detecting I2C devices


// i2c_scanner
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
Wire.begin();

Serial.begin(9600);
Serial.println("\nI2C Scanner");
}

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Code

void loop()
{
byte error, address;
int nDevices;

Serial.println("Scanning...");

nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();

if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Code

else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");

delay(5000); // wait 5 seconds for next scan


}

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Code

Reading acceleration values


#include<Wire.h>
const int MPU=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop(){
Wire.beginTransmission(MPU);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true); // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Code

Serial.print("Accelerometer: ");
Serial.print("X = "); Serial.print(AcX);
Serial.print(" | Y = "); Serial.print(AcY);
Serial.print(" | Z = "); Serial.println(AcZ);
//equation for temperature in degrees C from datasheet
Serial.print("Temperature: ");
Serial.print(Tmp/340.00+36.53); Serial.println(" C ");

Serial.print("Gyroscope: ");
Serial.print("X = "); Serial.print(GyX);
Serial.print(" | Y = "); Serial.print(GyY);
Serial.print(" | Z = "); Serial.println(GyZ);
Serial.println(" ");
delay(333);
}

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Code

Reading pitch, roll and yaw


#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Pitch, Roll and Yaw values


int pitch = 0;
int roll = 0;
float yaw = 0;

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

Serial.println("Initialize MPU6050");

while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}

// Calibrate gyroscope. The calibration must be at rest.


// If you don't want calibrate, comment this line.
mpu.calibrateGyro();

// Set threshold sensivty. Default 3.


// If you don't want use threshold, comment this line or set 0.
mpu.setThreshold(1);

// Check settings
checkSettings();
}

Computer Music, Fabio Antonacci


Inertial Measurement Unit (accelerometer + gyroscope)
Code

Reading pitch, roll and yaw (cont’d)


void loop()
{
// Read normalized values
Vector normAccel = mpu.readNormalizeAccel();
Vector normGyro = mpu.readNormalizeGyro();

// Calculate Pitch & Roll


pitch = -(atan2(normAccel.XAxis, sqrt(normAccel.YAxis*normAccel.YAxis +
normAccel.ZAxis*normAccel.ZAxis))*180.0)/M_PI;
roll = (atan2(normAccel.YAxis, normAccel.ZAxis)*180.0)/M_PI;

//Ignore the gyro if our angular velocity does not meet our threshold
if (normGyro.ZAxis > 1 || normGyro.ZAxis < -1) {
normGyro.ZAxis /= 100;
yaw += normGyro.ZAxis;
}

//Keep our angle between 0-359 degrees


if (yaw < 0)
yaw += 360;
else if (yaw > 359)
yaw -= 360;

// Output
Serial.print("Pitch = ");
Serial.print(pitch);
Serial.print("\tRoll = ");
Serial.print(roll);
Serial.print("\tYaw = ");
Serial.print(yaw);

Serial.println();

delay(10);
}

Computer Music, Fabio Antonacci


Ultrasonic transceiver
Working principle and applications

Ultrasonic transceiver is used for many applications that need


measurement of distance.
It is based on a transmitter and a receiver. The time of flight of the
ultrasonic pulse is computed in Arduino and can be used for
many different applications.
Example related to computer music: Theremin-like instruments.

Computer Music, Fabio Antonacci


Ultrasonic transceiver
Schematics

Computer Music, Fabio Antonacci


Ultrasonic transceiver
Code

const int trigPin = 9;


const int echoPin = 10;

float duration, distance;

void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT); pulseIn function: reads a pulse (either HIGH or
Serial.begin(9600);
} LOW) on a pin. For example, if value is HIGH,
pulseIn() waits for the pin to go HIGH, starts
void loop() {
digitalWrite(trigPin, LOW); timing, then waits for the pin to go LOW and
delayMicroseconds(2); stops timing.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); Returns the length of the pulse in
digitalWrite(trigPin, LOW); microseconds.
duration = pulseIn(echoPin, HIGH); Gives up and returns 0 if no pulse starts within
distance = (duration*.0343)/2; a specified time out.
Serial.print("Distance: ");
Serial.println(distance);
delay(100);
}

Computer Music, Fabio Antonacci


PIR motion sensor
Working principle

PIR sensors allow you to sense motion, almost always used to


detect whether a human has moved in or out of the sensors
range.
PIRs are basically made of a pyroelectric sensor (which you can
see below as the round metal can with a rectangular crystal in the
center), which can detect levels of infrared radiation.

Computer Music, Fabio Antonacci


PIR motion sensor
Pinout

Pin or Control Function


Time Delay Adjust Sets how long the output remains high
after detecting motion. Anywhere from 5
seconds to 5 minutes.

Sensitivity Adjust Sets the detection range.... from 3 meters


to 7 meters
Trigger Selection Jumper Set for single or repeatable triggers.
Ground pin Ground input
Output Pin Low when no motion is detected.. High
when motion is detected. High is 3.3V

Power Pin 5 to 20 VDC Supply input

Computer Music, Fabio Antonacci


PIR motion sensor
Schematics

Computer Music, Fabio Antonacci


PIR motion sensor
Code

int ledPin = 13; // LED on Pin 13 of Arduino


int pirPin = 7; // Input for HC-S501

int pirValue; // Place to store read PIR Value

void setup() {

pinMode(ledPin, OUTPUT);
pinMode(pirPin, INPUT);

digitalWrite(ledPin, LOW);
}

void loop() {
pirValue = digitalRead(pirPin);
digitalWrite(ledPin, pirValue);

Computer Music, Fabio Antonacci


Interfacing with Arduino

The output used in Arduino is the Serial stream.


The serial stream is nothing but a series of ASCII characters.
In order to interface with Arduino, in SuperCollider we need to
• Open the SerialPort;
• Convert ASCII characters to numbers.

These two steps are discussed in the next slides.

Computer Music, Fabio Antonacci


Opening a Serial Port

At first, we need to list all the serial port devices available.


To do so, use
SerialPort.devices;
Result on the post window:
[/dev/tty.Bluetooth-Incoming-Port,
/dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411]
Once Arduino is connected to the PC, it will be visible as a device
like the bold one.

Computer Music, Fabio Antonacci


Opening a Serial Port

To open a specific serial port device, use


~port = SerialPort.new("/dev/tty.usbmodem1411",
9600);
The second number is the baud rate of the connection. You must
use a rate that is compatible with the Arduino board.
Important note: the Arduino IDE must be closed when
SuperCollider is trying to access the serial port.

Computer Music, Fabio Antonacci


Acquiring data from the Serial Port

(
~charArray = [ ];
~getValues = Routine.new(
{ var ascii;
{ascii = ~port.read.asAscii;
if(ascii.isDecDigit,{~charArray =
~charArray.add(ascii)});
if(ascii == $a,{
~val1=
~charArray.collect(_.digit).convertDigits
;
~charArray = [ ];
});
}.loop;}
).play;)

Computer Music, Fabio Antonacci


Acquiring data from the serial port

In the previous script individual output values are separated by


the “a” character.
Once this routine is available, it must be executed continuously to
update the parameter to be controlled by the Arduino board.

Computer Music, Fabio Antonacci


Example: saw signal controlled by ultrasonic transceiver

Goal: control the fundamental frequency of a saw signal using


the distance from an ultrasonic transceiver

Computer Music, Fabio Antonacci


Example: saw signal controlled by ultrasonic transceiver

#include <NewPing.h> delay(50); // Wait 50ms between pings


#define TRIGGER_PIN 10 // Arduino pin (about 20 pings/sec). 29ms should be
tied to trigger pin on the ultrasonic the shortest delay between pings.
sensor. unsigned int uS = sonar.ping(); //
#define ECHO_PIN 9 // Arduino pin tied Send ping, get ping time in
to echo pin on the ultrasonic sensor. microseconds (uS).
#define MAX_DISTANCE 400 // Maximum ValueDist = uS / US_ROUNDTRIP_CM;
distance we want to ping for (in if (ValueDist == 0)
centimeters). Maximum sensor distance {
is rated at 400-500cm. ValueDist = prevValueDist;
}
NewPing sonar(TRIGGER_PIN, ECHO_PIN, else
MAX_DISTANCE);
{
int SetDistance = 0; prevValueDist = ValueDist;
int ValueDist = 0; }
int prevValueDist = 0; Serial.print(ValueDist); // Convert
ping time to distance in cm and print
void setup() { result (0 = outside set distance
Serial.begin(9600); range)
} Serial.print("a");

void loop() { }

Computer Music, Fabio Antonacci


Example: saw signal controlled by ultrasonic transceiver

Synth definition:
(
SynthDef.new("theremin_ultrasonic",{arg
fund_freq=440;
var sig = Saw.ar(fund_freq,0.2,0);
Out.ar(0,Pan2.ar(sig,0,1))}).send(s);
)
~t =
Synth("theremin_ultrasonic",["fund_freq",~val1.l
inlin(0,90,110,880)]);
The method linlin maps linearly the values in ~val1 in the range
[0,90] to the output range [110,880]. Similarly, the linexp method
performs an exponential mapping.

Computer Music, Fabio Antonacci


Example

Update of the parameter:


(~control = Routine.new({ {
~t.set(\fund_freq,~val1.linlin(0,90,110,880,8
80)); 0.01.wait;
}.loop;}
).play;)

Computer Music, Fabio Antonacci


Another example

Goal: control the fundamental


frequency of a variable duty saw
signal through a photoresistor,
and the panning of the signal
through a potentiometer.
Features: this time two
parameters are transmitted
through the serial port.

Computer Music, Fabio Antonacci


Another example

Arduino script {
if (sensorValue1 < sensorLow)
int sensorValue1 = 0;
sensorLow = sensorValue1;
int sensorValue2 = 0;
}
int sensorLow = 1023;
}
int sensorHigh = 0;
}
int temp;
void loop() {
void setup() {
temp = analogRead(A5);
Serial.begin(9600);
sensorValue1 = temp;
sensorValue2 = analogRead(A4);
while(millis()<5000)
Serial.print(temp);
{
Serial.print("a");
sensorValue1 = analogRead(A5);
Serial.print(sensorValue2);
if (sensorValue1 > sensorHigh)
{ Serial.print("b");
sensorHigh = sensorValue1; delay(10);
} }
// record the minimum sensor
value

Computer Music, Fabio Antonacci


Another example

(~charArray = [ ];
~getValues = Routine.new(
{ var ascii;
{ ascii = ~port.read.asAscii;
if(ascii.isDecDigit,{~charArray =
~charArray.add(ascii)});
if(ascii == $a,{
~val1= ~charArray.collect(_.digit).convertDigits;
~charArray = [ ]; });
if(ascii == $b,{
~val2 =
~charArray.collect(_.digit).convertDigits;~charArr
ay = [ ]; });
}.loop;}
).play;
)

Computer Music, Fabio Antonacci


Another example

Synth definition and creation:

(SynthDef.new("signal",
{
arg fundamental = 200,pan = 0;
var harmonics = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var sig = VarSaw.ar(LFPulse.kr(3, 0, 0.3,
fundamental,
fundamental*1.5),0,LFTri.kr(1.0).range(0,1),
0.1); Out.ar(0,Pan2.ar(sig,pan));}).add;)

~synth = Synth("signal");

Computer Music, Fabio Antonacci


Another example

Mapping of the variables onto the ~synth parameters:

(~control = Routine.new({ {
~synth.set(\fundamental,~val1.linexp(0,200,11
0,880,880),\pan,~val2.linlin(0,1023,-1,1,1));
0.05.wait;
}.loop;}
).play;
)

Computer Music, Fabio Antonacci

You might also like