dilluns, 7 de juliol del 2014

8bit pseudo-theremin (4): afegir un led bicolor per indicar el tempo

A l'article anterior vaig afegir un potenciòmetre per indicar el tempo. El problema és que no hi havia cap indicador visual del tempo actual. Per aquest motiu he decidit afegir un led de dos colors per indicar-ho.

Esquema del circuit

El codi no canvia gaire, a nivell bàsic s'ha afegit un vector amb dos pins (led vermell, led verd) i es va activant o desactivant depenent del cicle on s'estigui.


/*
 Translate HC-SR04 Ping distance sensor into buzzer tone with a potentiometer tempo
 
 Author: Ferran Recio
 This code is part of the project 8bit pseudo-theremin (http://laveudet.blogspot.com.es/2014/07/pseudo-theremin-8bits-part-0.html)
 
 Code based on:
 
 HC-SR04 Ping distance code by ScottC here: http://arduinobasics.blogspot.com.au/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html
 buzzer tutorial here:  http://arduino.cc/en/Tutorial/Tone
 
 on 04 Jul 2014.
 */

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED
 
int potenPid = A1;

int buzzerPin = 10;
int buzztone = 0;

//buzzer tone range
int maxbuzztone = 2500;//4978;
int minbuzztone = 1;

int maximumRange = 30; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance

//marcador de tempo
int tempo[] = {2,3};//leds
int currled = 0;

int delayval = 25;


void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
  pinMode(buzzerPin, OUTPUT);   // sets the pin as output
  
  int i;
  for (i = 0; i < 2; i = i + 1) {
    pinMode(tempo[i], OUTPUT);
  }
  
}

void loop() {
  /* The following trigPin/echoPin cycle is used to determine the
   distance of the nearest object by bouncing soundwaves off of it. */ 
   digitalWrite(trigPin, LOW); 
   delayMicroseconds(2);
  
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(10); 
   
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   
   //Calculate the distance (in cm) based on the speed of sound.
   distance = duration/58.2;
   
   if (distance >= maximumRange || distance <= minimumRange){
     //Serial.println("-1");
     digitalWrite(LEDPin, LOW);
     noTone(buzzerPin);
   }
   else {
     digitalWrite(LEDPin, HIGH);
     
     buzztone = map(distance, minimumRange, maximumRange, minbuzztone, maxbuzztone);
     buzztone = maxbuzztone - buzztone;
     
     tone(buzzerPin,buzztone);
   }
   
   //tempo
   if (currled==0) {
    currled = 1;
    digitalWrite(tempo[0], HIGH);
    digitalWrite(tempo[1], LOW);
   } else {
    currled = 0;
    digitalWrite(tempo[0], LOW);
    digitalWrite(tempo[1], HIGH);
   }

   
   //pillem el delay
   delayval = analogRead(potenPid);
   delay(delayval+1);
}

Aquest el vídeo de l'efecte: