Programación en Arduino
Programación en Arduino
Blink Button
const int buttonPin = 2;
int led = 13;
const int ledPin = 13;
int buttonState = 0;
void setup() {
pinMode(led, OUTPUT);
void setup() {
}
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
void loop() {
}
digitalWrite(led, HIGH);
delay(1000); void loop(){
digitalWrite(led, LOW); buttonState = digitalRead(buttonPin);
delay(1000);
} if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
DigitalReadSerial }
else {
int pushButton = 2;
digitalWrite(ledPin, LOW);
}
void setup() {
}
Serial.begin(9600);
pinMode(pushButton, INPUT);
}
void loop() {
int buttonState =
digitalRead(pushButton);
Serial.println(buttonState);
delay(1);
}
AnalogReadSerial
void setup() {
// initialize serial communication at
9600 bits per second:
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1);
}
Fade (Efecto led fundido-desvanece)
int led = 9; // salida PWM
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the
LED by
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
analogWrite(led, brightness);
Buzzer
int buzzer = 11;
void setup(){
pinMode(buzzer, OUTPUT); // sets the pin as
output
}
void loop(){
analogWrite(buzzer,128); //emite sonido
delay(2000); //espera dos segundos
digitalWrite(buzzer, LOW); //deja de emitir
delay(500);//espera medio segundo
}
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH);
delay(sensorValue);
digitalWrite(ledPin, LOW);
delay(sensorValue);
}
void setup(){
Serial.begin(9600);
pinMode(LeftPin, OUTPUT);
pinMode(RightPin, OUTPUT);
}
void loop(){
if (Serial.available()){
input=Serial.read();
if (input=='1'){ //El motor girará a la derecha
digitalWrite(LeftPin, LOW);
digitalWrite(RightPin, HIGH);
}
else if (input=='2'){ //El motor girará a la izquierda
digitalWrite(LeftPin, HIGH);
digitalWrite(RightPin, LOW);
}
else if (input=='0'){ //El motor se detendrá
digitalWrite(LeftPin, LOW);
digitalWrite(RightPin, LOW);
}
delay(10);
}
}
arduino-2servo.pde
#include <Servo.h>
void setup() {
servoLeft.attach(10); // Set left servo to digital pin 10
servoRight.attach(9); // Set right servo to digital pin 9
}
void reverse() {
servoLeft.write(180);
servoRight.write(0);
}
void turnRight() {
servoLeft.write(180);
servoRight.write(180);
}
void turnLeft() {
servoLeft.write(0);
servoRight.write(0);
}
void stopRobot() {
servoLeft.write(90);
servoRight.write(90);
}
//Programa para controlar 2 motores con control de velocidad y giro con
un L293
int switchPin = 7; // switch para cambiar el sentido de giro de los motores
int motor1Pin1 = 3; // Motor 1 adelante
int motor1Pin2 = 4; // Motor 1 atras
int speedPin1 = 9; // Motor 1 aceleracion (PWM) Pin enable del L293
int potPin = 0; // Potenciometro para controlar velocidad motor 1
void setup() {
Serial.begin (9600);
//configuracion de pines
pinMode(switchPin, INPUT);
//pinMode(switchPin2, INPUT); //no usado
// Control Motor 1
pinMode(motor1Pin1, OUTPUT);
pinMode(motor1Pin2, OUTPUT);
pinMode(speedPin1, OUTPUT);
//Control Motor 2
pinMode(motor2Pin1, OUTPUT);
pinMode(motor2Pin2, OUTPUT);
pinMode(speedPin2, OUTPUT);
pinMode(ledPin, OUTPUT);
// comprobacion de reseteo, si el led parpadea solo 3 veces, todo esta bien si vuelve a parpadear,
significa que ha hecho un reset, revisar conexiones por si hubiera un corto
blink(ledPin, 3, 100);
}
void loop() {
/*
Parpadeo del led, Significa que ha ejecutado la funcion setup()si todo va bien, solo parpadea
tres veces, si hay algun error que resetee el arduino, volvera a verse el parpadeo del led
*/
void blink(int whatPin, int howManyTimes, int milliSecs) {
int i = 0;
for ( i = 0; i < howManyTimes; i++) {
digitalWrite(whatPin, HIGH);
delay(milliSecs/2);
digitalWrite(whatPin, LOW);
delay(milliSecs/2);
}
}
Control Motor DC Simple
int motorPin = 3;
void setup(){
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
while (! Serial);
Serial.println("Speed 0 to 255");
}
void loop(){
if (Serial.available()){
int speed = Serial.parseInt();
if (speed >= 0 && speed <= 255){
analogWrite(motorPin, speed);
}}}
Sensor PIR
int pirPin = 2; //digital 2
void setup(){
Serial.begin(9600);
pinMode(pirPin, INPUT);
}
void loop(){
int pirVal = digitalRead(pirPin);
}
/*
---------------------------------------------
Control por PWM de un motor
---------------------------------------------
Programa que hace uso de un motor y la Consola serial de Arduino, tiene la posiblidad de configurar al
motor 5 velocidades distintas, desde el teclado del PC puedes enviarle la velocidad deseada. Las 5
velocidades se configuran con 5 PWM distintos.
Cosas de Mecatrónica y Tienda de Robótica
*/
//--------------------------------------------------
//Declara puertos de entradas y salidas y variables
//--------------------------------------------------
int motor=3; //Declara Pin del motor
//------------------------------------
//Funcion principal
//------------------------------------
void setup() // Se ejecuta cada vez que el Arduino se inicia
{
Serial.begin(9600); //Inicia la comunicacion serial Arduino-PC
}
//------------------------------------
//Funcion ciclicla
//------------------------------------
void loop() // Esta funcion se mantiene ejecutando
{ // cuando este energizado el Arduino
// Si hay algun valor en la Consola Serial
if (Serial.available()){
//Variable donde se guarda el caracter enviado desde teclado
char a = Serial.read();
// Si el caracter ingresado esta entre 0 y 5
if (a>='0' && a<='5'){
//Variable para escalar el valor ingresado a rango de PWM
int velocidad = map(a,'0','5',0,255);
//Escritura de PWM al motor
analogWrite(motor,velocidad);
//Mensaje para el usuario
Serial.print("El motor esta girando a la velocidad ");
Serial.println(a);
}else{ // Si el caracter ingresado NO esta entre 0 y 5
//Mensaje para el usuario
Serial.print("Velocidad invalida");
Serial.println(a);
}
}
}
//Fin programa
Sensor PIR
int pirPin = 7;
int minSecsBetweenEmails = 60; // 1 min
long lastSend = -minSecsBetweenEmails * 1000;
void setup(){
pinMode(pirPin, INPUT);
Serial.begin(9600);
}
void loop(){
long now = millis();
if (digitalRead(pirPin) == HIGH){
if (now > (lastSend + minSecsBetweenEmails * 1000)){
Serial.println("MOVEMENT");
lastSend = now;
}
else{
Serial.println("Too soon");
}
}
delay(500);
}
//Sensor de proximidad ultrasónico
const int echoPin = 6; //Definimos las constantes
const int trigPin = 7;
const int ledPin = 3;
long duracion, distancia; //Variables que almacenarán tiempo y distancia
void setup() {
Serial.begin (9600); //Iniciamos la comunicación serial a 9600bps
pinMode(echoPin, INPUT); //Definimos los pines como INPUT/OUTPUT
pinMode(trigPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(trigPin, LOW); //Apagamos el pin Trig antes de enviar un nuevo pulso
delayMicroseconds(2); //Esperamos 2 microsegundos
digitalWrite(trigPin, HIGH); //Enviamos un pulso de 10 microsegundos
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duracion = pulseIn(echoPin, HIGH); //Medimos el tiempo que ha durado el pulso
distancia = duracion/58; //Utilizamos la fórmula para obtener la distancia en cm
if (distancia > 400 || distancia < 2){ //Si la distancia está fuera del rengo de precisión
Serial.println("---"); //No imprimiremos la medición ya que no será precisa
}
else { //Si está dentro del rango
Serial.print("Distancia: ");
Serial.print(distancia); //Imprimimos la distancia en el monitor serial
Serial.println(" cm");
digitalWrite(ledPin, LOW); //Nos aseguramos de que el LED de alarma esté apagado
}
if (distancia <= 15 && distancia >= 1){ //Si la distancia está entre 1 y 15 cm (peligro)
digitalWrite(ledPin, HIGH); //Encendemos el LED de alarma
Serial.println("Alarma..."); //Imprimimos un aviso en el monitor serial
Serial.println("Alarma...");
Serial.println("Alarma...");
}
delay(200); //Espera de 0.2 segundos antes de realizar una nueva medición
}
Prueba Bluetooth # 1
char INBYTE;
int LED = 13; // LED on pin 13
void setup() {
Serial.begin(9600);
pinMode(LED, OUTPUT);
}
void loop() {
Serial.println("Press 1 to turn Arduino pin 13 LED ON or 0 to turn it OFF:");
while (!Serial.available()); // stay here so long as COM port is empty
INBYTE = Serial.read(); // read next available byte
if( INBYTE == '0' ) digitalWrite(LED, LOW); // if it's a 0 (zero) tun LED off
if( INBYTE == '1' ) digitalWrite(LED, HIGH); // if it's a 1 (one) turn LED on
delay(400);
}
Prueba Bluetooth # 2
void setup() {
// El baud rate debe ser el mismo que en el monitor serial
Serial.begin(9600);
pinMode(LED, OUTPUT);
}
void loop() {}
void setup(){
pinMode(buzzerPin, OUTPUT);
pinMode(inputPin, INPUT);
}
void loop(){
int value= digitalRead(inputPin);
if (value == HIGH){
digitalWrite(buzzerPin, HIGH);
}
}
Control de Servomotor
#include <Servo.h>
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//Arduino 1.0+ Only
//Arduino 1.0+ Only
#include <Wire.h>
// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;
void setup(){
Serial.begin(9600);
Wire.begin();
bmp085Calibration();
}
void loop()
{
float temperature = bmp085GetTemperature(bmp085ReadUT()); //MUST be called first
float pressure = bmp085GetPressure(bmp085ReadUP());
float atm = pressure / 101325; // "standard atmosphere"
float altitude = calcAltitude(pressure); //Uncompensated caculation - in Meters
Serial.print("Temperature: ");
Serial.print(temperature, 2); //display 2 decimal places
Serial.println("deg C");
Serial.print("Pressure: ");
Serial.print(pressure, 0); //whole number only.
Serial.println(" Pa");
Serial.print("Altitude: ");
Serial.print(altitude, 2); //display 2 decimal places
Serial.println(" M");
Serial.println();//line break
return temp;
}
b6 = b5 - 4000;
// Calculate B3
x1 = (b2 * (b6 * b6)>>12)>>11;
x2 = (ac2 * b6)>>11;
x3 = x1 + x2;
b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2;
// Calculate B4
x1 = (ac3 * b6)>>13;
x2 = (b1 * ((b6 * b6)>>12))>>16;
x3 = ((x1 + x2) + 2)>>2;
b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;
x1 = (p>>8) * (p>>8);
x1 = (x1 * 3038)>>16;
x2 = (-7357 * p)>>16;
p += (x1 + x2 + 3791)>>4;
long temp = p;
return temp;
}
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 1);
while(!Wire.available())
;
return Wire.read();
}
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 2);
while(Wire.available()<2)
;
msb = Wire.read();
lsb = Wire.read();
up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long)
xlsb) >> (8-OSS);
return up;
}
int v;
Wire.beginTransmission(deviceAddress);
Wire.write(address); // register to read
Wire.endTransmission();
while(!Wire.available()) {
// waiting
}
v = Wire.read();
return v;
}
float A = pressure/101325;
float B = 1/5.25588;
float C = pow(A,B);
C = 1 - C;
C = C /0.0000225577;
return C;
}
Sensor de presión
void setup()
{
Serial.begin(9600); // Enviaremos la información de depuración a través del
Monitor de Serial
pinMode(LEDpin, OUTPUT);
}
void loop()
{
ResRead = analogRead(AnalogPin); // La Resistencia es igual a la lectura del
sensor (Analog 0)
Serial.print("Lectura Analogica = ");
Serial.println(ResRead);
#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup()
{
// Define que o servo está ligado a porta 9
myservo.attach(9);
}
void loop()
{
// Le o valor do potenciometro (valores entre 0 e 1023)
val = analogRead(potpin);
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH){
// we have just turned of
Serial.println("Motion ended!");
pirState = LOW;
}}}
Sensor Ultrasonido
long distancia;
long tiempo;
void setup(){
Serial.begin(9600);
pinMode(9, OUTPUT); /*activación del pin 9 como salida: para el pulso
ultrasónico*/
pinMode(8, INPUT); /*activación del pin 8 como entrada: tiempo del rebote
del ultrasonido*/
}
void loop(){
digitalWrite(9,LOW); /* Por cuestión de estabilización del sensor*/
delayMicroseconds(5);
digitalWrite(9, HIGH); /* envío del pulso ultrasónico*/
delayMicroseconds(10);
tiempo=pulseIn(8, HIGH); /* Función para medir la longitud del pulso
entrante. Mide el tiempo que transcurrido entre el envío del pulso ultrasónico y cuando
el sensor recibe el rebote, es decir: desde que el pin 12 empieza a recibir el rebote,
HIGH, hasta que deja de hacerlo, LOW, la longitud del pulso entrante*/
distancia= int(0.017*tiempo); /*fórmula para calcular la distancia obteniendo un
valor entero*/
/*Monitorización en centímetros por el monitor serial*/
Serial.println("Distancia ");
Serial.println(distancia);
Serial.println(" cm");
delay(1000); }
Sensor de llama
#define PINDIGITAL 7
#define PINANALOGICO A0
void setup(){
Serial.begin(9600);
Serial.println("Digital/ Analogico" );
pinMode(PINDIGITAL, INPUT);
pinMode(PINANALOGICO, INPUT);
}
void loop(){
int valDigital = F_Digital(PINDIGITAL);
int valAnalogico = F_Analog(PINANALOGICO);
F_Comunicacion(valDigital, valAnalogico);
delay(500);
}
}
void loop()//función de loop-lectura del valor del sensor de llama y
corrección del umbral de lectura base
{
int valor = analogRead(A0) ;
if ( valor > 10){
beep1(200) ;//función de llamada al zumbador
}
}
void beep1(unsigned char pausa)//función del zumbador con los intervalos de
silencio correspondientes
{
analogWrite(9, 200);
delay(pausa); // Espera
analogWrite(9, 0); // Apaga
delay(pausa); // Espera
}
Control de Motor para carro a distancia.
Se usan los pines 0 y 1 para TX y RX del Blutooth
char INBYTE;
int led = 13; // LED on pin 13
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
}
void loop() {
Serial.println("presione 1 para adelantar, 2 para retroceder, 3 para izquierda, 4 para derecha y 5 para detenerse");
while (!Serial.available()); // stay here so long as COM port is empty
INBYTE = Serial.read(); // read next available byte
if(INBYTE == '1')
{
digitalWrite(3, HIGH);
digitalWrite (4, HIGH);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(led, HIGH);
delay(1000);
}
} }
}
Sensor PIR
int ledPin = 13; // declaramos el led en el pin 12 del arduino
int sensorPin=2; // declaramos el sensor PIR en el pin 11
int val = 0; //variable para asignar la lectura del sensor PIR
void setup(){
pinMode(ledPin, OUTPUT); //El pin 12 del arduino lo asignamos como salida para el led
pinMode(sensorPin, INPUT); //El pin 11 lo asignamos como entrada para la señal del sensor
Serial.begin(9600);
for(int i = 0; i < 30; i++){ //Utilizamos un for para calibrar el sensor depende del tipo de sensor que utilicemos va a cambiar el tiempo de calibración
delay(1000);
}
delay(50);
}
void loop(){
val = digitalRead(sensorPin); //Lee el valor de la variable (val)
if (val == HIGH) { //Si detecta que hay movimiento manda activar el led que hay conectado en el pin 12 del arduino
digitalWrite(ledPin, HIGH);
}else { //Si la condición anterior no se cumple manda apagar el led
digitalWrite(ledPin, LOW);
}
}
CONTROL DE MOTORES
Control de motor cc con transistor
//
// motorcc.pde
//
void setup() {
// set the transistor pin as output:
pinMode(transistorPin, OUTPUT);
}
void loop() {
digitalWrite(transistorPin, HIGH);
delay(1000);
digitalWrite(transistorPin, LOW);
delay(1000);
}
EL L293.
void loop() {
digitalWrite( pinA1, HIGH); // Valores ALTO en A y BAJO en B simulaneamente
digitalWrite( pinB1, LOW); // hacen girar el motor 1 hacia ADELANTE
valorPot = analogRead(pinPot); // Lee el valor del potenciometro
valorVeloc = map(valorPot, 0, 1023, 55, 255); //Convierte un valor entre 0 y
1023 al rango 0-255
// valorVeloc = valorPot / 4 ; // segunda opción
analogWrite(pinEN1, valorVeloc);// y establece la velocidad del motor con ese
valor
}
/* blinks an LED */
void blink(int whatPin, int cuantoTiempo, int milliSecs) {
for (int i = 0; i < cuantoTiempo; i++) {
digitalWrite(whatPin, HIGH);
delay(milliSecs/2);
digitalWrite(whatPin, LOW);
delay(milliSecs/2);
}
}
Control de motor con Puente H
/* Control de un motor DC con puente H
* motorL293h.pde
* http://itp.nyu.edu/physcomp/Labs/DCMotorControl
* Modificado por V. Garcia el 08.02.2011
* Puede adaptarse a un bot con un motor en las ruedas de traccion
* y una rueda de giro libre que pivote cambiando la direccion
*/
int switchPin = 2; // entrada del switch
int motor1Pin = 7; // pin 1 del L293
int motor2Pin = 8; // pin 2 del L293
int speedPin = 9; // pin enable del L293
int ledPin = 13; //LED
void setup() {
// pone el switch como una entrada
pinMode(switchPin, INPUT);
digitalWrite(switchPin, HIGH);
// pone todos los otros pines usados como salidas
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(speedPin, OUTPUT);
pinMode(ledPin, OUTPUT);
void loop() {
// si el switch es high, motor gira en una direccion
if (digitalRead(switchPin) == HIGH) {
digitalWrite(motor1Pin, LOW); // pone motor1 del H-bridge low
digitalWrite(motor2Pin, HIGH); // pone motor2 del H-bridge high
}
/* blinks an LED */
void blink(int whatPin, int cuantoTiempo, int milliSecs) {
int i = 0;
for ( i = 0; i < cuantoTiempo; i++) {
digitalWrite(whatPin, HIGH);
delay(milliSecs/2);
digitalWrite(whatPin, LOW);
delay(milliSecs/2);
}
}
/* Control de motor paso a paso bipolar sin utilizar librerias
* ------------------------------------------------------------
*/
void loop()
//gira media vuelta en sentido antihorario rápido
{
for (int i=0; i <= 265; i++){
gira_antihorario(2);
}
delay(2000);//espera 2 segundos
//gira media vuelta en sentido horario lento
for (int i=0; i <= 265; i++){
gira_horario(18);
}
delay(2000);//espera 2 segundos
}
Para profundizar y ver todas las posibilidades de la esta librería, consultad el siguiente enlace.
#include <Stepper.h>
#define STEPS 200 //360° divided by step angle
void setup(){
stepper.setSpeed(60); //RPMs
}
void loop(){
stepper.step(100);
delay(1000);
stepper.step(-100);
delay(1000);
}
int motorPin1 = 8;
int motorPin2 = 9;
int motorPin3 = 10;
int motorPin4 = 11;
int delayTime = 15; // delay que determina el tiempo cada vez que cambia de paso
int buttonPin = 2;
int estado = 0;
void setup() {
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
estado = digitalRead(buttonPin);
if(estado==HIGH)
{
digitalWrite(motorPin1, LOW); // sentido anti-horario
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(delayTime);
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(delayTime);
}
else
{
digitalWrite(motorPin1, HIGH); // sentido agujas del reloj
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(delayTime);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(delayTime);
}
}
// inicializamos la librería con los numeros pins del interfaz. Cada LCD puede llevar sus propios numeros
LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);
void setup() {
lcd.begin(16, 2); // establecemos el numero de columnas y filas del display
lcd.print("www.ajpdsoft.com"); // enviamos el mensaje a mostrar en el display
}
void loop() {
// enviamos la posicion del cursor al Display (nota: la linea 1 es la segunda fila, empieza a contar en 0
lcd.setCursor(0, 1);
lcd.print(millis()/1000); // mostramos el número de segundos desde el inicio del programa
LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7); // initialize the library with the numbers of the interface pins
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("www.ajpdsoft.com");
delay(1000);
}
void loop() {
// scroll 13 positions (string length) to the left
// to move it offscreen left:
for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
// scroll one position left:
lcd.scrollDisplayLeft();
// wait a bit:
delay(150);
}
Sensor de Luz
This example initalises the BH1750 object using the default high resolution mode and then makes a light level reading every second.
Connection:
VCC-5v
GND-GND
SCL-SCL(analog pin 5)
SDA-SDA(analog pin 4)
ADD-NC or GND
*/
#include <Wire.h>
#include <BH1750.h>
BH1750 lightMeter;
void setup(){
Serial.begin(9600);
lightMeter.begin();
Serial.println("Running...");
}
void loop() {
uint16_t lux = lightMeter.readLightLevel();
Serial.print("Light: ");
Serial.print(lux);
Serial.println(" lx");
delay(1000);
}
PIANO ARDUINO
int button_C = 2;
int button_D = 3;
int button_E = 4;
int button_F = 5;
int button_G = 6;
int button_A = 7;
int button_B = 8;
int button_Cup = 9;
int buttonstate_C = 0;
int buttonstate_D = 0;
int buttonstate_E = 0;
int buttonstate_F = 0;
int buttonstate_G = 0;
int buttonstate_A = 0;
int buttonstate_B = 0;
int buttonstate_Cup = 0;
//NOTES 'c' , 'd', 'e', 'f', 'g', 'a', 'b', 'C'
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 }; //freq
int Cur_tone = 0;
void setup(){
pinMode(button_C, INPUT);
pinMode(button_D, INPUT);
pinMode(button_E, INPUT);
pinMode(button_F, INPUT);
pinMode(button_G, INPUT);
pinMode(button_A, INPUT);
pinMode(button_B, INPUT);
pinMode(button_Cup, INPUT);
pinMode(speaker, OUTPUT);
}
void loop(){
buttonstate_C = digitalRead(button_C);
buttonstate_D = digitalRead(button_D);
buttonstate_E = digitalRead(button_E);
buttonstate_F = digitalRead(button_F);
buttonstate_G = digitalRead(button_G);
buttonstate_A = digitalRead(button_A);
buttonstate_B = digitalRead(button_B);
buttonstate_Cup = digitalRead(button_Cup);
if (buttonstate_C == HIGH){
Cur_tone = tones[0];
}
if (buttonstate_E == HIGH){
Cur_tone = tones[1];
}
if (buttonstate_G == HIGH){
Cur_tone = tones[2];
}
if (buttonstate_D == HIGH){
Cur_tone = tones[3];
}
if (buttonstate_F == HIGH){
Cur_tone = tones[4];
}
if (buttonstate_A == HIGH){
Cur_tone = tones[5];
}
if (buttonstate_B == HIGH){
Cur_tone = tones[6];
}
if (buttonstate_Cup == HIGH){
Cur_tone = tones[7];
}
digitalWrite(speaker, HIGH);
delayMicroseconds(Cur_tone);
digitalWrite(speaker, LOW);
delayMicroseconds(Cur_tone);
}
else{ //in case no button is pressed , close the piezo
digitalWrite(speaker, LOW);
}
}
Bluetooh Configurado para otros pines
/*
El siguiente programa recibe la informacion desde la PC
por medio del software antes mencionado.
Con este software se envia la informacion que sera recibida por
el modulo bluetooth.
Para este tutorial:
El envio de un '1', prende el LED conectado al pin 13.
El envio de un '2', prende el LED conectado al pin 12.
El envio de un '3', prende el LED conectado al pin 11.
El envio de un 'a', apaga el LED conectado al pin 13.
El envio de un 'b', apaga el LED conectado al pin 12.
El envio de un 'c', apaga el LED conectado al pin 11.
NOTA: RX EN TX Y TX EN RX
*/
#include<SoftwareSerial.h>
void setup(){
void loop()
{
char c=mySerial.read();
if(c=='1') digitalWrite(13,HIGH);
if(c=='2') digitalWrite(12,HIGH);
if(c=='3') digitalWrite(11,HIGH);
if(c=='a') digitalWrite(13,LOW);
if(c=='b') digitalWrite(12,LOW);
if(c=='c') digitalWrite(11,LOW);
}
INPUT_PULLUP Arduino
void setup(){
Serial.begin(9600);
pinMode(9, INPUT_PULLUP);
}
void loop(){
Serial.println(digitalRead(9));
}
Control de energia con Arduino
#include <avr/sleep.h>
void wakeUpNow() {
// execute code here after wake-up before returning to the loop() function
// timers and code using timers (serial.print and more...) will not work here.
// we don't really need to execute any special functions here, since we
// just want the thing to wake up
}
void setup() {
pinMode(wakePin, INPUT_PULLUP);
pinMode(led, OUTPUT);
attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}
void sleepNow() {
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
sleep_enable(); // enables the sleep bit in the mcucr register
attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
sleep_mode(); // here the device is actually put to sleep!!
// THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
sleep_disable(); // first thing after waking from sleep: disable sleep...
detachInterrupt(0); // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running
time.
}
void loop() {
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
sleepNow(); // sleep function called here
}
#include <Servo.h>
Servo myservo;
void setup()
{
myservo.attach(9);
}
void loop()
{
int val = analogRead(0);
Serial.println(val);
myservo.write(map(val, 0, 1023, 0, 179));
delay(15);
}
Programación en Arduino
Blink Button
const int buttonPin = 2;
int led = 13;
const int ledPin = 13;
int buttonState = 0;
void setup() {
pinMode(led, OUTPUT);
void setup() {
}
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
void loop() {
}
digitalWrite(led, HIGH);
delay(1000); void loop(){
digitalWrite(led, LOW); buttonState = digitalRead(buttonPin);
delay(1000);
} if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
DigitalReadSerial }
else {
int pushButton = 2;
digitalWrite(ledPin, LOW);
}
void setup() {
}
Serial.begin(9600);
pinMode(pushButton, INPUT);
}
void loop() {
int buttonState =
digitalRead(pushButton);
Serial.println(buttonState);
delay(1);
}
AnalogReadSerial
void setup() {
// initialize serial communication at
9600 bits per second:
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1);
}
Entrada a partir de un potenciómetro
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH);
delay(sensorValue);
digitalWrite(ledPin, LOW);
delay(sensorValue);
}
void setup(){
Serial.begin(9600);
pinMode(LeftPin, OUTPUT);
pinMode(RightPin, OUTPUT);
}
void loop(){
if (Serial.available()){
input=Serial.read();
if (input=='1'){ //El motor girará a la derecha
digitalWrite(LeftPin, LOW);
digitalWrite(RightPin, HIGH);
}
else if (input=='2'){ //El motor girará a la izquierda
digitalWrite(LeftPin, HIGH);
digitalWrite(RightPin, LOW);
}
else if (input=='0'){ //El motor se detendrá
digitalWrite(LeftPin, LOW);
digitalWrite(RightPin, LOW);
}
delay(10);
}
}
Control de Motor para carro a distancia.
Se usan los pines 0 y 1 para TX y RX del Blutooth
char INBYTE;
int led = 13; // LED on pin 13
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
}
void loop() {
Serial.println("presione 1 para adelantar, 2 para retroceder, 3 para izquierda, 4 para derecha y 5 para detenerse");
while (!Serial.available()); // stay here so long as COM port is empty
INBYTE = Serial.read(); // read next available byte
if(INBYTE == '1')
{
digitalWrite(3, HIGH);
digitalWrite (4, HIGH);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(led, HIGH);
delay(1000);
}
} }