- En la primera práctica hemos conseguido que los led luzcan correctamente y que al pulsar un pulsador parpadeen los led amarillo y rojo.
/*
Arduino Starter Kit example
Project 2 - Spaceship Interface
This sketch is written to accompany Project 2 in the
Arduino Starter Kit
Parts required:
1 green LED
2 red LEDs
pushbutton
10 kilohm resistor
3 220 ohm resistors
Created 13 September 2012
by Scott Fitzgerald
http://arduino.cc/starterKit
This example code is part of the public domain
*/
// Create a global variable to hold the
// state of the switch. This variable is persistent
// throughout the program. Whenever you refer to
// switchState, you’re talking about the number it holds
int switchstate = 0;
void setup(){
// declare the LED pins as outputs
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
// declare the switch pin as an input
pinMode(2,INPUT);
}
void loop(){
// read the value of the switch
// digitalRead() checks to see if there is voltage
// on the pin or not
switchstate = digitalRead(2);
// if the button is not pressed
// turn on the green LED and off the red LEDs
if (switchstate == LOW) {
digitalWrite(3, HIGH); // turn the green LED on pin 3 on
digitalWrite(4, LOW); // turn the red LED on pin 4 off
digitalWrite(5, LOW); // turn the red LED on pin 5 off
}
// this else is part of the above if() statement.
// if the switch is not LOW (the button is pressed)
// turn off the green LED and blink alternatively the red LEDs
else {
digitalWrite(3, LOW); // turn the green LED on pin 3 off
digitalWrite(4, LOW); // turn the red LED on pin 4 off
digitalWrite(5, HIGH); // turn the red LED on pin 5 on
// wait for a quarter second before changing the light
delay(250);
digitalWrite(4, HIGH); // turn the red LED on pin 4 on
digitalWrite(5, LOW); // turn the red LED on pin 5 off
// wait for a quarter second before changing the light
delay(250);
}
}
- Ahora, hemos modificado el código para que al pulsar el pulsador parpadeen los led amarillo y verde a una velocidad un poco mayor.
El código correspondiente es:
/*
Arduino Starter Kit example
Project 2 - Spaceship Interface
This sketch is written to accompany Project 2 in the
Arduino Starter Kit
Parts required:
1 green LED
2 red LEDs
pushbutton
10 kilohm resistor
3 220 ohm resistors
Created 13 September 2012
by Scott Fitzgerald
http://arduino.cc/starterKit
This example code is part of the public domain
*/
// Create a global variable to hold the
// state of the switch. This variable is persistent
// throughout the program. Whenever you refer to
// switchState, you’re talking about the number it holds
int switchstate = 0;
void setup(){
// declare the LED pins as outputs
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
// declare the switch pin as an input
pinMode(2,INPUT);
}
void loop(){
// read the value of the switch
// digitalRead() checks to see if there is voltage
// on the pin or not
switchstate = digitalRead(2);
// if the button is not pressed
// turn on the green LED and off the red LEDs
if (switchstate == LOW) {
digitalWrite(3, HIGH); // turn the green LED on pin 3 on
digitalWrite(4, LOW); // turn the red LED on pin 4 off
digitalWrite(5, LOW); // turn the red LED on pin 5 off
}
// this else is part of the above if() statement.
// if the switch is not LOW (the button is pressed)
// turn off the green LED and blink alternatively the red LEDs
else {
digitalWrite(3, LOW); // turn the green LED on pin 3 off
digitalWrite(4, LOW); // turn the red LED on pin 4 off
digitalWrite(5, HIGH); // turn the red LED on pin 5 on
// wait for a quarter second before changing the light
delay(250);
digitalWrite(4, HIGH); // turn the red LED on pin 4 on
digitalWrite(5, LOW); // turn the red LED on pin 5 off
// wait for a quarter second before changing the light
delay(250);
}
- Ahora hemos plantado otro código distinto con el que hemos conseguido que al pulsar el botón se encienda un único led.
El código correspondiente es:
// named constant for the pin the sensor is connected to
const int sensorPin = A0;
// room temperature in Celcius
const float baselineTemp = 20.0;
void setup(){
// open a serial connection to display values
Serial.begin(9600);
// set the LED pins as outputs
// the for() loop saves some extra coding
for(int pinNumber = 2; pinNumber<5; pinNumber++){
pinMode(pinNumber,OUTPUT);
digitalWrite(pinNumber, LOW);
}
}
void loop(){
// read the value on AnalogIn pin 0
// and store it in a variable
int sensorVal = analogRead(sensorPin); }
Durante la introducción a la programación vimos como
hacer pequeños programas y animaciones usando el ordenador. Encendíamos y
apagábamos los píxels en la pantalla del ordenador. La
placa Arduino no tiene pantalla, pero tiene un LED – una pequeña lámpara
que puede encenderse y apagarse fácilmente usando un programa. Se puede
decir que Arduino viene con una pantalla de un solo pixel.
Ese LED en placa, está conectado al Pin digital 13. Como puedes ver en
la placa, todos los pins están numerados y agrupados por funcionalidad.
Hay un grupo de 14 pins (numerados del 0 al 13) que son pins digitales y
luego otro grupo de 6 pins (etiquetados de A0 a A5) que son los
analógicos. Veamos cómo controlar el LED en tu Arduino
utilizando un comando sencillo. El primer ejemplo es el que llamamos Blink,
que significa encender y apagar el LED repetidamente. Al igual que los
programas de Processing que siempre necesitan tener una función
setup() y una función draw(), los programas Arduino necesitan las funciones setup() y loop():
setup(): Esta parte del programa sólo se ejecuta al principio. Aquí podrás configurar las funcionalidades de los pins, ya seaninputs(entradas) uoutputs(salidas), o si van a realizar una función más compleja como enviar señales a través del cable USB.loop(): Esta parte funcionará infinitamente (o hasta que desconectes la fuente de alimentación). Los comandos en elloopserán ejecutadas en orden, una tras otra. Cuando llegamos al último comando, comenzará de nuevo desde el principio.
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
pinMode(pinNumber, INPUT | OUTPUT | INPUT_PULLUP): Se utiliza para determinar si el Pin digital en tu Arduino está escribiendo(OUTPUT)o leyendo(INPUT | INPUT_PULLUP)las señales desde/hacia el entorno.digitalWrite(pinNumber, HIGH | LOW): Se utiliza para hacer que un Pin digital concreto escriba 5 voltios(HIGH)ó 0 voltios(LOW)a una salida.delay(time): Detiene el programa durante cierta cantidad de tiempo. El tiempo se expresa en milisegundos. Si quieres detener el programa durante 2 segundos, deberías escribirdelay(2000).
- Cada línea termina con punto y coma ‘;’.
- Los bloques de código están contenidos entre llaves ‘{ }’.
- Las funciones comienzan con una definición como
void. - Las funciones tienen parámetros que figuran entre paréntesis ‘( )’, y pueden tener tantos parámetros como necesites.
Entradas digitales
INPUT (entrada)
digital. Puedes conectar un cable a, por ejemplo, el pin 5 y encenderlo
conectando la otra parte del cable o bien a 5 voltios o a GND (0
voltios) en el conector de tu Arduino. ¡Prueba esto! Coge unos de los
conectores de tu kit, conéctalo al pin 5 y programa el siguiente código
en tu Arduino:int inputPin = 5;
int ledPin = 13;
void setup() {
pinMode(inputPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (digitalRead(inputPin) == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
- Primero, vemos que puedes utilizar muchas variables, en este caso, tenemos una para el LED
ledPiny otra para el cableinputPin. - Al igual que un
pinModese puede utilizar para asignar un pin como OUTPUT, puedes asignar el pin como INPUT. - Hay un comando,
digitalRead(inputPin), que leerá el valor del voltio en elinputPiny devolverá si está aHIGHoLOW. DevolveráHIGHcuando el cable esté a 5V yLOWcuando se conecte a GND. - El programa utiliza una instrucción condicional
ifpara comprobar el valor delinputPin. - Cuando quieres comparar dos valores en un programa, debes utilizar dos veces el signo ‘igual a’, es decir,
==. Esto hace que el ordenador entienda que los quieres comparar (en lugar de asignar). Este “doble igual” es lo que llamamos un operador. Hay otros operadores que comparan otro tipo de valores.
Comentarios
Publicar un comentario