Distance Sensor & NeoPixel

For this week, I assembled together a distance sensor with a NeoPixel light display, with the lights extending out the closer the user had his hand to the distance sensor.

I wanted to start working with some equipment/code we used for past projects, in preparation for the final project for TUI.

I wanted to try connecting output through the Serial Monitor to Ableton Live, but couldn’t get that piece to work just yet. I attached the Piezo speaker to make a clicking sound every time an object (etc. my hand) was detected.

Some useful resources for others doing similar things in the class:
MIDI controller output through arduino – http://forum.arduino.cc/index.php/topic,22336.0.html

https://youtu.be/HZ-NZvULZiU

/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
Red POS to Arduino pin 11
Green POS to Arduino pin 10
560 ohm resistor to both LED NEG and GRD power rail
More info at: http://goo.gl/kJ8Gl
Original code improvements to the Ping sketch sourced from Trollmaker.com
Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
*/

#include <Adafruit_NeoPixel.h>

#define trigPin 13
#define echoPin 12
int speakerPin = 7;
 int velocity = 100;//velocity of MIDI notes, must be between 0 and 127
 //higher velocity usually makes MIDI instruments louder
 
 int noteON = 144;//144 = 10010000 in binary, note on command
 int noteOFF = 128;//128 = 10000000 in binary, note off command

#define PIN 6
 
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  Serial.begin (31250);
  pinMode(speakerPin, OUTPUT); 
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

//send MIDI message
void MIDImessage(int command, int MIDInote, int MIDIvelocity) {
  Serial.write(command);//send note on or note off command 
  Serial.write(MIDInote);//send pitch data
  Serial.write(MIDIvelocity);//send velocity data
}

void loop() {
  
  long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  delay(100);
  if (distance < 43) {  // This is where the LED On/Off happens

    long k = distance % 7;
    long k2 = 6-k; 

  
  
    for( int i=0; i<5; i++ ) {  // play it for 50 cycles
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(1);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(1);
  }
    int j;
    //Serial.println("on stage"); 
    for(j=0;j<k2+1;j++) {
      //Serial.print("on: ");
      //Serial.println(j);
    strip.setPixelColor(j, random(0,255),random(0,255),random(0,255));   
        
strip.show();
    };
    ////Serial.println("off stage"); 
    for(j=k2;j>k-1;j--){
      //Serial.print("off: ");
      //Serial.println(j);
    strip.setPixelColor(j, 0,0,0);    
        
strip.show(); 
    }
     

}
else {
  //Serial.println("external off stage"); 
  int j; 
 for(j=0;j<7;j++){
      //Serial.print("off: ");
      //Serial.println(j);
    strip.setPixelColor(j, 0,0,0);    
        
strip.show(); 
    }
    
};
  
}

 

 

 

 

Twinkle Twinkle little star

Description

I have tried to build a circuit which plays the children’s poem Twinkle Twinkle little star when the light is shining on the piezo electric light sensor. This can be used in children’s books where the poem starts playing as soon as the child turns to a particular page.

Components

Arduino Board
Bread board
Piezo speaker
Wires
Photocell

int speakerPin = 3;
int potPin = 0;
int val = 0;

int length = 15; // the number of notes

//twinkle twinkle little star
char notes[] = "ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc "; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;

void playTone(int tone, int duration) {
  for (long i = 0; i < duration * 1000L; i += tone * 2) {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
  }
}

void playNote(char note, int duration) {
  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
  
  // play the tone corresponding to the note name
  for (int i = 0; i < 8; i++) {
    if (names[i] == note) {
      playTone(tones[i], duration);
    }
  }
}

void setup() {
  pinMode(speakerPin, OUTPUT);
}

void loop() {
  digitalWrite(speakerPin, LOW);
  val = analogRead(potPin);    // read value from the sensor
  val = val*2;                 // process the value a little
  //val = val/2; 
  
  for (int i = 0; i < length; i++) {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(val);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(val);
    if (notes[i] == ' ') {
      delay(beats[i] * tempo); // rest
    } else {
      playNote(notes[i], beats[i] * tempo);
    }
    
    // pause between notes
    delay(tempo / 2); 
  }
}

Party Box

Is it true that Arduinos were designed to fit inside Altoids cans? I may have just remembered that, or I may have just made it up, but how perfectly they fit! To celebrate how well they fit I’ve designed a party box: when the Altoids can is opened, the party ensues; when it is closed, the party ceases.

 

Materials:

Altoids can

Arduino Uno

3 LED lights

1 320 Ohm resistor

1 10k Ohm resistor

Wires

Tape

Piezo buzzer

 

Code:

/* Theremin
* ——–
*
*
* Created 24 October 2006
* copyleft 2006 Tod E. Kurt &lt;tod@nulltodbot.com
* http://todbot.com/
*/

int potPin = 0; // select the input pin for the potentiometer
int speakerPin = 7;

int val = 0;

int redPin = 9; // Red LED, connected to digital pin 9
int grnPin = 10; // Green LED, connected to digital pin 10
int bluPin = 11; // Blue LED, connected to digital pin 11

int redVal = 0; // Variables to store the values to send to the pins
int grnVal = 0;
int bluVal = 0;

int ramdred = 0;
int ramdblu = 0;
int ramdgrn = 0;

void setup() {
pinMode(speakerPin, OUTPUT);
pinMode(redPin, OUTPUT); // sets the pins as output
pinMode(grnPin, OUTPUT);
pinMode(bluPin, OUTPUT);
Serial.begin(9600);
Serial.println(“ready”);
}

void loop() {
digitalWrite(speakerPin, LOW);

val = analogRead(potPin); // read value from the sensor
val = val*2; // process the value a little
//val = val/2; // process the value a little
ramdred = random(0, 250);
ramdblu = random(0, 250);
ramdgrn = random(0, 250);

if (val > 0){
for( int i=0; i<50; i++ ) { // play it for 50 cycles
analogWrite(redPin, ramdred);
analogWrite(grnPin, ramdblu);
analogWrite(bluPin, ramdgrn);
digitalWrite(speakerPin, HIGH);
delayMicroseconds(val);
digitalWrite(speakerPin, LOW);
delayMicroseconds(val);
};
}
else {
analogWrite(redPin, 0);
analogWrite(grnPin, 0);
analogWrite(bluPin, 0);
delay(10);
};
Serial.print(val);
Serial.println();
};

Video:

https://youtu.be/ZeF2XRpKqaw

 

20161005_001028 20161005_001023 20161005_001045

Ode to Joy (While In Space)

I continued with what I made with my last lab. I want to incorporated music into the visual I made. So I worked on making Processing and Arduino to talk to each other by establishing a handshake between them.

Now, I can use my FSR to control the gravity of the bouncing balls. And Processing will process the gravity values into 0 and 1 and feed it back to Arduino. Arduino will control the speed of the music. The music being played is Ode to Joy. The music will play slower when gravity is set to zero!

Arduino Code


/* Photocell simple testing sketch. 
 
Connect one end of the photocell to 5V, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground 
Connect LED from pin 11 through a resistor to ground 
For more information see http://learn.adafruit.com/photocells */
 
int photocellPin = 0;     // the cell and 10K pulldown are connected to a0
int photocellReading;     // the analog reading from the sensor divider
int LEDpin = 11;          // connect Red LED to pin 11 (PWM pin)
int LEDbrightness;        // 
int val;
int buzzerPin = 7;
#define NOTE_C6 1047
#define NOTE_D6 1157
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_G6 1568
#define NOTE_A6 1760
#define NOTE_B6 1976
#define NOTE_C7 2093

void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);   
  establishContact();  // send a byte to establish contact until receiver responds 
}
 
void loop(void) {
  photocellReading = analogRead(photocellPin);
  
  // LED gets brighter the darker it is at the sensor
  // that means we have to -invert- the reading from 0-1023 back to 1023-0
  photocellReading = 1023 - photocellReading;
  //now we have to map 0-1023 to 0-255 since thats the range analogWrite uses
//  LEDbrightness = map(photocellReading, 0, 1023, 255, 0);
//  analogWrite(LEDpin, LEDbrightness);
  Serial.println(photocellReading);
  delay(100);
   if (Serial.available()>0) 
   { // If data is available to read,
     val = Serial.read(); // read it and store it in val
   }
   if (val == '1') 
   { 
    tone(buzzerPin, NOTE_A6, 100);
    delay(100);
    tone(buzzerPin, NOTE_A6, 100);
    delay(100);
    tone(buzzerPin, NOTE_B6, 100);
    delay(100);
    tone(buzzerPin, NOTE_G6, 100);
    delay(100);
    tone(buzzerPin, NOTE_A6, 100);
    delay(100);
    tone(buzzerPin, NOTE_B6, 100);
    delay(100);
    tone(buzzerPin, NOTE_C7, 100);
    delay(100);
    tone(buzzerPin, NOTE_B6, 100);
    delay(100);
    tone(buzzerPin, NOTE_G6, 100);
    delay(100);
    tone(buzzerPin, NOTE_A6, 100);
    delay(100);
    tone(buzzerPin, NOTE_B6, 100);
    delay(100);
    tone(buzzerPin, NOTE_C7, 100);
    delay(100);
    tone(buzzerPin, NOTE_B6, 100);
    delay(100);
    tone(buzzerPin, NOTE_A6, 100);
    delay(100);
    tone(buzzerPin, NOTE_G6, 100);
    delay(100);
    tone(buzzerPin, NOTE_A6, 100);
    delay(100);
   } else {
    tone(buzzerPin, NOTE_A6, 100);
    delay(200);
    tone(buzzerPin, NOTE_A6, 100);
    delay(200);
    tone(buzzerPin, NOTE_B6, 100);
    delay(200);
    tone(buzzerPin, NOTE_G6, 100);
    delay(200);
    tone(buzzerPin, NOTE_A6, 100);
    delay(200);
    tone(buzzerPin, NOTE_B6, 100);
    delay(200);
    tone(buzzerPin, NOTE_C7, 100);
    delay(200);
    tone(buzzerPin, NOTE_B6, 100);
    delay(200);
    tone(buzzerPin, NOTE_G6, 100);
    delay(200);
    tone(buzzerPin, NOTE_A6, 100);
    delay(200);
    tone(buzzerPin, NOTE_B6, 100);
    delay(200);
    tone(buzzerPin, NOTE_C7, 100);
    delay(200);
    tone(buzzerPin, NOTE_B6, 100);
    delay(200);
    tone(buzzerPin, NOTE_A6, 100);
    delay(200);
    tone(buzzerPin, NOTE_G6, 100);
    delay(200);
    tone(buzzerPin, NOTE_A6, 100);
    delay(200);
   }
}

  void establishContact() {
    while (Serial.available() <= 0) {
    Serial.println("A");   // send a capital A
    delay(300);
    }
  }

Processing Code


import processing.serial.*;
import processing.sound.*;

// Change this to the portname your Arduino board
String portname =  "/dev/cu.usbmodem1411"; // or "COM5"
Serial port;
String buf="";
int cr = 13;  // ASCII return   == 13
int lf = 10;  // ASCII linefeed == 10
int SerialVal = 0;
float r = 0;
float g = 0;
float b = 0;

int numBalls = 30;
float spring = 0.05;
float gravity = 0.03;
float friction = -0.9;
Ball[] balls = new Ball[numBalls];

int barWidth = 5;
int lastBar = -1;

// since we're doing serial handshaking, 
// we need to check if we've heard from the microcontroller
boolean firstContact = false;

void setup() {
  size(1500, 800);
  for (int i = 0; i < numBalls; i++) {
    balls[i] = new Ball(random(width), random(height), random(30, 70), i, balls);
  }
  noStroke();
  
  port = new Serial(this, portname, 9600); 
}

void draw() {
  background(r, g ,b);
  for (Ball ball : balls) {
    ball.collide();
    ball.move();
    ball.display();  
  }

  if (keyPressed == true && keyCode == UP) {
      spring += 0.01;
    } else if (keyPressed == true && keyCode == DOWN) {
      spring -= 0.01;
    } else if (keyPressed == true && key == 'r') {
      r += 10;
    } else if (keyPressed == true && key == 'R') {
      r -= 10;
    } else if (keyPressed == true && key == 'g') {
      g += 10;
    } else if (keyPressed == true && key == 'G') {
      g -= 10;
    } else if (keyPressed == true && key == 'b') {
      b += 10;
    } else if (keyPressed == true && key == 'B') {
      b -= 10;
    } else if (keyPressed == true && key == 'S' || key == 's') {
      friction = -0.9;
      spring = 0.05;
      r=0;
      g=0;
      b=0;
    }
    int whichBar = mouseX / barWidth;
    if (whichBar != lastBar) {
      int barX = whichBar * barWidth;
      fill(barX, mouseY, 66);
      rect(barX, 0, barWidth, height);
      lastBar = whichBar;
    }
}

