martes, 9 de febrero de 2010

Simulación coche fantástico

Vamos a crear una simulación del coche fantástico. Para ello utilizaremos diez LEDs colocados en linea, un timbre y un botón.
El programa comenzará a encender LEDs en orden y el timbre sonará cada vez que se enciendan y apaguen los 10 LEDs.
Con el botón haremos que se encienda y apague el sistema a como si de un interruptor se tratara.

El circuito lo implementaremos así:

Lado + de cada LED a los pines del 4 al 13 (digital)
Lado - de cada LED a ground

Lado + botón a +5V
Lado + botón al pin 2 (digital)
Lado - boton a ground

Lado + timbre a pin 3
Lado - timbre a ground





//Simularemos las luces del coche fantástico con 10 LEDs colocados en línea, mientras los LEDs estén encendidos haremos sonar el timbre.
const int pinesLed[]={4,5,6,7,8,9,10,11,12,13};
const int pinBoton=2;
const int speakerPin=3;

int aux=0;
int i=0;
int j=0;
int contadorBoton=0;
int lastState=0;
int state=0;

int ultimoTiempo=0;
int tiempo=690;
int ultimoTiempo2=0;
int tiempo2=40;

int length=19;
char notes[]="cdegcdefCefgCabCebC";

void playTone(int tone, int duration)
{
for (long j=0; j {
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 };
for (i=0; i<8; i++)
{
if (names[i] == note)
{
playTone(tones[i], duration);
}
}
}

void setup()
{
for(i=0; i<10; i++)
{
pinMode(pinesLed[i], OUTPUT);
}
pinMode(pinBoton, INPUT);
pinMode(speakerPin, OUTPUT);
}

void loop()
{
if(contadorBoton%2==1)
{
while(contadorBoton%2==1)
{
j=0;
for(i=0; i<10; i++)
{
state=digitalRead(pinBoton);
if(state!=lastState)
{
if(state==HIGH)
{
contadorBoton++;
}
lastState=state;
}
if(millis()-ultimoTiempo>tiempo)//Cada 'tiempo' controlamos el valor del sensor
{
ultimoTiempo=millis();
playNote(notes[i], 10);
}
digitalWrite(pinesLed[j], HIGH);
j+=1;
delay(30);
}
j=0;
i=10;
for(i=10; i>=0; i--)
{
state=digitalRead(pinBoton);
if(state!=lastState)
{
if(state==HIGH)
{
contadorBoton++;
}
lastState=state;
}
if(millis()-ultimoTiempo>tiempo)//Cada 'tiempo' controlamos el valor del sensor
{
ultimoTiempo=millis();
playNote(notes[i], 10);
}
digitalWrite(pinesLed[j], LOW);
j+=1;
delay(30);
}
}
}
if(contadorBoton%2==0)
{
for(i=10; i>=0; i--)
{
digitalWrite(pinesLed[i], LOW);
}
}
}

No hay comentarios:

Publicar un comentario