class Ball {
  float x, y;
  float diameter;
  float vx = 0;
  float vy = 0;
  int id;
  Ball[] others;
 
  Ball(float xin, float yin, float din, int idin, Ball[] oin) {
    x = xin;
    y = yin;
    diameter = din;
    id = idin;
    others = oin;
  } 
  
  void collide() {
    for (int i = id + 1; i < numBalls; i++) {
      float dx = others[i].x - x;
      float dy = others[i].y - y;
      float distance = sqrt(dx*dx + dy*dy);
      float minDist = others[i].diameter/2 + diameter/2;
      if (distance < minDist) { 
        float angle = atan2(dy, dx);
        float targetX = x + cos(angle) * minDist;
        float targetY = y + sin(angle) * minDist;
        float ax = (targetX - others[i].x) * spring;
        float ay = (targetY - others[i].y) * spring;
        vx -= ax;
        vy -= ay;
        others[i].vx += ax;
        others[i].vy += ay;
      }
    }   
  }
  
  void move() {
    vy += gravity;
    x += vx;
    y += vy;
    if (x + diameter/2 > width) {
      x = width - diameter/2;
      vx *= friction; 
    }
    else if (x - diameter/2 < 0) {
      x = diameter/2;
      vx *= friction;
    }
    if (y + diameter/2 > height) {
      y = height - diameter/2;
      vy *= friction; 
    } 
    else if (y - diameter/2 < 0) {
      y = diameter/2;
      vy *= friction;
    }
  }
  void display() {
    ellipse(x, y, diameter, diameter);
  }
}

// called whenever serial data arrives
void serialEvent(Serial port) {
 int c = port.read();
 if (c != lf && c != cr) {
   buf += char(c);
 }
 if (c == lf) {
   SerialVal = int(buf);
   println("val="+SerialVal);
   gravity = SerialVal/1000;
   println("gravity="+gravity);
   buf = "";
   if (gravity == 0.0) 
   {
     port.write('0');
     println("gravity is zero");
   } else
   {
     port.write('1');
     println("gravity is one");
   }
 }
}

Piezo Phase

Description:
Using a force sensor, an LED and a piezo I tried to control the famous 12-note melody of Steve Reich’s Piano Phase and tried to place it to the studio version. The effect that leads to certain parts of the phrase being highlighted was accentuated by the LED effect.

Components:

  • Arduino Uno
  • 1 Piezo Buzzer
  • 1 Force Sensor Resistor
  • 1 Green LED
  • Green Scotch tape
  • Ping pong ball to diffuse
  • 10K and 220 Ohm resistors
  • Jumper wires

Code:


/* Piezo Phase - inspired by Steve Reich
 *  (to be played along with Piano Phase)
 * ------------
 *
 * Program to play tones depending on the data coming from the serial port.
 *
 * The calculation of the tones is made following the mathematical
 * operation:
 *
 *       timeHigh = 1/(2 * toneFrequency) = period / 2
 *
 * where the different tones are described as in the table:
 * 
 * Piano Phase notes:
 * 
 * E4 F♯4 B4 C♯5 D5 F♯4 E4 C♯5 B4 F♯4 D5 C♯5
 * 
 * Updated table below (thanks Tod Kurt):
 *
 * note   frequency   PW (timeHigh)  
 * E4     329.63 Hz   1516.85   
 * F#4    369.99 Hz   1351.38   
 * B4     493.88 Hz   1012.39   
 * C#5    554.37 Hz   901.92   
 * D5     587.30 Hz   851.35 
 * 
 * Transposed
 * note   frequency   PW (timeHigh)  
 * E4     349.228 Hz   1432   
 * F#4    391.995 Hz   1276   
 * B4     523.251 Hz   956   
 * C#5    587.330 Hz   851   
 * D5     622.254 Hz   804 
 * 
 * Transposing to one-step lower
 * Base code by Tod E. Kurt <tod@todbot.com> to use new Serial. commands
 * and have a longer cycle time.
 */

int speakerPin = 13;
int ledPin = 7;

int fsrPin = A0;
int fsrReading;

int length = 12; // the number of notes

char notes[] = "EFBcdFEcBFdc";

int beats[] = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};

//bool toggle = HIGH;

float tempo = 96.1538461538;

// everything good till here

void playTone(int tone, int duration){
  
  for (long i = 0; i < duration * 1000L; i += tone*2){
    digitalWrite(ledPin, HIGH);
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(ledPin, LOW);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
  }
}

void playNothing(){
//  toggle = LOW;
  // this means that the melody is stopped
  digitalWrite(ledPin, LOW);
  digitalWrite(speakerPin, LOW);
}

void playNote(char note, int duration){
//  toggle = HIGH;
  // this means that the melody is running

  char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',           

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

  int tones[] = { 1915, 1700, 1432, 1276, 1275, 1136, 956,

                 851,  804,  765,  593,  468,  346,  224,

                 655 , 715 };

  int SPEED = 5;

  for (int i = 0; i < 12; i++){
    if (names[i] == note){
      int newduration = duration/SPEED;
      playTone(tones[i], newduration);
    }
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(speakerPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  fsrReading = analogRead(fsrPin);
  Serial.print("FSR Reading: ");
  Serial.print(fsrReading);
  Serial.print("\n");
//
//  Serial.print("Toggle: ");
//  Serial.print(toggle);
//  Serial.print("\n");

//  while (fsrReading > 200){
//    toggle = !toggle;
//  }
  
  if (fsrReading > 300){
        for (int i = 0; i < length; i++) {
          if (notes[i] == ' ') {
            delay(beats[i] * tempo); // rest
          } 
   
          else {
            playNote(notes[i], beats[i] * tempo);
          }
        
        delay(tempo);
        }
  }
}

Video link

Handshake

Description

We must have heard people defining various intensities of handshakes. Some say that a handshake was “mellow” and some say it was “warm”. Well, these terms sound pretty vague as they are subjective. It’s time to bring in a device that actually measures how strong was your handshake. I used a Force Sensitive Resistor on a glove to measure how hard the handshake was. The way people would be able to measure this “hardness” is by seeing the color change of the LED on the glove and the sound of the speaker. The harder the handshake, the higher the frequency. It was a difficult task to find out the exact spot on the hand that would measure the intensity appropriately. Light handshakes might not involve the touch of palms, so the FSR had to be placed somewhere, where there is a definite contact. I figured it out to be the tip of the index finger.

Components

  • 1 Arduino Uno R3
  • 1 Piezo Speaker
  • 1 Force Sensitive Resistor
  • 3 LEDs
  • 1 Glove (woolen)

Code

 

// The three primary colour LEDs, driven as analogue outputs (actually PWM, but
// close enough for our analogue eyes).

const int ledPinRed = 11; // Red LED connected to analogue out pin
const int ledPinGrn = 10; // Green LED connected to analogue out pin
const int ledPinBlu = 9; // Blue LED connected to analogue out pin
const int piezoPin = 7;

// The Brightness potentiometer goes on an analogue pin, taking the pin from
// 0V to 5V.

const int fsr = 1;

// Constants to define the ranges.

const int hueRedLow = 0;
const int hueRedHigh = 255;
const int hueBlue = 170;

// The size of the angle of one sector (1/6 of a colour wheel), and of a complete
// cycle of the colour wheel.

const int angleMin = 0;
const int angleSector = 60;
const int angleMax = 360;

const int brightMin = 0;
const int brightMax = 255;

//constants to define the range of beats
const int beatsMin = 40;
const int beatsMax = 220;

// Work variables.

// The hue potentiometer value is mapped to the range 0 to 360 (degrees).
int fsrValueHue;

//The brightness potentiometer value is mapped from 0 to 255 (full brightness)
int fsrValueSound;

int hue, brightness;

const int saturation = 255;

// The brightess of each LED (0 to 255).

unsigned int r, g, b;

void setup() {
// Still need to set a baud rate, even for USB.
Serial.begin(9600);

// Set LED pins to output.
pinMode(ledPinRed, OUTPUT);
pinMode(ledPinGrn, OUTPUT);
pinMode(ledPinBlu, OUTPUT);
pinMode(piezoPin , OUTPUT);

// Poteniometer analogue pin is an input.
pinMode(fsr, INPUT);
}

void loop() {

// fsr values are mapped to create a color based on the intensity of the handshake
fsrValueHue = map(analogRead(fsr), 0, 1023, angleMin, angleMax);
// fsr values are mapped to create sound of a particular frequency based on the intensity of the handshake. Lower the intensity, lower the frequency
fsrValueSound = map(analogRead(fsr), 0, 1023, 75, 10000);

// Colour wheel mode (red to red, wrapped around in a cycle).
hue = map(fsrValueHue, angleMin, angleMax, hueRedLow, hueRedHigh);

// Do the conversion.
HSBToRGB(hue, saturation, brightness, &amp;r, &amp;g, &amp;b);

analogWrite(ledPinRed, r);
analogWrite(ledPinGrn, g);
analogWrite(ledPinBlu, b);
digitalWrite(piezoPin , fsrValueSound);
}

// This function taken from here:
// http://eduardofv.com/read_post/179-Arduino-RGB-LED-HSV-Color-Wheel-

void HSBToRGB(
unsigned int inHue, unsigned int inSaturation, unsigned int inBrightness,
unsigned int *oR, unsigned int *oG, unsigned int *oB )
{
if (inSaturation == 0)
{
// achromatic (grey)
*oR = *oG = *oB = inBrightness;
}
else
{
unsigned int scaledHue = (inHue * 6);
unsigned int sector = scaledHue &gt;&gt; 8; // sector 0 to 5 around the color wheel
unsigned int offsetInSector = scaledHue - (sector &lt;&lt; 8); // position within the sector unsigned int p = (inBrightness * ( 255 - inSaturation )) &gt;&gt; 8;
unsigned int q = (inBrightness * ( 255 - ((inSaturation * offsetInSector) &gt;&gt; 8) )) &gt;&gt; 8;
unsigned int t = (inBrightness * ( 255 - ((inSaturation * ( 255 - offsetInSector )) &gt;&gt; 8) )) &gt;&gt; 8;

switch( sector ) {
case 0:
*oR = inBrightness;
*oG = t;
*oB = p;
break;
case 1:
*oR = q;
*oG = inBrightness;
*oB = p;
break;
case 2:
*oR = p;
*oG = inBrightness;
*oB = t;
break;
case 3:
*oR = p;
*oG = q;
*oB = inBrightness;
break;
case 4:
*oR = t;
*oG = p;
*oB = inBrightness;
break;
default: // case 5:
*oR = inBrightness;
*oG = p;
*oB = q;
break;
}
}
}
 

gloves

Colorful sounds!

Components: 7 LDRs 7 x 10KΩ resists Jumper wires USB cable Computer Arduino Uno Breadboard Description For a while now I have been wanting to combine sounds and colors, so this assignment was the perfect opportunity to do so. I … Continue reading

Lab 5: Coincidential Input/Output

I hooked up the computer that would have been the output for the Processing code to a small pico projector and placed it in a box. I cut the top of the box off and replaced it with a translucent material (waxed paper) so that the top of the box is effectively a small rear-projection screen.

I placed a mirror in the end of the box, opposite the pico projector so that the image would be reflected up 90 degrees. Also in the box are the Arduino and a photocell resistor. When one waves a source of light over the box where the photocell is, the Processing graphics on the box moves in response.

 

Components:

1 Arduino

1 breadboard

1 pico projector

1 photocell resistor

10-ohm resistor

cables

cardboard box

small mirror

waxed paper

tape

computer

 

code

Arduino:

int potPin = 0; // Analog input pin that the potentiometer is attached to
int potValue = 0; // value read from the pot
int ledR = 9; // PWM pin that the LED is on. n.b. PWM 0 is on digital pin 9
int ledG = 10; // PWM pin that the LED is on. n.b. PWM 0 is on digital pin 9
int ledB = 11; // PWM pin that the LED is on. n.b. PWM 0 is on digital pin 9
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
// declare the led pin as an output:
pinMode(ledR, OUTPUT);
pinMode(ledG, OUTPUT);
pinMode(ledB, OUTPUT);
}

void loop() {
potValue = analogRead(potPin); // read the pot value
analogWrite(ledR, potValue/4); // PWM the LED with the pot value (divided by 4 to fit in a byte)
analogWrite(ledG, potValue/4); // PWM the LED with the pot value (divided by 4 to fit in a byte)
analogWrite(ledB, potValue/4); // PWM the LED with the pot value (divided by 4 to fit in a byte)
Serial.println(potValue); // print the pot value back to the debugger pane
delay(10); // wait 10 milliseconds before the next loop
}

Processing:
import processing.serial.*;
// Change this to the portname your Arduino board
String portname = “/dev/cu.usbmodem1421”; // or “COM5″
Serial port;
String buf=””;
int cr = 13; // ASCII return == 13
int lf = 10; // ASCII linefeed == 10

int serialVal = 0;

void setup() {
size(1280,720);
frameRate(10);
smooth();
background(255,255,255);
noStroke();
port = new Serial(this, portname, 9600);
}

void draw() {
// erase the screen
background(0, 0, 0);

// draw the ball
noFill();
stroke(200);
strokeWeight(.5);
line(150,serialVal,serialVal,100);
line(100,serialVal,serialVal,150);
ellipse(serialVal, serialVal, 50 + serialVal, 50 + serialVal);

strokeWeight(1);
line(200,serialVal,serialVal,75);
line(75,serialVal,serialVal,200);
ellipse(serialVal, serialVal, serialVal, serialVal);

strokeWeight(2);
line(250,serialVal,serialVal,55);
line(55,serialVal,serialVal,250);
ellipse(serialVal, serialVal, serialVal -50, serialVal – 50);

strokeWeight(2.5);
line(300,serialVal,serialVal,35);
line(35,serialVal,serialVal,300);
ellipse(serialVal, serialVal, serialVal -150, serialVal – 150);

strokeWeight(3.5);
line(500,serialVal,serialVal,15);
line(15,serialVal,serialVal,500);

}

// called whenever serial data arrives
void serialEvent(Serial p) {
int c = port.read();
if (c != lf && c != cr) {
buf += char(c);
}
if (c == lf) {
serialVal = int(buf);
println(“potValue=”+serialVal);
buf = “”;
}
}

 

 

6 5 4 3 2 1

Lab 05

Description

I used Arduino with force sensor. I edited the sample melody (twinkle twinkle little star) sketch code to make the piezo buzzer play the meolody and use the force sensor to control the melody’s tempo. With different value detected by the force sensor, the tempo of the melody will change. Also, to make the input and output coincide I attache both the piezo buzzer and force sensor to the android toy. Lastly, I  uploaded the code and took pictures of the result.

Components

  • 1 Arduino
  • 1 Piezo
  • 1 Breadboard
  • 1 force sensor
  • 1 Andoird toy

Code

/*
Connections For this application;
Use Freeduino-RichBoard made by www.EmbeddedMarket.com

1. Connect Digital Pin 9 to Buz pin in Section 9 on Freeduino Board

2. Connect USB Cable

*/

/* Melody
 * (cleft) 2005 D. Cuartielles for K3
 *
 * This example uses a piezo speaker to play melodies. It sends
 * a square wave of the appropriate frequency to the piezo, generating
 * the corresponding tone.
 *
 * The calculation of the tones is made following the mathematical
 * operation:
 *
 * timeHigh = period / 2 = 1 / (2 * toneFrequency)
 *
 * where the different tones are described as in the table:
 *
 * note frequency period timeHigh
 * c 261 Hz 3830 1915 
 * d 294 Hz 3400 1700 
 * e 329 Hz 3038 1519 
 * f 349 Hz 2864 1432 
 * g 392 Hz 2550 1275 
 * a 440 Hz 2272 1136 
 * b 493 Hz 2028 1014 
 * C 523 Hz 1912 956
 *
 * http://www.arduino.cc/en/Tutorial/Melody
 */
 
int speakerPin = 7;
// Do we want debugging on serial out? 1 for yes, 0 for no
//int DEBUG = 1;
int potPin = 2;
int val = 0;

int length = 15; // the number of notes

//twinkle twinkle little star
char notes[] = "ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc "; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 200;

void playTone(int tone, int duration) {
 for (long i = 0; i &lt; duration * 1000L; i += tone * 2) {
 digitalWrite(speakerPin, HIGH);
 delayMicroseconds(tone);
 digitalWrite(speakerPin, LOW);
 delayMicroseconds(tone);
 }
}

void playNote(char note, int duration) {
 char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
 int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
 
 // play the tone corresponding to the note name
 for (int i = 0; i &lt; 8; i++) {
 if (names[i] == note) {
 playTone(tones[i], duration);
 }
 }
}

void setup() {
 pinMode(speakerPin, OUTPUT);
 Serial.begin(9600); // Set serial out if we want debugging
 Serial.println("ready"); 
}

void loop() {
 val = analogRead(potPin); //read value from the sensor
 if (tempo&gt;500){
 tempo = 100;
 } else{
 tempo = tempo+val;
 }

for (int i = 0; i &lt; length; i++) {
 if (notes[i] == ' ') {
 delay(beats[i] * tempo); // rest
 } else {
 playNote(notes[i], beats[i] * tempo);
 }
 
 // pause between notes
 delay(tempo / 2); 
 }
}

//read a string from the serial and store it in an array
//you must supply the array variable
void readSerialString (char *strArray) {
 int i = 0;
 if(!Serial.available()) {
 return;
 }
 while (Serial.available()) {
 strArray[i] = Serial.read();
 i++;
 }
}
hw5

Photosensing Alarm Clock

Description

I wanted to make an alarm clock for people whose activities depend not on the 24 hr clock we use but the sunlight outside. A good example of this could be farmers who schedule taking the animals out, watering crops etc based on how sunny it is. My clock uses a photo sensor and can be programmed to play different alarms depending on the brightness outside. Pressing the off button lightly snoozes the alarm while presses it hard switches off the alarm altogether.

Component

  • Arduino
  • 1 photo sensor
  • 1 FSR
  • 2 10k ohm resistors
  • 1 piezo speaker
  • Bread board
  • Jumper cables

Arduino Code


#include "pitches.h"

int fsrPin = A0;
int pcPin = A1;
int speakerPin = 8;

int fsrVal;
int pcVal;

// alarm 1
int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4};
int noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4};

// alarm 2
int melody2[] = {
NOTE_GS4, NOTE_GS4, NOTE_GS3, NOTE_GS3, NOTE_DS4, NOTE_DS4, NOTE_GS3, NOTE_GS3, NOTE_GS4, NOTE_GS4, NOTE_E4, NOTE_B4, NOTE_FS4, NOTE_FS4, NOTE_FS3, NOTE_FS3};

void setup() {
pinMode(fsrPin, INPUT);
pinMode(pcPin, INPUT);
pinMode(speakerPin, OUTPUT);
Serial.begin(9600);
}

void loop() {

fsrVal = analogRead(fsrPin);
pcVal = analogRead(pcPin);

Serial.print(“FSR Value: “);
Serial.println(fsrVal);
Serial.print(“PC Value: “);
Serial.println(pcVal);

// Afternoon alarm
if (pcVal > 200 && pcVal < 500 && fsrVal < 100 ) {
for (int thisNote = 0; thisNote < 8; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000 / noteDurations[thisNote]; tone(8, melody[thisNote], noteDuration); // to distinguish the notes, set a minimum time between them. // the note’s duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); // stop the tone playing: noTone(8); } } // Dusk alarm if (pcVal > 500 && fsrVal < 100 ) {
for (int thisNote2 = 0; thisNote2 < 16; thisNote2++) { tone(speakerPin, melody2[thisNote2]); delay(200); noTone(speakerPin); } } // Snooze. Have to wait a while for FSR to go back to 0 if (fsrVal > 30 && fsrVal < 800) { delay(800); } // Stop alarm if (fsrVal > 800) {
exit(0);
}

}

fullsizerender