Index:
UPDATED ✅ Do you want to know what are the best projects to do on Arduino yourself? ⭐ ENTER HERE ⭐ and Learn Everything From Scratch!
In recent years, Arduino has been widely praised because it can provide developers around the world with the benefits of using its development board and platform. to develop digital and interactive projects.
With the help of Arduino IDE language program, you can add instructions to a board’s microcontroller, so that the hardware or software you want to design can perform specific tasks.
That said, the reason for this post may vary depending on the purpose you have in mind. Therefore, We present you some of the most common and simple technologies that you can develop with Arduino.
What kind of devices can I create using Arduino and its hardware development boards?
One of the advantages offered by Arduino is its great flexibility to work on any project. This is based, in general, on the development of the platform, which is of Open Source. In this way, it can be used in the creation of different types of tasks and unique devices.
If you want to know some projects that you can program quickly, take a look below:
wearables
Wearable technology is very well known today. The small size of its devices, which can be worn under or over clothing, and the functions it offers the user are distinctive aspects of this tool. You can create a prosthesis, a bracelet, a watch and any body object you can think of with Arduino. This wearable technology identifies which smart accessories can be included in clothing.
One of the differences that a receiver and transmitter of data for the body has with a common device is that the former have exclusive functions, for example, screens, sensors and a processor to manage specific information required by the user. While the rest of the electronic equipment is designed to perform standard functions, no matter what type of operator uses it.
Let’s see below an example of a Wearable project with Arduino. For to create a pulse sensor you are going to need an Arduino UNO board and an electronic sensor ProtoCentral for oximeter breakage, you must also have cables to make the joints.
Once you have all the elements you must open the Arduino IDE and copy this code:
#include "Protocentral_MAX30100.h" #include <Wire.h> MAX30100 sensor; uint8_t data_len=8; uint8_t DataPacketHeader[15]; volatile long IRR,REDD; void setup() { begin(); begin(57600); while(!Serial); begin(pw1600, i50, sr100 ); printRegisters(); } void loop() { readSensor(); IRR=sensor.IR; REDD=sensor.RED; DataPacketHeader[0] = 0x0A; DataPacketHeader[1] = 0xFA; DataPacketHeader[2] = (uint8_t) (data_len); DataPacketHeader[3] = (uint8_t) (data_len>>8); DataPacketHeader[4] = 0x02; DataPacketHeader[5] = REDD; DataPacketHeader[6] = REDD>>8; DataPacketHeader[7] = REDD>>16; DataPacketHeader[8] = REDD>>24; DataPacketHeader[9] = IRR; DataPacketHeader[10] = IRR>>8; DataPacketHeader[11] = IRR>>16; DataPacketHeader[12] = IRR>>24; DataPacketHeader[13] = 0x00; DataPacketHeader[14] = 0x0b; for(int i=0; i<15; i++) // esto servirá para transmitir los datos al sensor { write(DataPacketHeader[i]); } //Serial.println(sensor.getPartID()); /* Tener presente: println(REDD,HEX); println(IRR,HEX);*/ delay(10); }
Domotics
When we talk about home automation, in general, it refers to the smart home systems. These technologies are widely recognized for their many advantages when it comes to ingeniously automating any part of a home. There are various types of devices that we can use in this environmentone of the most interesting examples and that has helped to solve the respective security problems are those surveillance systems, alarms and anti-theft locks that can be included in the home.
To carry out a project without making mistakes, you can create a surveillance camera with motion sensor. When an alert is triggered you will receive a photo in the Discord platform. You’ll need a connector kit, an Arduino Nano R3 board, a breadboard, a motion sensor and an ESP32 type camera.
The codes you will need to write are:
/* Ejemplo de uso de una placa Arduino Nano R3 para cámara ESP32 Internet Paso a Paso */ #include <WiFiClientSecure.h> #include <credentials.h> const char* ssid = mySSID; const char* password = myPASSWORD; const char* server = "howsmyssl.com"; // Server URL const char* root_ca = //Ingresa un certificado para autenticación de clientes, los puedes conseguir desde plataformas autorizadas peer to peer //Si lo deseas, puedes usar x.509 client certificates //const char* test_client_key = ""; //esto es para verificar el cliente //const char* test_client_cert = ""; //autenticación de clientes WiFiClientSecure client; void setup() { //Initialize serial and wait for port to open: begin(115200); delay(100); print("Attempting to connect to SSID: "); println(ssid); begin(ssid, password); // attempt to connect to Wifi network: while (WiFi.status() != WL_CONNECTED) { print("."); // wait 1 second for re-trying delay(1000); } print("Connected to "); println(ssid); setCACert(root_ca); //client.setCertificate(test_client_key); //client.setPrivateKey(test_client_cert); println("Iniciando conexión al servidor"); if (!client.connect(server, 443)) { println("¡Sin conexión!"); } else { println("¡Conectado al servidor de forma correcta!"); // Make a HTTP request: println("GET https:// "); //ingresar la dirección de host println("Host: "); // URL del host println("Conección OK"); println(); while (client.connected()) { String line = client.readStringUntil('n'); if (line == "r") { println("headers received"); break; } } // if there are incoming bytes available // from the server, read them and print them: while (client.available()) { char c = client.read(); write(c); } stop(); } } void loop() { // no hacer nada }
robotics
The term robotics is one of the most mentioned, and not only in this field of design, but also internationally. As we well know, this science is used for the production of robots, this is known, for being devices or computers that have the ability to move and perform a specific task. A simple project that you can make with a Mega 2560 board, an HC-SR04 sensor, a wiring kit, and an SG90 servo motor is an Arduino Animator.
To do this you must enter these programming codes in the IDE environment:
#include <Servo.h> #include <SPI.h> #include <Adafruit_GFX.h> #include <Max72xxPanel.h> //matrix int l; int Cs = 53; int i=0; int x=7; bool Mprint=false; bool ok=false; unsigned long time3; Max72xxPanel m1 = Max72xxPanel(Cs, 1, 1); String msg = "Internet Paso a Paso, Curso de Arduino"; int w8 = 70; int esp = 1; int ancpal = 5 + esp; bool msgact =false; // Ultrasonido int medida; int ultra=15; int eco=14; int dura; int distancia; int dist; bool distOk= false; int tomas=0; int c5=0; unsigned long time4; // buzzer int push; int c1; int c=0; bool coff = false; bool actB = false; unsigned long time2; //servos Servo servoR; Servo servoL; unsigned long time1; int R=90,L=90; boolean c2=false; bool cs2=false; int c22=0; bool actS = false; //System bool systemF= false; void setup() { pinMode(ultra,OUTPUT); pinMode(eco,INPUT); attach(9); attach(10); pinMode(30,OUTPUT); pinMode(31,OUTPUT); pinMode(32,OUTPUT); pinMode(33,OUTPUT); pinMode(2,INPUT_PULLUP); pinMode(7,OUTPUT); write(0); write(180); setIntensity(7); } void loop() { push=digitalRead(2); if(push==0){ dist=100; actS=!actS; actB=!actB; cs2=!cs2; c2=!c2; msgact=!msgact; systemF=false; time1=millis(); time2=millis(); time3=millis(); time4=millis(); analogWrite(7,0); RGBoff(); } if(dist>0 && dist<50 && distOk == true && systemF == false){ actS=!actS; actB=!actB; cs2=!cs2; c2=!c2; msgact=!msgact; time1=millis(); time2=millis(); time3=millis(); time4=micros(); systemF=true;} if(c==0 && coff == false && actB==true){ analogWrite(7,277); RGBon();} if((millis() - time1 )>= 100 && c==0 && coff==false && actB==true){ analogWrite(7,0); coff=!coff; RGBoff(); time1=millis();} if((millis() - time1 )>= 350 && c==0 && coff==true&& actB==true){ c++; coff=!coff; time1=millis();} if(c==1 && coff==false&& actB==true){ analogWrite(7,277); RGBon();} if((millis() - time1 ) >= 100 && c==1&& coff==false && actB==true){ analogWrite(7,0); RGBoff(); coff=!coff; time1=millis();} if((millis() - time1 )>= 350 && c==1 && coff==true && actB==true){ c++; coff=!coff; time1=millis();} if(c==2 && coff==false && actB==true){ analogWrite(7,277); RGBon();} if(millis() - time1 >= 100 && c==2 && coff==false && actB==true){ analogWrite(7,0); coff=!coff; time1=millis();} if((millis() - time1 )>= 150 && c==2 && coff==true && actB==true){ c++; coff=!coff; time1=millis();} if(c==3 && coff==false && actB==true){ analogWrite(7,277); RGBon();} if(millis() - time1 >= 100 && c==3 && coff==false && actB==true){ analogWrite(7,0); RGBoff(); coff=!coff; time1=millis();} if((millis() - time1 )>= 150 && c==3 && coff==true && actB==true){ c++; coff=!coff; time1=millis();} if(c==4 && coff==false && actB==true){ analogWrite(7,277); RGBon();} if(millis() - time1 >= 100 && c==4 && coff==false && actB==true){ analogWrite(7,0); RGBoff(); coff=!coff; time1=millis();} if((millis() - time1 )>= 350 && c==4 && coff==true && actB==true){ c=0; coff=!coff; time1=millis();} // Servos if(c2==true && cs2==true && c22==0 && actS==true){ if(R==150 && L==30){time2=millis();c22++;c2=false;} write(R); write(L); if(millis()-time2 >=5 && c22==0){ L--;R++; time2=millis(); } } if((millis()-time2 >=1000) && c2==false && actS==true){ c2=true;time2=millis(); } if(c2==true && cs2==true && c22==1 && actS==true){ if(R==30 && L==150){time2=millis();c22=0;} write(R); write(L); if(millis()-time2 >=5 && c22==1){ L++;R--; time2=millis(); } } //matrix if (i < ancpal * msg.length() + m1.width() - 1 - esp && ok == true && Mprint == false && msgact==true){ i++;m1.fillScreen(LOW); ok=false; l = i / ancpal; x = (m1.width() - 1) - i % ancpal; if(i >= ancpal * msg.length() + m1.width() - 1 - esp){i=0;} } if ( x + ancpal - esp >= 0 && l >= 0 && ok == false && Mprint == false && msgact==true) { if ( l < msg.length() ) { drawChar(x, 1, msg[l], HIGH, LOW, 1); } l--; x -= ancpal; } else if(Mprint == false && msgact==true) { ok=true; time3=millis(); Mprint=true;m1.write();} if(millis() - time3 >= w8 && ok ==true && Mprint==true && msgact==true){ Mprint=false;} //Ultrasonido if(systemF == false){ if(micros()-time4>=10 && c5== 0){ digitalWrite(ultra,LOW); c5++; time4=micros();} if(micros()-time4>=10 && c5== 1){ digitalWrite(ultra,HIGH); c5++; time4=micros();} if(micros()-time4>=20 && c5== 2){ digitalWrite(ultra,LOW); c5=0;tomas++; dura=pulseIn(eco,HIGH); distancia=int(dura/58); distancia=(0.9775*distancia)-0.2461; if(tomas<=10){dist+=distancia;distOk=false;} if(tomas==10){dist=dist/10; distOk=true;tomas=0;} }} } void RGBon(){ analogWrite(30,140); analogWrite(31,140); analogWrite(32,140); analogWrite(33,140); } void RGBoff(){ analogWrite(30,0); analogWrite(31,0); analogWrite(32,0); analogWrite(33,0); }
monitoring
Another of the things that allows us to make an Arduino, is the composition of devices that can monitor situations that need to be evaluated, so that later, they can be intervened and solved. An example of monitoring, is a system managed by a program that has the ability to examine and analyze energy efficiency within a company or home.
In this way, it is possible to control electricity consumption and make it much more profitable. If you want to practice with such a project you can make an energy data logger. For this you will have to choose a plate Arduino UNO or Arduino Nano R3a MicroSD module, a DS3231MPMB1 peripheral integrated board, a 9-volt transformer, resistors and cables for connection.
You will need to write the following codes:
/* Conexiones de hardware / uso de pines Placa Arduino Nano Pines 0 y 1 -> Conexión serie/USB SD - Se comunica por SPI MOSI -> pin 11 MISO -> pin 12 CLK -> pin 13 CS (SS) -> Pin 10 Reloj RTC DS3231 - por I2C/Wire SDA -> pin A4 SCL -> pin A5 Monitoreo de señales analógicas Tensión: // Es necesario para medir tensión que se genera la conectar el transformador pin A2 Corriente: // Mide los parámetros eléctricos. pin A3 Senales de info/control LED "latido" -> pin 2 LED "errorSD" -> pin 3 Pines reservados para futuras mejoras LED (reservado) -> pin 4 Boton "arriba" | Boton "abajo" | Boton "izquierda" | -> array (teclado analógico) conectado a A1 Boton "derecha" | Boton "enter" | */ #include <SPI.h> //Comunicación con periferícos SPI #include <Wire.h> //Comunicación I2C #include <SdFat.h> //Librería SdFat en lugar de la de arduino por estar optimizada - Manejo de tarjeta SD - SdFat SD; //Línea necesaria para compatibizar el programa escrito para SD.h (libreria original) #include <TimeLib.h> #include <DS1307RTC.h> #include <EmonLib.h> // Declaración de etiquetas para los pines utilizados // pines reservados para futuras mejoras //const int pinLedReservado = 4; // LED reservado //const int pinTeclado = A1; // Pin para teclado analógico // Pin para selección de la SD const int CS_SD = 10; // Pin para led´s const int pinLedLatido = 2; const int pinErrorSD = 3; // Pines analógicos, señales analógicas const int pinTension = 2; // Pin (analógico) para la medición (Valor de tensión) de la energía eléctrica. const int pinCorriente = 3; // Pin (analógico) para la medición (Valor de Corriente) de la energía eléctrica. const unsigned long intervaloLectura = 2000; //intervalo de lectura de sensores const unsigned long intervaloEscrituraSD = 300; //intervalo de escritura de datos en la SD EnergyMonitor emon1; // Variable para indicar presencia de tarjeta SD boolean presenciaSD = 0; // Sincro de reloj const int intervaloSincro = 300; //Intervalo de sincronización del reloj arduino con el RTC void setup() { begin(9600); voltage(pinTension, 169.17, 1.7); current(pinCorriente, 60.6); pinMode(pinLedLatido, OUTPUT); //salida donde se conecta el led "latido" pinMode(pinErrorSD, OUTPUT); //salida donde se conecta el led "errorSD" //Inicializa tarjeta SD if (!SD.begin(CS_SD)) { presenciaSD = 0; digitalWrite(pinErrorSD, HIGH); } else { presenciaSD = 1; //tarjeta detectada digitalWrite(pinErrorSD, LOW); // apaga led error SD } //Icicializamos el reloj y el tiempo setTime(RTC.get()); ajustarReloj(); setSyncProvider(RTC.get); setSyncInterval(intervaloSincro); } void loop() { static unsigned long millisPrevio = intervaloLectura; static unsigned long millisPrevio2 = intervaloEscrituraSD; static float energia = 0; static float energiaParcial = 0; static boolean ledLatido = LOW; static String datos; unsigned long millisActual = millis(); if (millisActual - millisPrevio >= intervaloLectura){ println(F("Fecha/Hora; Potencia activa; Potencia aparente; Tensión; Corriente; Factor de potencia")); print(timeLabel()); print(" "); calcVI(20,1000); // Calcula todos los parámetros. No de medias ondas (cruces), time-out serialprint(); energiaParcial = energiaParcial + ((emon1.realPower * (intervaloLectura/1000))/3600000); //calculamos la energía acumulada (desde el ultimo grabacion SD) expresado en KWh. energia = energia + ((emon1.realPower * (intervaloLectura/1000))/3600000); //calculamos la energía acumulada (desde el ultimo reset) expresado en KWh. print(F("nEnergía consumida: ")); println(energia, 4); datos = timeLabel(); // coloca la marca de tiempo en el String datos datos = datos + ", " + String(emon1.Vrms, 2); //va agregando todos los valores medidos al string datos = datos + ", " + String(emon1.Irms, 2); datos = datos + ", " + String(emon1.realPower, 1); datos = datos + ", " + String(emon1.powerFactor, 2); datos = datos + ", " + String(emon1.apparentPower, 1); datos = datos + ", " + String(energiaParcial, 4); datos = datos + ", " + String(energia, 4); if (ledLatido == LOW) { ledLatido = HIGH; } else { ledLatido = LOW; } digitalWrite(pinLedLatido, ledLatido); millisPrevio = millisActual; } if (millisActual - millisPrevio2 >= intervaloEscrituraSD * 1000UL){ //procede a grabar los datos if (grabarDatosSD(datos)) { //si hubo error al grabar devuelve 1 digitalWrite(pinErrorSD, HIGH); //como hubo error en el grabado se enciende el led error SD } energiaParcial = 0; //Vuelve a cero el contador de energía millisPrevio2 = millisActual; } } String timeLabel() { time_t t = now(); String tiempoActual = String('0'); tiempoActual = year if (month tiempoActual = String(tiempoActual + '-' + '0' + month else tiempoActual = String(tiempoActual + '-' + month if (day tiempoActual = String(tiempoActual + '-' + '0' + day else tiempoActual = String(tiempoActual + '-' + day tiempoActual = String(tiempoActual + ' '); if (hour tiempoActual = String(tiempoActual + '0' + hour else tiempoActual = String(tiempoActual + hour tiempoActual = String(tiempoActual + ':'); if (minute tiempoActual = String(tiempoActual + '0' + minute else tiempoActual = String(tiempoActual + minute if (second tiempoActual = String(tiempoActual + '0' + second else tiempoActual = String(tiempoActual + second return tiempoActual; } boolean grabarDatosSD(String data) { time_t t = now(); String date = String('0'); //Se crea string date = year if (month date = String(date + '0' + month else date = String(date + month if (day date = String(date + '0' + day else date = String(date + day date = String(date + ".csv"); char fileName[13]; toCharArray(fileName, 13); //convertimos el string a un array de caracteres if (!presenciaSD) { return 1; } if (SD.exists(fileName)) { //Si existe el archivo "fileName" lo abrimos File nrg_log = SD.open(fileName, FILE_WRITE); if (nrg_log) { //Si el archivo se abre correctamente escribimos en el... println(data); close(); digitalWrite(pinErrorSD, HIGH); delay(100); digitalWrite(pinErrorSD, LOW); delay(50); digitalWrite(pinErrorSD, HIGH); delay(100); digitalWrite(pinErrorSD, LOW); return 0; } else { return 1; } } else { //si no existe el archivo "nrg_log.cvs" se lo genera File nrg_log = SD.open(fileName, FILE_WRITE); if (nrg_log) { //Si el archivo se abre correctamente escribimos print(F("Archivo de registro de mediciones de energía eléctrica. Creado: ")); println(timeLabel()); println('n'); println(F("Fecha/Hora, Tensión, Corriente, Potencia activa, Factor de potencia, Potencia aparente, Energía de intervalo, Energía consumida total")); println(data); close(); digitalWrite(pinErrorSD, HIGH); delay(100); digitalWrite(pinErrorSD, LOW); delay(50); // Doble parpadeo de LED para indicar que grabamos a la SD digitalWrite(pinErrorSD, HIGH); delay(100); digitalWrite(pinErrorSD, LOW); return 0; } else { return 1; } } }
List of the best Arduino projects that you can program yourself to learn how to develop free hardware and software
It is important to consider that Arduino can be used to design a great magnitude of exceptional works.
Here is a list of the most prominent Arduino projects so you can make your own open source devices and programs:
Sensor to turn on lights
First of all, we have this amazing device for your room. With just the use of sensors for an Arduino board and an LED strip and the proper programming, you can create a presence sensor. You will be able to apply this project outside your home, in a place where it receives a direct source of solar energy. For this project you will need an Arduino Nano R3, a light and motion sensor, an LED strip, batteries, a MOSFET module and a 14.5 cm by 14.5 cm solar panel with USB output.
Then you will have to enter this code to make the sensor work:
int Light = 5 ; // pin para LED int PIRpower = 13 ; // alimentación al sensor PIR int PIR = 12 ; // entrada del sensor PIR int PIRState = LOW ; // estado de PIR int LDR = 2 ; // entrada de LDR int LDRpower = 3 ; // alimentación al sensor LDR int LDRState = LOW ; // estado de LDR Noche () { escritura digital ( PIRpower , ALTA ); retraso ( 2000 ); Serial . println ( "A. Sensor PIR ENCENDIDO, detectando movimiento" ); retraso ( 3000 ); PIRState = digitalRead ( PIR ); retraso ( 500 ); Serial . println ( "B. Lectura del sensor de movimiento, desactivando el PIR" ); digitalWrite ( PIRpower , BAJO ); retraso ( 500 ); if ( PIRState == HIGH ) { println(">>>>>>>>>> MOTION DETECTED"); delay(500); println("I. switching Light ON"); delay(500); digitalWrite(Light, HIGH); println("II. Light 100%"); delay(15000); // esperar 15 sec analogWrite(Light, 175); println("II. Light 70%"); delay(15000); // esperar 15 sec analogWrite(Light, 100); println("II. Light 40%"); delay(15000); // esperar 15 sec analogWrite(Light, 50); println("II. Light 20%"); delay(500); println(".......... Wait 5 seconds.........."); delay(1000); }else { println(">>>>>>>>>> MOTION NOT DETECTED"); delay(500); println(".......... Wait 10 seconds.........."); delay(10000); // esperar 10 sec } } void setup() { pinMode(Light, OUTPUT); // declare LED as output pinMode(PIRpower, OUTPUT); // declare PIRpower as output pinMode(LDRpower, OUTPUT); // declare LDRpower as output pinMode(LDR, INPUT); // declare LDR sensor as input pinMode(PIR, INPUT); // declare PIR sensor as input digitalWrite(PIRpower, LOW); digitalWrite(LDRpower, LOW); begin(9600); } void loop(){ println(".......... START.........."); digitalWrite(LDRpower, HIGH); println("1. LDRpower ON, reading LDR sensor"); delay(3000); LDRState = digitalRead(LDR); delay(500); println("2. LDR status read, turning LDRpower OFF"); delay(500); println("3. LDRpower OFF"); digitalWrite(LDRpower, LOW); delay(500); if (LDRState == HIGH){ // Lee el estado del LDR println(">>>>>>>>>> LUCES DETECTADAS!!!"); delay(500); println("Switch ON Light 20%"); analogWrite(Light, 50); Night(); println(".......... Restarting.........."); } else{ println(">>>>>>>>>> BRIGHTNESS DETECTED"); delay(500); digitalWrite(Light, LOW); println(".......... Waiting 5mins.........."); delay(60000); // Espera un minuto println(".......... Waiting 4mins.........."); delay(60000); // Espera un minuto println(".......... Waiting 3mins.........."); delay(60000); // Espera un minuto println(".......... Waiting 2mins.........."); delay(60000); // Espera un minuto println(".......... Waiting 1mins.........."); delay(60000); // Espera un minuto println(".......... Restarting.........."); }
electronic dice
With an Arduino board you can make projects of great benefit and entertainment, for example, an electric dice to play any board game with your family. You can connect seven-segment LEDs to a board and set it up to display numbers from 1 to 6, just by pressing a button so you can randomly generate a number. With an Arduino Nano R3 board, a led screen, a 330 ohm resistor, a SPDT type toggle switch and necessary cables for the connection you will be able to create this project.
The codes you will need are:
int a = 6 ; int b = 7 ; int c = 10 ; int d = 8 ; int e = 9 ; int f = 4 ; int g = 5 ; número largo = 0 ; salida larga = 0 ; int displayTime = 5000 ; int sensorPin = 0 ; int sensorValue = 0 ; int switchIn = 12 ; int analogPin = A3 ; int switchStatus ; unsigned long previousMillis = 0 ; unsigned long currentMillis = 0; const long interval = 400; int minus = 0; void setup() { initialize(); pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); pinMode(d, OUTPUT); pinMode(e, OUTPUT); pinMode(f, OUTPUT); pinMode(g, OUTPUT); pinMode(switchIn, INPUT); currentMillis = millis(); } void initialize() { digitalWrite(a, LOW); digitalWrite(b, LOW); digitalWrite(c, LOW); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, LOW); } void zero() { digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, HIGH); digitalWrite(f, HIGH); digitalWrite(g, LOW); } void one() { digitalWrite(a, LOW); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, LOW); } void two() { digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, LOW); digitalWrite(d, HIGH); digitalWrite(e, HIGH); digitalWrite(f, LOW); digitalWrite(g, HIGH); } void three() { digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, HIGH); } void four() { digitalWrite(a, LOW); digitalWrite(b, HIGH); digitalWrite(c, HIGH); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, HIGH); digitalWrite(g, HIGH); } void five() { digitalWrite(a, HIGH); digitalWrite(b, LOW); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, LOW); digitalWrite(f, HIGH); digitalWrite(g, HIGH); } void six() { digitalWrite(a, HIGH); digitalWrite(b, LOW); digitalWrite(c, HIGH); digitalWrite(d, HIGH); digitalWrite(e, HIGH); digitalWrite(f, HIGH); digitalWrite(g, HIGH); } void shuffle() { digitalWrite(g, LOW); digitalWrite(a, HIGH); delay(100); digitalWrite(a, LOW); digitalWrite(b, HIGH); delay(100); digitalWrite(b, LOW); digitalWrite(c, HIGH); delay(100); digitalWrite(c, LOW); digitalWrite(d, HIGH); delay(100); digitalWrite(d, LOW); digitalWrite(e, HIGH); delay(100); digitalWrite(e, LOW); digitalWrite(f, HIGH); delay(100); digitalWrite(f, LOW); digitalWrite(g, LOW); digitalWrite(a, HIGH); delay(100); digitalWrite(a, LOW); digitalWrite(b, HIGH); delay(100); digitalWrite(b, LOW); digitalWrite(c, HIGH); delay(100); digitalWrite(c, LOW); digitalWrite(d, HIGH); delay(100); digitalWrite(d, LOW); digitalWrite(e, HIGH); delay(100); digitalWrite(e, LOW); digitalWrite(f, HIGH); delay(100); digitalWrite(f, LOW); digitalWrite(g, LOW); digitalWrite(a, HIGH); delay(100); digitalWrite(a, LOW); digitalWrite(b, HIGH); delay(100); digitalWrite(b, LOW); digitalWrite(c, HIGH); delay(100); digitalWrite(c, LOW); digitalWrite(d, HIGH); delay(100); digitalWrite(d, LOW); digitalWrite(e, HIGH); delay(100); digitalWrite(e, LOW); digitalWrite(f, HIGH); delay(100); digitalWrite(f, LOW); } void sensorCheck() { sensorValue = analogRead(sensorPin); } void switchCheck() { switchStatus = analogRead(analogPin); if (switchStatus >100) { randomSeed(analogRead(4)); number = random(1, 7); switchStatus = digitalRead(switchIn); } else { randomSeed(analogRead(4)); output = random(1,17); if (output == 1) { number = 0; } else if (output == 2 || output == 3) { number = 1; } else if (output == 4 || output == 5 || output == 6) { number = 2; } else if (output == 7 || output == 8 || output == 9 || output == 10) { number = 3; } else if (output == 11 || output == 12 || output == 13) { number = 4; } else if (output == 14 || output == 15) { number = 5; } else if (output == 16) { number = 6; } } } void loop() { currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; sensorCheck(); while (sensorValue < 600) { shuffle(); sensorCheck(); switchCheck(); } if (number == 0) { zero(); } else if (number == 1) { one(); } else if (number == 2) { two(); } else if (number == 3) { three(); } else if (number == 4) { four(); } else if (number == 5) { five(); } else if (number == 6) { six(); } } }
Alarm clock
you will also be able make an advanced alarm clock for you to connect to the Internet and in this way schedule your appointments more easily. By connecting your alarm clock to your network, it will take over to wake you up in case you receive an important email. You will need an Arduino UNO board, an RTC type clock, a 12mm push button switch, and a 16 by 2 backlit LCD screen. You’ll also need to choose a kit of cables and connectors to tie everything together.
Next, we detail the codes that you must enter:
#include <Pushbutton.h> // part of arduino library. Search in manage libraries. #include <EEPROM.h> #include <RTClib.h> #include <LCD.h> #include <LiquidCrystal.h> #include <LiquidCrystal_I2C.h> #include <Wire.h> LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address RTC_DS1307 RTC; const int DS1307 = 0x68; const int lightAlarm_pin = 6; const int selectButton_pin = 5; const int nextButton_pin = 4; const int upButton_pin = 3; const int downButton_pin = 2; const int alarmButton_pin = A1; const boolean alarmSystem_pin = 7; const boolean timerLightOnLED_pin = 8; Pushbutton selectButton(selectButton_pin); Pushbutton nextButton(nextButton_pin); Pushbutton upButton(upButton_pin); Pushbutton downButton(downButton_pin); Pushbutton alarmButton(alarmButton_pin); enum mainSelection { ALARM_ON_OFF = 1, //switching alarm on or off = 1 ALARM_SEASON, //change the time of starting = 2 ALARM_SET, //to set the alarm start and stop time = 3 CLOCK_SET, //to set time and date = 4 AlARM_AUTO, //Light timer automatic or manual = 5 RUN_CLOCK //Reading and displaying time and date = 6 }; enum mainSelection key = RUN_CLOCK; int alarmMinuteStart = 1; int alarmHourStart = 1; int alarmMinuteStop = 2; int alarmHourStop = 2; int alarmPlus = 0; boolean alarmOnOff = false; boolean autoManual = false; int alarmOffSet = 6; int yr = 2000; int mo = 1; int dy = 1; int hr = 0; int mn = 0; int setYr = 00; int setMo = 1; int setDy = 1; int setHr = 0; int setMn = 0; boolean daylightSaving = true; boolean aBlink = true; const int loopCheckMax = 80; //duration of the loops in the settings int loopCheck = 0; unsigned long clockDisplayCheck = millis(); //counter in the loop int lcdDisplayCheck = 0; //counter for controling the time the lcd will be on boolean timerLight = false; //set the relais for the alarm lights int timerLightStage = 0; void setup() { pinMode(lightAlarm_pin, OUTPUT); pinMode(alarmSystem_pin, OUTPUT); pinMode(timerLightOnLED_pin, OUTPUT); begin(16, 2); begin(); begin(); begin(9600); clockRunning(); clear(); on(); displayLcdFirstLine( 2); readTimeNow(); displayTimeNow(2); readAlarm(); } void loop() { key = RUN_CLOCK; lightManualyOnOff(); lcdLight(); if ((millis() - clockDisplayCheck) > 500) //Reading and displaying date and time continuesly every 0.5 second { clockRunning(); clockDisplayCheck = millis(); readTimeNow(); displayTimeNow(2); readAlarm(); displayLcdFirstLine( 0); //Basic display line alarmActivate(); //setting the alarm timerLightOnOff(); } if (selectButton.getSingleDebouncedPress()) { lcdDisplayCheck = 0; // lcd back to maximum time lcdLight(); //turns lcd on mainKeySelection(); // reads keySelection ALARM_ON_OFF,ALARM_SEASON,ALARM_SET,CLOCK_SET,RUN_CLOCK, // setCursor(0, 0); switch (key) { case ALARM_ON_OFF: setTimerOnOff(); break; case ALARM_SEASON: setTimerPlus(); break; case ALARM_SET: setHr = alarmHourStop; setMn = alarmMinuteStop; setCursor(0, 0); print("Set alarm time "); presetClockTime(alarmOffSet); if (setHr == 12) { setHr = 11; setMn = 59; } saveAlarmSet(); // readAlarm(); break; case CLOCK_SET: presetClockDate(); readTimeNow(); setHr = hr; setMn = mn; setCursor(0, 0); print("Set clock time "); presetClockTime(0); saveClock(); break; case AlARM_AUTO: alarmAutoManual(); break; } } } void clockRunning() { if (!RTC.begin() || !RTC.isrunning()) { while (!selectButton.getSingleDebouncedPress ()) { if (digitalRead(alarmSystem_pin) == LOW) digitalWrite(alarmSystem_pin, HIGH); else digitalWrite(alarmSystem_pin, LOW); delay(100); } } } void lcdLight() { if (alarmButton.getSingleDebouncedPress()) lcdDisplayCheck = 0; lcdDisplayCheck++; if (lcdDisplayCheck < 900) { //times half a second the display will be on display(); backlight(); } else { noDisplay(); noBacklight(); if (lcdDisplayCheck > 2000) lcdDisplayCheck = 900; } void timerLightOnOff() { if (timerLight) { digitalWrite(lightAlarm_pin, LOW); // the relay activates to zero digitalWrite(timerLightOnLED_pin, HIGH); } else { digitalWrite(lightAlarm_pin, HIGH); digitalWrite(timerLightOnLED_pin, LOW); } } void lightManualyOnOff() { if (!alarmOnOff) { if (nextButton.getSingleDebouncedPress()) { print (timerLight); timerLight = !timerLight; } } } void readTimeNow() { DateTime now = RTC.now(); yr = now.year(); mo = now.month(); dy = now.day(); hr = now.hour(); mn = now.minute(); } void readAlarm() { alarmHourStop = EEPROM.read(0); delay(15); alarmMinuteStop = EEPROM.read(1); delay(15); alarmPlus = EEPROM.read(2); delay(15); alarmOnOff = EEPROM.read(3); delay(50); autoManual = EEPROM.read(4); delay(50); if (alarmHourStop <= alarmOffSet) alarmHourStop = alarmOffSet + 1; alarmHourStart = alarmHourStop - alarmPlus; alarmMinuteStart = alarmMinuteStop; //calculating the timer stopping time if (alarmAutoManual) automaticTimer(); dayLightSaving(); } void alarmActivate() { if (alarmOnOff) { if ((hr - alarmHourStart) == 0) { if (mn >= alarmMinuteStart) timerLight = true; else timerLight = false; } else if (hr - alarmHourStop == 0) { if ( mn <= alarmMinuteStop) timerLight = true; else timerLight = false; } else if ((alarmHourStop - hr < alarmPlus) && (alarmHourStop - hr >= 1)) timerLight = true; else timerLight = false; } // else timerLight = false; } void displayTimeNow(int digitBlink) { char textDT[16]; sprintf(textDT, "%02d:%02d %02d/%02d/%04d", hr, mn, dy, mo, yr); //puts int variabels in the rigth format into textDT setCursor(0, 1); print(textDT); //prints in four and two digits setCursor(digitBlink, 1); if (aBlink) lcd.print(" "); else lcd.print(":"); aBlink = !aBlink; } void displayLcdFirstLine( int blinking) { if (blinking > 0) { for (int i = 1; i <= blinking; i++) { setCursor(0, 0); print(" "); setCursor(0, 0); delay(400); print("TIMER-1.00 "); //Titel setCursor(11, 0); if (alarmOnOff == false) lcd.print("off~ "); else lcd.print(" on~ "); setCursor(15, 0); if (autoManual) lcd.print("A"); else lcd.print(alarmPlus); delay(400); } } else { setCursor(0, 0); print("TIMER-1.00"); //Titel setCursor(10, 0); if (alarmOnOff == false) lcd.print(" off~ "); else lcd.print(" on~ "); setCursor(15, 0); if (autoManual) lcd.print("A"); else lcd.print(alarmPlus); delay(400); } } void mainKeySelection() { unsigned long started = millis(); delay(10); unsigned long moment; const int laps = 2000; int state = 0; int lapTime = 0; while (selectButton.isPressed()) { moment = millis(); delay(100); lapTime = moment - started; if (((lapTime) >= (0 * laps)) && ((lapTime) <= (1 * laps))) state = 1; else if (((lapTime) >= (1 * laps)) && ((lapTime) <= (2 * laps))) state = 2; else if (((lapTime) >= (2 * laps)) && ((lapTime) <= (3 * laps))) state = 3; else if (((lapTime) >= (3 * laps)) && ((lapTime) <= (4 * laps))) state = 4; else if (((lapTime) >= (4 * laps)) && ((lapTime) <= (5 * laps))) state = 5; else if (((lapTime) >= (5 * laps)) && ((lapTime) <= (6 * laps))) state = 6; delay(500); switch (state) { case 1: setCursor(0, 1); print("set alarm on/off"); break; case 2: setCursor(0, 1); print("Timer hours set "); break; case 3: setCursor(0, 1); print("Alarm time set! "); break; case 4: setCursor(0, 1); print("Clock time set! "); break; case 5: setCursor(0, 1); print("Alarm man/auto"); break; case 6: setCursor(0, 1); print("Back to the menu"); break; } if ((lapTime) > (6 * laps)) { //back into the same routine started = moment; } } key = state;// keySelection ALARM_ON_OFF,ALARM_SEASON,ALARM_SET,CLOCK_SET,AlARM_AUTO,RUN_CLOCK, } void setTimerOnOff() { boolean setAlarmOnOff = alarmOnOff; setCursor(0, 0); print("switch it now "); setCursor(0, 1); print("Timer is: "); setCursor(11, 1); if (alarmOnOff == false) lcd.print("[off] "); else lcd.print("[on] "); while (!selectButton.getSingleDebouncedPress ()) { if (upButton.getSingleDebouncedPress() setCursor(11, 1); if (setAlarmOnOff == false) lcd.print("[off] "); else lcd.print("[on] "); delay(30); } if (alarmOnOff != setAlarmOnOff) { write(3, setAlarmOnOff); delay(15); } } void setTimerPlus() { readAlarm(); int setAlarmPlus = alarmPlus; setCursor(0, 0); print("stop time: 00:00"); if (alarmHourStop < 10) lcd.setCursor(12, 0); else lcd.setCursor(11, 0); print(alarmHourStop); if (alarmMinuteStop < 10) lcd.setCursor(15, 0); else lcd.setCursor(14, 0); print(alarmMinuteStop); setCursor(0, 1); print("hours on: "); setCursor(11, 1); print(setAlarmPlus); while (!selectButton.getSingleDebouncedPress ()) { setCursor(11, 1); if (alarmHourStop > 6) { / if (upButton.isPressed() && (setAlarmPlus < 6)) setAlarmPlus++; if (downButton.isPressed() && (setAlarmPlus > 1)) setAlarmPlus--; print(setAlarmPlus); } else { setCursor(0, 0); print("Set alarm stop "); // in case the alarm is set too early in the day. Minimum after 6 am setCursor(0, 1); print("timer first !!!!"); } delay(250); } if (alarmPlus != setAlarmPlus) { write(2, setAlarmPlus); delay(15); } } void presetClockDate() { int loops = 20; boolean pBlink = false; const int loopMax = 25; //Moment of refreshing the LCD int loopCheck = 0; //to controll if if there is any interaction enum YMD {YEAR = 1, MONTH, DAY}; enum YMD YrMoDy = YEAR; setYr = (yr - 2000); setMo = mo; setDy = dy; setHr = hr; setMn = mn; setCursor(0, 0); print("Set Year // Date"); while (loopCheck < loopCheckMax) { delay(10); loops++; if (YrMoDy == YEAR) { setYear(); loopCheck = 0; } if (YrMoDy == MONTH) { setMonth(); loopCheck = 0; } if (YrMoDy == DAY) { setDay(); loopCheck = 0; } if (YrMoDy > DAY) loopCheck = loopCheckMax; if (nextButton.getSingleDebouncedPress()) YrMoDy = YrMoDy + 1; if (loops > loopMax) { setCursor(0, 1); print("Y-00 Mo-00 Dy-00"); if (setYr < 10) { setCursor(2, 1); print("00"); setCursor(3, 1); } else lcd.setCursor(2, 1); print(setYr); if (setMo < 10) { setCursor(8, 1); print("00"); setCursor(9, 1); } else lcd.setCursor(8, 1); print(setMo); if (setDy < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } else lcd.setCursor(14, 1); print(setDy); if (YrMoDy == YEAR)lcd.setCursor(2, 1); if (YrMoDy == MONTH)lcd.setCursor(8, 1); if (YrMoDy == DAY)lcd.setCursor(14, 1); if (pBlink)lcd.print(" "); pBlink = !pBlink; loops = 0; loopCheck++; } if (selectButton.getSingleDebouncedPress ()) { loopCheck = loopCheckMax; } delay(10); } setCursor(0, 0); print(" "); setCursor(0, 1); print(" "); } void presetClockTime(int StartingPointHour) { int loops = 20; boolean pBlink = false; const int loopMax = 25; //Moment of refreshing the LCD int loopCheck = 0; //to controll if if there is any interaction // setHr = hr; setMn = mn; enum HM {HOUR = 1, MINUTE}; enum HM HrMn = HOUR; while (loopCheck < loopCheckMax) { delay(10); loops++; if (HrMn == HOUR) { //Setting hour function setHr = hourReturn(setHr, StartingPointHour); delay(10); loopCheck = 0; } if (HrMn == MINUTE) { //Setting minute function setMn = minuteReturn(setMn); delay(10); loopCheck = 0; } if (HrMn > MINUTE)loopCheck = loopCheckMax; if (nextButton.getSingleDebouncedPress()) HrMn = HrMn + 1; if (loops > loopMax) { // displaying whit a long interval setCursor(0, 1); print("hour:00 minu:00"); if (setHr < 10) { setCursor(5, 1); print("00"); setCursor(6, 1); } else lcd.setCursor(5, 1); print(setHr); if (setMn < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } else lcd.setCursor(14, 1); print(setMn); if (HrMn == HOUR)lcd.setCursor(5, 1); if (HrMn == MINUTE)lcd.setCursor(14, 1); if (pBlink)lcd.print(" "); pBlink = !pBlink; loops = 0; loopCheck++; } if (selectButton.getSingleDebouncedPress ()) { //breaks the loop by the select button or by time lapsed loopCheck = loopCheckMax; } delay(10); } setCursor(0, 0); print(" "); setCursor(0, 1); print(" "); } int lastDayOfTheMonth(int setMonth) { switch (setMonth) { case 1: //January return 31; break; case 2: //February if ((setYr % 4) == 0) return 29; else return 28; break; case 3: //March return 31; break; case 4: //April return 30; break; case 5: //May return 31; break; case 6: //June return 30; break; case 7: //Juli return 31; break; case 8: //August return 31; break; case 9: //September return 30; break; case 10: //October return 31; break; case 11: //November return 30; break; case 12: //December return 31; break; } } void setYear() { int teller = 0; if (setYr < 18) setYr = 17; while (upButton.isPressed()) { if (setYr < 99) setYr++; setCursor(2, 1); print(setYr); teller++; if (teller > 7) delay(100); else delay(250); } while (downButton.isPressed()) { if (setYr > 17) setYr--; setCursor(2, 1); print(setYr); teller++; if (teller > 7) delay(100); else delay(250); } } void setMonth() { while (upButton.isPressed()) { if (setMo < 12) setMo++; setCursor(8, 1); if (setMo < 10) { setCursor(8, 1); print("00"); setCursor(9, 1); } print(setMo); delay(250); } while (downButton.isPressed()) { if (setMo > 1) setMo--; setCursor(8, 1); if (setMo < 10) { setCursor(8, 1); print("00"); setCursor(9, 1); } print(setMo); delay(250); } } void setDay() { int teller = 0; int maxD = maxDay(); while (upButton.isPressed()) { if (setDy < maxD) setDy++; setCursor(14, 1); if (setDy < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } print(setDy); teller++; if (teller > 7) delay(100); else delay(250); } while (downButton.isPressed()) { if (setDy > 1) setDy--; setCursor(14, 1); if (setDy < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } print(setDy); teller++; if (teller > 7) delay(100); else delay(250); } } int maxDay() { switch (setMo) { case 1: return 31; case 2: if ((setYr % 4) == 0)return 29; else return 28; case 3: return 31; case 4: return 30; case 5: return 31; case 6: return 30; case 7: return 31; case 8: return 31; case 9: return 30; case 10: return 31; case 11: return 30; case 12: return 31; } } int hourReturn(int setHour, int startingPoint) { if (setHour < startingPoint) setHour = startingPoint; while (upButton.isPressed()) { if (setHour < 24) setHour++; setCursor(5, 1); if (setHour < 10) { setCursor(5, 1); print("00"); setCursor(6, 1); } print(setHour); delay(200); } while (downButton.isPressed()) { if (setHour > startingPoint) setHour--; setCursor(5, 1); if (setHour < 10) { setCursor(5, 1); print("00"); setCursor(6, 1); } print(setHour); delay(200); } return setHour; } int minuteReturn(int setMinute) { while (upButton.isPressed()) { if (setMinute < 60) setMinute++; setCursor(14, 1); if (setMinute < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } print(setMinute); delay(200); } while (downButton.isPressed()) { if (setMinute > 1) setMinute--; setCursor(14, 1); if (setMinute < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } print(setMinute); delay(200); } return setMinute; } void saveClock() { boolean saveNew = true; setCursor(0, 1); print("00:00 00/00/2000"); //setHr is still two digets if (setHr < 10) lcd.setCursor(1, 1); else lcd.setCursor(0, 1); print(setHr); if (setMn < 10) lcd.setCursor(4, 1); else lcd.setCursor(3, 1); print(setMn); if (setDy < 10) lcd.setCursor(7, 1); else lcd.setCursor(6, 1); print(setDy); if (setMo < 10) lcd.setCursor(10, 1); else lcd.setCursor(9, 1); print(setMo); setCursor(14, 1); print(setYr); setCursor(0, 0); print("save clock?: yes"); while (!selectButton.getSingleDebouncedPress ()) { setCursor(13, 0); if (saveNew == false) lcd.print("no "); else lcd.print("yes"); if ((upButton.getSingleDebouncedPress() == 1) || (downButton.getSingleDebouncedPress() == 1))saveNew = !saveNew;; delay(80); } if (saveNew = true) { int setSec = 0; int setWkDy = 1; delay(100); // The following codes transmits the data to the RTC beginTransmission(DS1307); write(byte(0)); write(decToBcd(setSec)); write(decToBcd(setMn)); write(decToBcd(setHr)); write(decToBcd(setWkDy)); //not in use write(decToBcd(setDy)); write(decToBcd(setMo)); write(decToBcd(setYr)); //has to be two digits write(byte(0)); endTransmission(); // Ends transmission of data } delay(100); } byte decToBcd(byte val) { return ((val / 10 * 16) + (val % 10)); } void saveAlarmSet() { boolean saveNew = true; setCursor(0, 1); print("hour:00 minu:00"); if (setHr < 10) { setCursor(5, 1); print("00"); setCursor(6, 1); } else lcd.setCursor(5, 1); print(setHr); if (setMn < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } else lcd.setCursor(14, 1); print(setMn); setCursor(0, 0); print("save Alarm?: yes"); while (!selectButton.getSingleDebouncedPress ()) { setCursor(13, 0); if (saveNew == false) lcd.print("no "); else lcd.print("yes"); if ((upButton.getSingleDebouncedPress() == 1) || (downButton.getSingleDebouncedPress() == 1))saveNew = !saveNew;; delay(80); } if (saveNew = true) { write(0, setHr); delay(15); write(1, setMn); delay(15); } delay(100); } void alarmAutoManual() { boolean autoManualNew = autoManual; //using this variable makes the display less restless setCursor(0, 1); print("Lights off 00:00"); if (alarmHourStop < 10) { setCursor(11, 1); print("00"); setCursor(12, 1); } else lcd.setCursor(11, 1); print(alarmHourStop); if (alarmMinuteStop < 10) { setCursor(14, 1); print("00"); setCursor(15, 1); } else lcd.setCursor(14, 1); print(alarmMinuteStop); setCursor(0, 0); if (autoManualNew)lcd.print("Timer: automatic"); else lcd.print("Timer: manual "); while (!selectButton.getSingleDebouncedPress ()) { if (upButton.getSingleDebouncedPress() || downButton.getSingleDebouncedPress()) { autoManualNew = !autoManualNew; setCursor(0, 0); if (autoManualNew)lcd.print("Timer: automatic"); else lcd.print("Timer: manual "); } delay(80); } if (autoManualNew != autoManual) { write(4, autoManualNew); delay(20); } } void automaticTimer() { switch (mo) { case 1: alarmOffSet = 6; break; case 2: alarmOffSet = 5; break; case 3: alarmOffSet = 5; break; case 4: alarmOffSet = 4; break; case 5: alarmOffSet = 3; break; case 6: alarmOffSet = 2; break; case 7: alarmOffSet = 2; break; case 8: alarmOffSet = 3; break; case 9: alarmOffSet = 4; break; case 10: alarmOffSet = 5; break; case 11: alarmOffSet = 6; break; case 12: alarmOffSet = 6; break; } } void dayLightSaving() { boolean daylightSavingNew = false; switch (yr) { case 2017: if ((mo == 3 && dy >= 26) || (mo > 3 && mo < 10) || (mo == 10 && dy < 29)) daylightSavingNew = true; break; case 2018: if ((mo == 3 && dy >= 25) || (mo > 3 && mo < 10) || (mo == 10 && dy < 28)) daylightSavingNew = true; break; case 2019: if ((mo == 3 && dy >= 31) || (mo > 3 && mo < 10) || (mo == 10 && dy < 27)) daylightSavingNew = true; break; case 2020: if ((mo == 3 && dy >= 29) || (mo > 3 && mo < 10) || (mo == 10 && dy < 25)) daylightSavingNew = true; break; case 2021: if ((mo == 3 && dy >= 28) || (mo > 3 && mo < 10) || (mo == 10 && dy < 31)) daylightSavingNew = true; break; case 2022: if ((mo == 3 && dy >= 27) || (mo > 3 && mo < 10) || (mo == 10 && dy < 30)) daylightSavingNew = true; break; case 2023: if ((mo == 3 && dy >= 26) || (mo > 3 && mo < 10) || (mo == 10 && dy < 29)) daylightSavingNew = true; break; case 2024: if ((mo == 3 && dy >= 31) || (mo > 3 && mo < 10) || (mo == 10 && dy < 27)) daylightSavingNew = true; break; case 2025: if ((mo == 3 && dy >= 30) || (mo > 3 && mo < 10) || (mo == 10 && dy < 26)) daylightSavingNew = true; break; case 2026: if ((mo == 3 && dy >= 29) || (mo > 3 && mo < 10) || (mo == 10 && dy < 25)) daylightSavingNew = true; break; case 2027: if ((mo == 3 && dy >= 28) || (mo > 3 && mo < 10) || (mo == 10 && dy < 31)) daylightSavingNew = true; break; case 2028: if ((mo == 3 && dy >= 26) || (mo > 3 && mo < 10) || (mo == 10 && dy < 29)) daylightSavingNew = true; break; case 2029: if ((mo == 3 && dy >= 25) || (mo > 3 && mo < 10) || (mo == 10 && dy < 28)) daylightSavingNew = true; break; } if (daylightSavingNew != daylightSaving) { if (hr > 2) { if (daylightSavingNew) hr = hr + 1; if (!daylightSavingNew) hr = hr - 1; daylightSaving = daylightSavingNew; } } }
Training jacket for cyclists
It is worth mentioning that there are different types of plates to design unique devices. Just like a jacket with lights that can indicate which direction to take when moving along the roads of city. With a special plate for clothesyou can create this device and insert it into your jacket without any problem.
In this project you will need an Arduino board of the LilyPad model, also a battery holder, 5 white leds for the board version, HC-SR04 ultrasonic sensor, a sparkfun button board and a buzzer. Also, You must have connector kits and cables that serve to join the components.
The code that you will need to enter into your Arduino board is:
#include <Ultrassonico.h> #define Echo 10 #define Trigger 11 #define zumbador 3 Ultrassonico ultra ( Echo , Trigger ); // Eco, disparador configuración vacía () { Serial . comenzar ( 9600 ); pinMode ( 4 , SALIDA ); pinMode ( 5 , SALIDA ); pinMode ( zumbador , SALIDA ); } bucle vacío () { uint16_t cm = ultra . centimetrosUltra (); De serie . println ( cm ); si (( cm > 80 ) y ( cm < 130 )) { tono ( zumbador , 3000 ); escritura digital( 4 , BAJO ); escritura digital ( 5 , BAJO ); retraso ( 500 ); ni uno( zumbador ); demora( 500 ); } si (( cm > 30 ) y ( cm < 50 )) { tono ( zumbador , 2000 ); escritura digital ( 4 , ALTA ); escritura digital ( 5, BAJO ); demora ( 100 ); ni uno( zumbador ); demora ( 100 ); } si ( cm < 30 ) { tono ( zumbador , 1000 ); digitalWrite ( 4 , BAJO ); escritura digital ( 5 , ALTA ); retraso ( 30 ); noTone ( zumbador ); retraso ( 30 ); } retraso ( 50 ); }
advanced semaphore
Several buttons are used for this device that indicate the proximity of a car. In this way, its function is activated and deactivated, changing green while a car is far away, and red while a car is approaching a junction. To carry out this project you will need a YUN platean Arduino UNO, a real time clock, resistors, leds, a 433 MHz module, an SD memory card, an HC-SR04 ultrasonic sensor and cables.
Then you will have to go to programming by entering:
#define RedLED 5 #define OrangeLED 6 #define GreenLED 7 #define rx_pin 9 #include <VirtualWire.h> // Para los módulos RF 433 MHz #include <TimeAlarms.h> // Alarma #include <Wire.h> #include "RTClib.h" #include <Process.h> long UnixTime_green_1 ; long UnixTime_red_1; long UnixTime_green_2; long UnixTime_red_2; long s_till_orange; RTC_DS3231 rtc; char StringReceived[22]; boolean i; int interval = 5; // in seconds int distance; // in cm void setup() { begin(); //rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); begin(9600); begin(); // Initialize Bridge vw_setup(2000); // Bits per sec vw_set_rx_pin ( rx_pin ); vw_rx_start (); Alarma . timerRepeat ( intervalo , UpdateTrafficLData ); // siguiente semáforo verde, en rojo... Alarma . timerRepeat ( 1 , PrintCurrentTime ); pinMode ( GreenLED , SALIDA ); pinMode ( OrangeLED , SALIDA ); pinMode ( LED rojo , SALIDA ); digitalWrite ( GreenLED , BAJO ); digitalWrite ( OrangeLED , BAJO ); digitalWrite ( LED rojo , BAJO ); Serial . println ( "Instalación finalizada" ); } bucle vacío () { Alarma . retraso ( 0 ); RF_Listen (); } void RF_Listen () { uint8_t buf [ VW_MAX_MESSAGE_LEN ]; uint8_t buflen = VW_MAX_MESSAGE_LEN ; si ( vw_get_message ( buf , y buflen )) { int a ; para ( a = 0 ; a < buflen ; a ++ ) { StringReceived [ a ] = char ( buf [ a ]); } sscanf ( StringReceived , "% d" , & distancia ); MySQL_UpdateDistance (); Serial . print ( "Distancia:" ); Serial . println ( distancia ); } memset ( StringReceived , 0 , sizeof ( StringReceived )); } void UpdateTrafficLData () { DateTime ahora = rtc . ahora (); si ( i == 1 ) { UnixTime_green_1 = ahora . unixtime () + intervalo + 1 ; UnixTime_red_1 = ahora . unixtime () + 2 * intervalo + 1 ; UnixTime_green_2 = ahora . unixtime () + 3 * intervalo + 1 ; UnixTime_red_2 = ahora . unixtime () + 4 * intervalo + 1 ; MySQL_UpdateTrafficLData (); i = 0 ; } más si ( i == 0 ) { UnixTime_red_1 = ahora . unixtime () + intervalo + 1 ; UnixTime_green_1 = now.unixtime() + (2 * interval) + 1; UnixTime_red_2 = now.unixtime()+ 3 * interval + 1; UnixTime_green_2 = now.unixtime() + 4 * interval + 1; MySQL_UpdateTrafficLData(); i = 1; } print(" Green_1 at "); print(UnixTime_green_1); print(" Red_1 at "); print(UnixTime_red_1); print(" Green_2 at "); print(UnixTime_green_2); print(" Red_2 at "); println(UnixTime_red_2); } void MySQL_UpdateTrafficLData() { long dataArray[4]={UnixTime_green_1, UnixTime_red_1, UnixTime_green_2,UnixTime_red_2}; Process p; begin("/mnt/sda1/MySQL_UpdateTrafficLData.php"); for (int b = 0; b < 4; b++){ addParameter(String(dataArray[b])); } run(); while (p.available() > 0) { char c = p.read(); print(c); } flush(); } void MySQL_UpdateDistance(){ Process p; begin("/mnt/sda1/MySQL_UpdateDistance.php"); addParameter(String(distance)); run(); while (p.available() > 0) { char c = p.read(); print(c); } flush(); } void PrintCurrentTime () { DateTime ahora = rtc . ahora (); SetLEDsTrafficL (); Serial . imprimir ( ahora . hora (), DEC ); Serial . imprimir ( ':' ); Serial . imprimir ( ahora . minuto (), DEC ); Serial . imprimir ( ':' ); Serial . imprimir ( ahora . segundo (), DEC ); Serial . imprimir ( "" ); Serial . println ( ahora . unixtime ()); } void SetLEDsTrafficL () { DateTime ahora = rtc . ahora (); s_till_orange = UnixTime_red_1 - ahora . unixtime (); si ( i == 0 ) { digitalWrite ( GreenLED , BAJO ); digitalWrite ( OrangeLED , BAJO ); escritura digital ( LED rojo , ALTO ); } if ( i == 1 && s_till_orange <= 3 ) { digitalWrite ( GreenLED , BAJO ); digitalWrite ( OrangeLED , ALTA ); digitalWrite ( LED rojo , BAJO ); } if ( i == 1 && s_till_orange > 3 ) { digitalWrite ( GreenLED , HIGH ); digitalWrite ( OrangeLED , BAJO ); digitalWrite ( LED rojo , BAJO ); } }
home alarm
Building a home alarm It is one of the most affordable and eye-catching projects. This device is used to detect any type of presence that wants to invade our home. If we connect an Arduino board with some motion detectors, lights and a sound meter, we can build our own alarm. In addition to your Arduino UNO board, you will need a generic protoboard, an ultrasonic sensor, a buzzer and a kit of cables and connectors to join the entire installation..
You will need to write the following commands in the Arduino IDE:
const int TrigPin = 2 ; const int EchoPin = 3 ; const int Datos = 8 ; flotar cm ; configuración vacía () { Serial . comenzar ( 9600 ); pinMode ( TrigPin , SALIDA ); pinMode ( EchoPin , ENTRADA ); pinMode ( Datos , SALIDA ); } bucle vacío () { digitalWrite ( TrigPin , BAJO ); delayMicroseconds ( 2 ); digitalWrite ( TrigPin , ALTO ); delayMicroseconds ( 10 ); digitalWrite ( TrigPin , BAJO ); cm = pulseIn ( EchoPin , ALTO ) / 0 ; // El tiempo de eco se convierte en cm cm = ( int ( cm * 0 )) / 100.0 ; Serial . println (); if ( cm < 15 ) { // si está colocando el sensor detrás de la puerta será necesario usar ">" sysmbole en lugar de ">" ps. Hay que tener en cuenta que la puerta esté a menos de 15 cm de distancia con el sensor digitalWrite ( Datos , ALTO ); retraso ( 200 ); Serial . print ( "Puerta cerrada" ); } demás { digitalWrite ( Datos , BAJO ); retraso ( 200 ); Serial . print ( "Puerta abierta" ); } retraso ( 200 ); }
spy camera
For many, being able to fit items into spaces as small as a cup is a huge challenge, let alone when we refer to a spy camera. If you want to carry out this project, you will have to insert an accelerometer module to activate and take a picture through the movement of the object used.
The components and supplies that will be needed in this project They should include an Arduino Micro board, CdS photocell resistor, gate eye, and a Raspberry Pi board with its LED display. Connectors and the object where you want to install the spy camera.
When you have all the previous elements you will have to enter this code:
long previousMillis = 0 ; tiempo de calibración largo = 5000 ; long startMillis = 0 ; int sensorMin = 1024 ; int sensorMax = 0 ; int promedio = 0 ; int umbral = 5 ; bool lastState = true ; bool isClosed = true ; #include "Keyboard.h" configuración vacía () { Serial . comenzar ( 9600 ); Serial . println ( " Configuración " ); Teclado . comenzar (); startMillis = millis (); } bucle vacío () { unsigned largo currentMillis = millis (); int sensorValue = analogRead ( A0 ); //Serial.println(sensorValue); si ( currentMillis - startMillis < calibrationtime ) { // guarda la última vez que hiciste parpadear el LED // imprime el valor que leíste: int ElapsedTime = currentMillis - startMillis ; Serial . println (tiempo transcurrido ); Serial . println ( sensorMin ); Serial . println ( sensorMax ); if ( sensorValue < sensorMin ) { sensorMin = sensorValue ; promedio = ( sensorMin + sensorMax ) / 2; } if ( sensorValue > sensorMax ) { sensorMax = sensorValue ; promedio = ( sensorMin + sensorMax ) / 2 ; } retraso ( 100 ); } else { if ( sensorValue > promedio + umbral ) { isClosed = false ; if ( lastState ! = isClosed ) { } } else { isClosed = true ; if ( lastState ! = isClosed) { Teclado . imprimir ( "" ); } } lastState = isClosed ; retraso ( 100 ); } }
automated garden
If you want to ensure that your plants are in good condition when you are away from home, you can consider creating an automatic irrigation and temperature system, so you can keep your garden cared for at all times.
For these types of projects, It is necessary to include sensors that can detect climate change, in order to adapt the system. In order to water and monitor your garden plants you will need the Arduino Nano R3 model, a DHT11 version temperature and humidity sensor, a generic relay and general connectors for the union.
You will have to program the panel by entering:
#include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <DHT.h> #define DHTPIN 2 // a qué pin estamos conectados #define DHTTYPE DHT11 // DHT 11 #define OLED_RESET 4 Pantalla Adafruit_SSD1306 ( OLED_RESET ); DHT DHT ( DHTPIN , DHTTYPE ); Información de cadena ; riego booleano = falso , estado = falso ; configuración vacía () { Alambre . comenzar (); dht . comenzar (); // inicializar dht pantalla . comenzar ( SSD1306_SWITCHCAPVCC , 0x3C ); Serial . comenzar ( 9600 ); } void displayTempHumid(){ delay(2000); // Lectura de humedad y temperatura float h = dht.readHumidity(); float t = dht.readTemperature(); float f = dht.readTemperature(true); if (isnan(h) || isnan clearDisplay(); // clearing the display setTextColor(WHITE); //setting the color setTextSize(1); //set the font size setCursor(5,0); //set the cursor coordinates print("Failed to read from DHT sensor!"); return; } clearDisplay(); setTextColor(WHITE); setTextSize(1); setCursor(0,0); print("Humidity: "); print(h); print(" %t"); setCursor(0,10); pantalla . print ( "Temperatura:" ); pantalla . imprimir ( t ); pantalla . imprimir ( "C" ); pantalla . setCursor ( 0 , 20 ); pantalla . print ( "Temperatura:" ); pantalla . imprimir ( f ); pantalla . imprimir ( "F" ); } bucle vacío () { displayTempHumid (); pantalla . display (); }
smart heating system
The Arduino UNO board It is one of the most used for advantageous projects and on a large scale. One of the powers of having an advanced system is that you can manage your home’s heating from your smartphone and wherever you are. Incorporating a temperature sensor, some resistors, along with a stable connection to a board structure, you will have the function of this spectacular system.
addition to the plate must have for this heating system a board for 8 channel 5v relays, a thermoelectric actuator MT8-230-NC and a kit of cables that will help you join the pins with the above items.
When you are ready, you will only have to enter these codes in the IDE:
#include <avr / wdt.h> #define VALVE_TIME 3000L #ifdef FAST_MODE #define PUMP_MAINTENANCE_TIME 108000L #else #define PUMP_MAINTENANCE_TIME 1300000L #endif #define PUMP_ACTIVATION_TIME 5000L #define COOLDOWN_TIME 18000L #include "./Devices.h" struct Zone { String name; Valve valve; Thermostat thermostat; }; // Configuración del bloque #define HEATER_PIN 4 #define FU_PUMP_PIN 5 #define LIVING_VALVE 7 #define KITCHEN_VALVE 6 #define DINING_VALVE 3 #define LIVING_THERMO 8 #define KITCHEN_THERMO 9 #define DINING_THERMO 11 #define NO_ZONE_THERMO 10 #define HEATING_LED 12 #define INDICATION_LED 13 #define NR_ZONES 3 Zone Zones[NR_ZONES] = { {"Living Room", Valve(LIVING_VALVE, "Living Valve"), Thermostat(LIVING_THERMO, "Living Thermostat")}, {"Kitchen Area", Valve(KITCHEN_VALVE,"Kitchen Valve"), Thermostat(KITCHEN_THERMO,"Kitchen Thermostat")}, {"Dining Room", Valve(DINING_VALVE, "Dining Valve"), Thermostat(DINING_THERMO, "Dining Thermostat")}}; // Fin de la configuración del bloque LED iLED(INDICATION_LED, "Indicator LED"); LED hLED(HEATING_LED, "Heating LED"); Manipulator CV(HEATER_PIN, "CV Heater"); Pump FUPump(FU_PUMP_PIN, "Floor Unit Pump"); Thermostat ZonelessThermo(NO_ZONE_THERMO, "Zoneless Thermostat"); void printConfiguration() { println("------ Board Configuration: ---------"); Print(); Print(); Print(); Print(); Print(); for(int i=0; i<NR_ZONES; i++) { print("Zone["); Serial.print(i+1); print("]: "); Serial.println(Zones[i].name); Serial . imprimir ( "-" ); Zonas [ i ]. válvula . Imprimir (); Serial . imprimir ( "-" ); Zonas [ i ]. termostato . Imprimir (); } Serial . println ( "-------------------------------------" ); } { publico : estados de enumeración { ralentí , sobre , enfriarse }; privado : // vars estados _State ; unsigned long cooldownCount ; publico : //constructor StateMAchine () { _State = inactivo ; } // Getter estados const & operator () () const { return _State ; } // Setter operador void () ( estados const y newState ) { printTimeStamp (); Serial . print ( ": cambio de estado de [" ); Imprimir (); _State = newState ; print("] to ["); Print(); println("]"); // deal with transition actions to the new state switch(_State) { case idle: Off(); Off(); // stop heating Off(); allValvesOff(); break; case on: On(); On(); break; case cooldown: Off(); allValvesOn(); break; default: println("WARNING Unhandled State transition"); break; } } void doProcessingActions() { switch(_State) { case on: onProcessing(); break; case cooldown: coolDownProcessing(); break; case idle: idleProcessing(); break; default: println("ERROR Unhandled State"); break; } } void setCoolDownNeeded() { cooldownCount = COOLDOWN_TIME; } bool whileCoolDownNeeded() { if (cooldownCount > 0) { cooldownCount--; } return checkCoolDownNeeded(); } bool checkCoolDownNeeded() { return (cooldownCount> 0); } void Print() { switch(_State) { case idle: print("idle"); break; case on: print("on"); break; case cooldown: print("cooldown"); break; } } }; State CVState; void setup() { begin(115200); printTimeStamp(); print(": "); #ifdef FAST_MODE println("CV Zone Controller started in TestMode!n" " - Board time runs ca 50 times fastern" " - Pump maintenance cycle runs ever 3 hours instead once per 36 hours"); #else println("CV Zone Controller started. Time stamps (dd:hh:mm:ss)"); #endif println(" - Time stamps format (dd:hh:mm:ss)"); printConfiguration(); wdt_enable(WDTO_1S); } void loop() { #ifdef FAST_MODE delay(2); #else delay(100); #endif Alternate(); Update(); for (int i=0; i<NR_ZONES; i++) { Zones[i].valve.Update(); } wdt_reset(); doProcessingActions(); } void onProcessing() { if (ProcessThermostats()) { if (FloorPumpingAllowed()) { On(); } else { Off(); } } else if ( CVState.checkCoolDownNeeded() ) { CVState(State::cooldown); } else { CVState(State::idle); } } void coolDownProcessing() { Alternate(); if (HeatingRequested()) { CVState(State::on); } else { if ( CVState.whileCoolDownNeeded() ) { if (FloorPumpingAllowed()) { On(); } else { Off(); } } else { CVState(State::idle); } } } void idleProcessing() { if (HeatingRequested()) { CVState(State::on); } else { if ( FUPump.doMaintenanceRun()) { if (FUPump.IsOff()) { if ( allValvesOpen() == false ) { printTimeStamp(); Serial.println(": Start daily cycle for Floor Unit Pump; open valves: "); allValvesOn(); } if (FloorPumpingAllowed()) { printTimeStamp(); Serial.println(": Start daily cycle for Floor Unit Pump; start pump "); On(); } } } else if (FUPump.IsOn()) { printTimeStamp(); Serial.println(": Stop daily cycle for Floor Unit Pump; stop pump and close valves"); Off(); allValvesOff(); } } }
Shutter for high-speed photography
If you are a photographer with great potential that seeks to capture the public’s attention with fascinating images, you can make use of an Arduino microcontroller to take an optimal photo at a high speed with your GoPro. You will need an Arduino model MKR1000, generic LED lights, a breadboard, a 221 ohm resistor, a sparkfun 12mm push button switch and jumper wires.
You must unite all these electronic components and then write the following in the IDE:
#include <GoPRO.h> #define CONNECT_PRESSED 1 #define ON_PRESSED 2 #define CAPTURE_PRESSED 3 char ssid[] = "yourNetwork"; char pass[] = "yourPassword"; const int buttonConnect = A1; const int buttonOn = A2; const int buttonCapture = A3; const int connectLED = 3; const int onLED = 4; const int captureLED = 5; bool onStatus = true; bool captureStatus = false; void setup() { pinMode(buttonConnect, INPUT_PULLUP); pinMode(buttonOn, INPUT_PULLUP); pinMode(buttonCapture, INPUT_PULLUP); pinMode(connectLED, OUTPUT); pinMode(onLED, OUTPUT); pinMode(captureLED, OUTPUT); digitalWrite(connectLED, LOW); digitalWrite(onLED, HIGH); digitalWrite(captureLED, LOW); } void loop() { switch (isButtonPressed()) { default: break; case CONNECT_PRESSED: if (!GoPRO.checkConnection()) { if (GoPRO.begin(ssid, pass)) { digitalWrite(connectLED, HIGH); } else { digitalWrite(connectLED, LOW); } } else { digitalWrite(connectLED, HIGH); } break; case ON_PRESSED: if (GoPRO.checkConnection()) { onStatus = !onStatus; if (onStatus) { if (GoPRO.turnOn()) digitalWrite(onLED, HIGH); } else { if (GoPRO.turnOff()) digitalWrite(onLED, LOW); } } break; case CAPTURE_PRESSED: if (GoPRO.checkConnection()) { captureStatus = !captureStatus; if (captureStatus) { if (GoPRO.startCapture()) digitalWrite(captureLED, HIGH); } else { if (GoPRO.stopCapture()) digitalWrite(captureLED, LOW); } } break; } delay(100); } int isButtonPressed() { if (digitalRead(buttonConnect) == LOW) return 1; else if (digitalRead(buttonOn) == LOW) return 2; else if (digitalRead(buttonCapture) == LOW) return 3; else return 0; }
Ambient light sensor
The programming of this project is simple, so we did not want to leave aside the idea of having your own mood lights for any room in your home. You will make them reflect on the wall, giving a unique style. You will need a SparkFun type Pro Mini 328 board, the TEMT6000 ambient light sensor, AA battery holder, cables and connectors in general.
Enter this code to program your Arduino:
int temt6000Pin = A0; float light; int light_value; void setup() { begin(112500); pinMode(temt6000Pin, INPUT); //data pin for ambientlight sensor pinMode(13, OUTPUT); } void loop() { int light_value = analogRead(temt6000Pin); light = light_value * 0.0976;// percentage calculation println(light); delay(100); if (light_value > 1000) { digitalWrite(13, HIGH); } else {digitalWrite(13,LOW);} }
robot that folds clothes
This project is categorized among the most complex that can be developed, it is a very creative and exclusive invention, which also requires much more money than a common design. With the help of an Arduino board, you can create a robot and program it with a mechanism to fold your clothes. or perform any other task. You must have an Arduino 101, a robotic arm that you can get for around €25, four micro servo motors, an Ethernet module and an Android mobile.
Then, you are going to have to execute these commands in the programming environment:
#include <Servo.h> // Used pins #define GRIPPER_SERVO 9 #define UPPER_JOINT_SERVO 6 #define LOWER_JOINT_SERVO 5 #define BASE_ROTATOR_JOINT_SERVO 3 #define GRIPPER_OPEN 0 #define GRIPPER_CLOSED_SOFT 1 #define GRIPPER_CLOSED_MEDIUM 2 #define GRIPPER_CLOSED_HARD 3 // Gripper configuration #define GRIPPER_OPEN_ANGLE 150 // The angle of the servo in different positions #define GRIPPER_CLOSED_SOFT_ANGLE 75 // Closing with low force (less stressful on the servo) #define GRIPPER_CLOSED_MEDIUM_ANGLE 65 // Closing with medium force (slightly stressful on the servo) #define GRIPPER_CLOSED_HARD_ANGLE 0 // Closing with high force (quite stressful on the servo, it will also heat up) #define SERVO_ANGLE_UPPER_LIMIT 170 #define SERVO_ANGLE_LOWER_LIMIT 0 #define SERVO_ANGLE_RESTING 90 #define MIN_MOVEMENT_DELAY 2 // Commands #define MOVE_GRIPPER 'G' #define MOVE_ARM 'A' Servo gripper, upperJoint, lowerJoint, baseRotator; unsigned int movementDelay = 5; int gripperState; int targetUpperJointAngle; int targetLowerJointAngle; int targetBaseRotatorAngle; float currentUpperJointAngle, currentLowerJointAngle, currentBaseRotatorAngle; float upperJointStep, lowerJointStep, baseRotatorStep; unsigned long lastStepTime = 0; void setup() { begin(115200); attach(GRIPPER_SERVO); attach(UPPER_JOINT_SERVO); attach(LOWER_JOINT_SERVO); attach(BASE_ROTATOR_JOINT_SERVO); gripperState = GRIPPER_CLOSED_SOFT; targetUpperJointAngle = currentUpperJointAngle = 140; targetLowerJointAngle = currentLowerJointAngle = 45; targetBaseRotatorAngle = currentBaseRotatorAngle = 85; moveGripper(gripperState); moveTo(targetUpperJointAngle, targetLowerJointAngle, targetBaseRotatorAngle); } void loop() { if (Serial1.available() > 0) { char command = Serial1.read(); if (command == MOVE_GRIPPER) { updateGripperState(); moveGripper(gripperState); delay(250); } else if (command == MOVE_ARM) { updateArmMovement(); } } if (millis() - lastStepTime >= movementDelay) { if (targetUpperJointAngle != round(currentUpperJointAngle)) currentUpperJointAngle -= upperJointStep; if (targetLowerJointAngle != round(currentLowerJointAngle)) currentLowerJointAngle -= lowerJointStep; if (targetBaseRotatorAngle != round(currentBaseRotatorAngle)) currentBaseRotatorAngle -= baseRotatorStep; moveTo(currentUpperJointAngle, currentLowerJointAngle, currentBaseRotatorAngle); printPosition(); lastStepTime = millis(); } } void updateGripperState() { if (Serial1.available() > 0) gripperState = Serial1.parseInt(); else return; clearSerial1(); } void updateArmMovement() { int mDelay; if (Serial1.available() > 0) mDelay = Serial1.parseInt(); else return; int upperJointAngle; if (Serial1.available() > 0) upperJointAngle = Serial1.parseInt(); else return; int lowerJointAngle; if (Serial1.available() > 0) lowerJointAngle = Serial1.parseInt(); else return; int baseRotatorAngle; if (Serial1.available() > 0) baseRotatorAngle = Serial1.parseInt(); else return; clearSerial1(); movementDelay = mDelay >= MIN_MOVEMENT_DELAY ? mDelay : MIN_MOVEMENT_DELAY; targetUpperJointAngle = upperJointAngle; targetLowerJointAngle = lowerJointAngle; targetBaseRotatorAngle = baseRotatorAngle; upperJointStep = (currentUpperJointAngle - targetUpperJointAngle) / 100; lowerJointStep = (currentLowerJointAngle - targetLowerJointAngle) / 100; baseRotatorStep = (currentBaseRotatorAngle - targetBaseRotatorAngle) / 100; } void clearSerial1() { while (Serial1.available() > 0) read(); } void moveGripper(int state) { switch (state) { case GRIPPER_OPEN: write(GRIPPER_OPEN_ANGLE); break; case GRIPPER_CLOSED_SOFT: write(GRIPPER_CLOSED_SOFT_ANGLE); break; case GRIPPER_CLOSED_MEDIUM: write(GRIPPER_CLOSED_MEDIUM_ANGLE); break; case GRIPPER_CLOSED_HARD: write(GRIPPER_CLOSED_HARD_ANGLE); break; } } void moveTo(int upperJointAngle, int lowerJointAngle, int baseRotatorAngle) { write(upperJointAngle); write(lowerJointAngle); write(baseRotatorAngle); } void printPosition() { print(movementDelay); print(" "); print(gripperState); print(" "); print(round(currentUpperJointAngle)); print(" "); print(round(currentLowerJointAngle)); print(" "); println(round(currentBaseRotatorAngle)); }
fingerprint reader
The security of our home is something fundamental in our day to day, and with the use of an Arduino Nano R3 board we can install a very particular access system that works through our footprint. For this project, some batteries, transistors, and a fingerprint sensor are required, so you can place your security system anywhere in your home.
Look at the codes that you must write in the IDE to program the board:
#include <Adafruit_Fingerprint.h> #include <SoftwareSerial.h> uint8_t getFingerprintEnroll(int id); // pin #2 is IN from sensor (GREEN wire) // pin #3 is OUT from arduino (WHITE wire) SoftwareSerial mySerial(2, 3); Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial); void setup() { begin(9600); println("fingertest"); begin(57600); if (finger.verifyPassword()) { println("Found fingerprint sensor!"); } else { println("Did not find fingerprint sensor :("); while (1); } } void loop() { println("Type in the ID # you want to save this finger as..."); int id = 0; while (true) { while (! Serial.available()); char c = Serial.read(); if (! isdigit(c)) break; id *= 10; id += c - '0'; } print("Enrolling ID #"); println(id); while (! getFingerprintEnroll(id) ); } uint8_t getFingerprintEnroll(int id) { int p = -1; println("Waiting for valid finger to enroll"); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: println("Image taken"); break; case FINGERPRINT_NOFINGER: println("."); break; case FINGERPRINT_PACKETRECIEVEERR: println("Communication error"); break; case FINGERPRINT_IMAGEFAIL: println("Imaging error"); break; default: println("Unknown error"); break; } } p = finger.image2Tz(1); switch (p) { case FINGERPRINT_OK: println("Image converted"); break; case FINGERPRINT_IMAGEMESS: println("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: println("Communication error"); return p; case FINGERPRINT_FEATUREFAIL: println("Could not find fingerprint features"); return p; case FINGERPRINT_INVALIDIMAGE: println("Could not find fingerprint features"); return p; default: println("Unknown error"); return p; } println("Remove finger"); delay(2000); p = 0; while (p != FINGERPRINT_NOFINGER) { p = finger.getImage(); } p = -1; println("Place same finger again"); while (p != FINGERPRINT_OK) { p = finger.getImage(); switch (p) { case FINGERPRINT_OK: println("Image taken"); break; case FINGERPRINT_NOFINGER: print("."); break; case FINGERPRINT_PACKETRECIEVEERR: println("Communication error"); break; case FINGERPRINT_IMAGEFAIL: println("Imaging error"); break; default: println("Unknown error"); break; } } p = finger.image2Tz(2); switch (p) { case FINGERPRINT_OK: println("Image converted"); break; case FINGERPRINT_IMAGEMESS: println("Image too messy"); return p; case FINGERPRINT_PACKETRECIEVEERR: println("Communication error"); return p; case FINGERPRINT_FEATUREFAIL: println("Could not find fingerprint features"); return p; case FINGERPRINT_INVALIDIMAGE: println("Could not find fingerprint features"); return p; default: println("Unknown error"); return p; } p = finger.createModel(); if (p == FINGERPRINT_OK) { println("Prints matched!"); } else if (p == FINGERPRINT_PACKETRECIEVEERR) { println("Communication error"); return p; } else if (p == FINGERPRINT_ENROLLMISMATCH) { println("Fingerprints did not match"); return p; } else { println("Unknown error"); return p; }
small weather station
Using an UNO board, an Adafruit RGB 16×2 LED screen and a breadboard with potentiometers and resistors, you will be able to install a device anywhere. that can measure and inspect time. Its programming is very simple, you just have to configure the LED screen to show the data, and you can even see the forecasts for the next few days.
The codes to enter are:
#include <LiquidCrystal.h> // Liquid Cristal Mgt Lib #include <Wire.h> // Gestión de conexiones de cables #include "cactus_io_BME280_I2C.h" // Gestiona el sensor de temperatura, humedad y presión // Pines LCD d4, d5, d6, d7 a pines Arduino 5, 4, 3, 2 LiquidCrystal lcd ( 12 , 11 , 10 , 5 , 4 , 3 , 2 ); // Definir PINs LCD // Crea el objeto BME280 // BME280_I2C bme; // I2C usando 0x77 por defecto BME280_I2C bme ( 0x76 ); // I2C usando la dirección 0x76 int backLight = 13; void setup() { pinMode(backLight, OUTPUT); begin(9600); digitalWrite(backLight, HIGH); begin(16,2); clear(); setCursor(0,0); print("Temperatura Sensore"); setCursor(0,1); print("XY Celsius"); if (!bme.begin()) { //Check if BME280 is connected and working println("Could not find a valid BME280 sensor, check wiring!"); while (1); } setTempCal(-1); } void loop() { clear(); readSensor(); setCursor(0,0); print("P:"); lcd.print(bme.getPressure_MB()); print(" H:"); lcd.print(bme.getHumidity()); setCursor(0,1); print("T:"); lcd.print(bme.getTemperature_C()); lcd.print("C"); print(" T:"); lcd.print(bme.getTemperature_F()); lcd.println("F"); delay(1000); }
robotic spider
Secondly, we have a robot spider, a very different model than many Arduino projects, however its Preparation is somewhat more complicated and requires some knowledge. The materials you will need to use are an Arduino Nano R3 board, a model sg90 micro servo motor, I buy AA batteries, a 5 volt Adafruit Trinket controller, and a model MAX7219 LED module.
Then you must enter the Arduino IDE programming environment and write these codes:
#include <LedControl.h> #define PIN_EYES_DIN 12 #define PIN_EYES_CS 11 #define PIN_EYES_CLK 10 LedControl lc = LedControl(PIN_EYES_DIN, PIN_EYES_CLK, PIN_EYES_CS, 2); // rotation bool rotateMatrix0 = false; // rotate 0 matrix by 180 deg bool rotateMatrix1 = false; // rotate 1 matrix by 180 deg // define eye ball without pupil byte eyeBall[8]={ B00111100, B01111110, B11111111, B11111111, B11111111, B11111111, B01111110, B00111100 }; byte eyePupil = B11100111; byte eyeCurrent[8]; int currentX; int currentY; int cntLoop = 0; int cntEffect = 0; #define MIN -2 #define MAX 2 #define DELAY_BLINK 40 #define EFFECT_ITERATION 4 void setup() { shutdown(0,false); shutdown(1,false); setIntensity(0,1); setIntensity(1,1); clearDisplay(0); clearDisplay(1); byte b = B10000000; for (int c=0; c<=7; c++) { for (int r=0; r<=7; r++) { setRow(0, r, b); setRow(1, r, b); } b = b >> 1; delay(50); } b = B11111111; for (int r=0; r<=7; r++) { setRow(0, r, b); setRow(1, r, b); } delay(500); clearDisplay(0); clearDisplay(1); delay(500); randomSeed(analogRead(0)); displayEyes(0, 0); delay(2000); blinkEyes(true, false); blinkEyes(false, true); delay(1000); } void loop() { moveEyes(random(MIN, MAX + 1), random(MIN, MAX + 1), 50); delay(random(5, 7) * 500); if (random(0, 5) == 0) { delay(500); blinkEyes(); delay(500); } if (EFFECT_ITERATION > 0) { cntLoop++; if (cntLoop == EFFECT_ITERATION) { cntLoop = 0; if (cntEffect > 6) cntEffect = 0; switch(cntEffect) { case 0: // cross eyes crossEyes(); delay(1000); break; case 1: roundSpin(2); delay(1000); break; case 2: crazySpin(2); delay(1000); break; case 3: methEyes(); delay(1000); break; case 4: lazyEye(); delay(1000); break; case 5: blinkEyes(true, false); blinkEyes(false, true); delay(1000); break; case 6: glowEyes(3); delay(1000); break; default: break; } cntEffect++; } } } void blinkEyes() { blinkEyes(true, true); } void blinkEyes(boolean blinkLeft, boolean blinkRight) { if (!blinkLeft && !blinkRight) return; for (int i=0; i<=3; i++) { if (blinkLeft) { setRow(0, i, 0); setRow(0, 7-i, 0); } if (blinkRight) { setRow(1, i, 0); setRow(1, 7-i, 0); } delay(DELAY_BLINK); } for (int i=3; i>=0; i--) { if (blinkLeft) { setRow(0, i, eyeCurrent[i]); setRow(0, 7-i, eyeCurrent[7-i]); } if (blinkRight) { setRow(1, i, eyeCurrent[i]); setRow(1, 7-i, eyeCurrent[7-i]); } delay(DELAY_BLINK); } } void crazySpin(int times) { if (times == 0) return; moveEyes(0, 0, 50); delay(500); byte row = eyePupil; for (int t=0; t<times; t++) { for (int i=0; i<5; i++) { row = row >> 1; row = row | B10000000; setRow(0, 3, row); setRow(1, 3, row); setRow(0, 4, row); setRow(1, 4, row); delay(50); if (t == 0) delay((5-i)*10); // increase delay on 1st scroll } for (int i=0; i<5; i++) { row = row >> 1; if (i>=2) row = row | B10000000; setRow(0, 3, row); setRow(1, 3, row); setRow(0, 4, row); setRow(1, 4, row); delay(50); if (t == (times-1)) delay((i+1)*10); // increase delay on last scroll } } } void crossEyes() { moveEyes(0, 0, 50); delay(500); byte pupilR = eyePupil; byte pupilL = eyePupil; for (int i=0; i<2; i++) { pupilR = pupilR >> 1; pupilR = pupilR | B10000000; pupilL = pupilL << 1; pupilL = pupilL | B1; setRow(0, 3, pupilR); setRow(1, 3, pupilL); setRow(0, 4, pupilR); setRow(1, 4, pupilL); delay(100); } delay(2000); for (int i=0; i<2; i++) { pupilR = pupilR << 1; pupilR = pupilR | B1; pupilL = pupilL >> 1; pupilL = pupilL | B10000000; setRow(0, 3, pupilR); setRow(1, 3, pupilL); setRow(0, 4, pupilR); setRow(1, 4, pupilL); delay(100); } } void displayEyes(int offsetX, int offsetY) { offsetX = getValidValue(offsetX); offsetY = getValidValue(offsetY); int row1 = 3 - offsetY; int row2 = 4 - offsetY; byte pupilRow = eyePupil; if (offsetX > 0) { for (int i=1; i<=offsetX; i++) { pupilRow = pupilRow >> 1; pupilRow = pupilRow | B10000000; } } else if (offsetX < 0) { for (int i=-1; i>=offsetX; i--) { pupilRow = pupilRow << 1; pupilRow = pupilRow | B1; } } byte pupilRow1 = pupilRow & eyeBall[row1]; byte pupilRow2 = pupilRow & eyeBall[row2]; for(int r=0; r<8; r++) { if (r == row1) { setRow(0, r, pupilRow1); setRow(1, r, pupilRow1); eyeCurrent[r] = pupilRow1; } else if (r == row2) { setRow(0, r, pupilRow2); setRow(1, r, pupilRow2); eyeCurrent[r] = pupilRow2; } else { setRow(0, r, eyeBall[r]); setRow(1, r, eyeBall[r]); eyeCurrent[r] = eyeBall[r]; } } currentX = offsetX; currentY = offsetY; } int getValidValue(int value) { if (value > MAX) return MAX; else if (value < MIN) return MIN; else return value; } void glowEyes(int times) { for (int t=0; t<times; t++) { for (int i=2; i<=8; i++) { setIntensity(0,i); setIntensity(1,i); delay(50); } delay(250); for (int i=7; i>=1; i--) { setIntensity(0,i); setIntensity(1,i); delay(25); } delay(150); } } void methEyes() { moveEyes(0, 0, 50); delay(500); byte pupilR = eyePupil; byte pupilL = eyePupil; for (int i=0; i<2; i++) { pupilR = pupilR << 1; pupilR = pupilR | B1; pupilL = pupilL >> 1; pupilL = pupilL | B10000000; setRow(0, 3, pupilR); setRow(1, 3, pupilL); setRow(0, 4, pupilR); setRow(1, 4, pupilL); delay(100); } delay(2000); for (int i=0; i<2; i++) { pupilR = pupilR >> 1; pupilR = pupilR | B10000000; pupilL = pupilL << 1; pupilL = pupilL | B1; setRow(0, 3, pupilR); setRow(1, 3, pupilL); setRow(0, 4, pupilR); setRow(1, 4, pupilL); delay(100); } } void lazyEye() { moveEyes(0, 1, 50); delay(500); for (int i=0; i<3; i++) { setRow(1, i+2, eyeBall[i+2]); setRow(1, i+3, eyeBall[i+3] & eyePupil); setRow(1, i+4, eyeBall[i+4] & eyePupil); delay(150); } delay(1000); for (int i=0; i<3; i++) { setRow(1, 4-i, eyeBall[4-i] & eyePupil); setRow(1, 5-i, eyeBall[5-i] & eyePupil); setRow(1, 6-i, eyeBall[6-i]); delay(25); } } void roundSpin(int times) { if (times == 0) return; moveEyes(2, 0, 50); delay(500); for (int i=0; i<times; i++) { displayEyes(2, -1); delay(40); if (i==0) delay(40); displayEyes(1, -2); delay(40); if (i==0) delay(30); displayEyes(0, -2); delay(40); if (i==0) delay(20); displayEyes(-1, -2); delay(40);if (i==0) delay(10); displayEyes(-2, -1); delay(40); displayEyes(-2, 0); delay(40); displayEyes(-2, 1); delay(40);if (i==(times-1)) delay(10); displayEyes(-1, 2); delay(40);if (i==(times-1)) delay(20); displayEyes(0, 2); delay(40); if (i==(times-1)) delay(30); displayEyes(1, 2); delay(40); if (i==(times-1)) delay(40); displayEyes(2, 1); delay(40); if (i==(times-1)) delay(50); displayEyes(2, 0); delay(40); } }
Smoke detector
This is one of the most important projects that you can carry out because, thanks to Arduino, you can save your life and yours from fires. Among its functions is the possibility of receiving a notification in the event of an accident. If you want, you can add a monitor to make the most of this idea.
The materials that you will have to acquire are not expensive, since you will need an Arduino board of the Nano R3, Mega2560 or ATMEGA2560 version. You should also have a DHT11 temperature and humidity sensor, a gas sensor module, a buzzer, a PCB breadboard, 1k Ohm resistor, wires and an LCD screen.
As for the programming codes that you will have to write in the IDE, you can copy them below:
#include<LiquidCrystal.h> LiquidCrystal lcd(12,11,5,4,3,2); int temp; int humi; int tol; int j; int H=50; int T=25; int B=1; int flag=0; int led=7; int LED=9; int BU=2; int BUTTON=3; int FMQ=13; int fmq=10; unsigned int loopCnt; int chr[40] = {0}; unsigned long time; #define pin 8 void setup() { pinMode(fmq,OUTPUT); pinMode(FMQ,OUTPUT); pinMode(LED,OUTPUT); pinMode(led,OUTPUT); begin(9600); } void loop() { HH(); TT(); keyScan(); bgn: delay(200); pinMode(pin,OUTPUT); digitalWrite(pin,LOW); delay(20); digitalWrite(pin,HIGH); delayMicroseconds(40); digitalWrite(pin,LOW); pinMode(pin,INPUT); loopCnt=10000; while(digitalRead(pin) != HIGH) { if(loopCnt-- == 0) { println("HIGH"); goto bgn; } } loopCnt=30000; while(digitalRead(pin) != LOW) { if(loopCnt-- == 0) { println("LOW"); goto bgn; } } for(int i=0;i<40;i++) { while(digitalRead(pin) == LOW) {} time = micros(); while(digitalRead(pin) == HIGH) {} if (micros() - time >50) { chr[i]=1; }else { chr[i]=0; } } humi=chr[0]*128+chr[1]*64+chr[2]*32+chr[3]*16+chr[4]*8+chr[5]*4+chr[6]*2+chr[7]; temp=chr[16]*128+chr[17]*64+chr[18]*32+chr[19]*16+chr[20]*8+chr[21]*4+chr[22]*2+chr[23]; tol=chr[32]*128+chr[33]*64+chr[34]*32+chr[35]*16+chr[36]*8+chr[37]*4+chr[38]*2+chr[39]; print("temp:"); println(temp); print("humi:"); println(humi); print("tol:"); println(tol); if(temp>T) { digitalWrite(LED,HIGH); digitalWrite(FMQ,LOW); }else{ digitalWrite(LED,LOW); digitalWrite(FMQ,HIGH); } if(humi>H) { digitalWrite(led,HIGH); digitalWrite(fmq,LOW); }else{ digitalWrite(led,LOW); digitalWrite(fmq,HIGH); } int val; val=analogRead(0); print("smo:"); println(val,DEC); delay(100); if(flag==0) { begin(16,2); setCursor(0,0); print("TEMP: C"); setCursor(9,0); print("SMO:"); setCursor(0,1); print("HUMI: %"); setCursor(9,1); //lcd.print("BEP:"); setCursor(5,0); print(temp); setCursor(5,1); print(humi); setCursor(13,0); print(val,DEC); } if(flag==1) { begin(16,2); print("ALARM TEMP:"); setCursor(11,0); print(T); } if(flag==2) { begin(16,2); print("ALARM HUMI:"); setCursor(12,0); print(H); } } void keyScan() { if(analogRead(BUTTON)>600) { delay(20); if(analogRead(BUTTON)>600) { flag++; if(flag>=3) flag=0; while(analogRead(BUTTON)>600); } } } void HH() { if(analogRead(B)>600) { delay(20); if(analogRead(B)>600) { H++; if(H>=61) H=40; while(analogRead(B)>600); } } } void TT() { if(analogRead(BU)>600) { delay(20); if(analogRead(BU)>600) { T++; if(T>=31) T=20; while(analogRead(BU)>600); } } }
Automatic open bin
It’s amazing how an ultrasonic sensor can be the crucial complement for a wide variety of extraordinary projects. With the help of an Arduino UNO board, you can create a garbage can, but one that stands out for its automatic lid opening. For this, you will need Arduino Genuino and UNO, a servo motor, a movement sensor, cables and other connectors.
When you have all the materials, you will have to write in the Arduino IDE:
#include <Servo.h> Servo servo; int trigPin = 5; int echoPin = 6; int servoPin = 7; long duration, dist, verage; long aver[3]; void setup() { attach(servoPin); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); write(0); delay(100); detach(); } void measure() { digitalWrite(10,HIGH); digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(15); digitalWrite(trigPin, LOW); pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); dist = (duration/2) / 29.1; } void loop() { for (int i=0;i<=2;i++) { measure(); aver[i]=dist; delay(10); } dist=(aver[0]+aver[1]+aver[2])/3; if ( dist < 150 ) { attach(servoPin); delay(1); write(90); delay(3000); write(0); delay(300); detach(); } }
pool monitor
With the elaboration of this monitor You can greatly benefit since you will be able to monitor the state of the pool, showing you the data in real time. In this way you will have the PH at the correct levels and you will know when to add chlorine or algaecides. It will also serve to show you the temperature of the water. Building this project will require you to have an Arduino model Nano 33 IoT board, an ISE probe, an integrated EC probe, and a connector kit.
Lastly, you will need to open the Arduino programming environment and start writing these codes:
#include <ArduinoJson.h> #include <ArduinoBLE.h> #include <uFire_EC_JSON.h> #include <uFire_pH_JSON.h> #include <uFire_ORP_JSON.h> BLEService uFire_Service("4805d2d0-af9f-42c1-b950-eae78304c408"); BLEStringCharacteristic tx_Characteristic("50fa7d80-440a-44d2-967a-ec7731ec736a", BLENotify, 20); BLEStringCharacteristic rx_Characteristic("50fa7d80-440b-44d2-967b-ec7731ec736b", BLEWrite, 20); uFire_EC_JSON ec; uFire_pH_JSON ph; uFire_ORP_JSON orp; void rxCallback(BLEDevice central, BLECharacteristic characteristic) { String rx_command = rx_Characteristic.value(); String json_out = ec.processJSON(rx_command); if (json_out != "") { setValue(json_out); return; } // comprobar el PH json_out = ph.processJSON(rx_command); if (json_out != "") { setValue(json_out); return; } json_out = orp.processJSON(rx_command); if (json_out != "") { setValue(json_out); return; } } void setup() { begin(new uFire_EC); begin(new ISE_pH); begin(new ISE_ORP(0x3e)); begin(); begin(); setLocalName("uFire BLE"); setAdvertisedService(uFire_Service); addCharacteristic(tx_Characteristic); addCharacteristic(rx_Characteristic); addService(uFire_Service); setEventHandler(BLEWritten, rxCallback); advertise(); } void loop() { poll(); }
infinity kaleidoscope mirror
This is another of the projects to pass the time and to practice the knowledge learned in Arduino. The creation of this mirror produces an ever-changing infinite illusion as your address moves, creating an amazing effect for the one you are viewing. You will need an Arduino 101, directional leds, heat shrink tubing, AA batteries, square mirror, foam core, jumper pins, and various connectors.
Next, you’ll need to enter these programming commands into the IDE:
#include "CurieIMU.h" #include <Adafruit_NeoPixel.h> #define PIN 6 //// ¿A qué pin están conectados los NeoPixels? Tira de Adafruit_NeoPixel = Adafruit_NeoPixel ( 54 , PIN , NEO_GRB + NEO_KHZ800 ); int tr = 0 ; int tg = 0 ; int tb = 0 ; int r = 0 ; int g = 0; int b = 0; int rawX = 0; int rawY = 0; //int rawZ = 0; float angle = 0.0; void setup() { begin(); setAccelerometerRange(2); begin(); show(); } void loop() { int rawX = CurieIMU.readAccelerometer(X_AXIS); int rawY = CurieIMU.readAccelerometer(Y_AXIS); int rawZ = CurieIMU.readAccelerometer(Z_AXIS); angle = atan2(rawX, rawY); // the funtion atan2() converts x and y forces into an angle in radians. if (abs(angle) > 2.5) { // digital pins are down /// turn lights off in this position tr = 0; tg = 0; tb = 0; runlights(); } if ((angle > 1.5) && (angle < 2.5)) { tr = 100; tg = 100; tb = 100; runlights(); } else if ((angle < 1.5) && (angle > 0.5)) { tr = 100; tg = 0; tb = 0; runlights(); } else if ((angle < 0.5) && (angle > -0.5)) { //make lights green in this position tr = 0; tg = 100; tb = 0; runlights(); } else if ((angle < -1.5) && (angle > -2.5)) { //make lights blue in this position tr = 0; tg = 0; tb = 100; runlights(); } else if ((angle < -0.5) && (angle > -1.5)) { theaterChase(); } else { tr = 0; tg = 0; tb = 0; runlights(); } } void runlights() { /// color smoothing. if (tr > r + 1) { r++; } if (tg > g + 1) { g++; } if (tb > b + 1) { b++; } if (tr < r) { r--; } if (tg < g) { g--; } if (tb < b) { b--; } //turn all the LEDS to the current r, g, b values. for (int i = 0; i < strip.numPixels(); i++) { setPixelColor(i, r, g, b); } show(); delay(10); } void rainbowCycle(uint8_t wait) { uint16_t i, j; for(j=0; j<256*5; j++) { for(i=0; i< strip.numPixels(); i++) { setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255)); } show(); delay(wait); } } void theaterChase(){ for (int j = 0; j < 3; j++) { //3cycles of chasing for (int q = 0; q < 3; q++) { for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) { setPixelColor(i + q, r, g, b); } show(); delay(50); for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) { setPixelColor(i + q, 0); } } } } uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if(WheelPos < 85) { return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } if(WheelPos < 170) { WheelPos -= 85; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } WheelPos -= 170; return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); }
control panel for computer
This project is based on programming the Arduino board in a control panel for the PC, so, that can execute different types of commands on the computer. Although, crafting it can be a bit complex and can take some time.is a very effective project that can ease the use of your device. If you are interested in this electronic plan you will need the UNO version of Arduino, a generic breadboard, a buzzer and connectors.
To finish, you will have to use these codes:
#include <Wire.h> #include <PC42.h> #include <EEPROM.h> #define TONE_ERR Si1 // 59 Hz #define TONE_ALARM Do6 #define MAX_SECONDS 9999 #define EEPROM_ADDR_SECONDS 4 typedef struct { int total_time; int countdown; int count_millis; long millis; long millis_old; struct { unsigned state:3; unsigned alarm:3; }; } tempo_t; tempo_t tempo; enum {INIT_STOP, STOP, INIT_COUNTDOWN, COUNTDOWN, INIT_ALARM, ALARM}; enum {OFF, ON }; void setup() { begin(); tempo_init(); } void loop() { // Dispatcher switch(tempo.state) { case INIT_STOP: ledBegin(); ledWrite(1, HIGH); power_off(); state = STOP; break; case STOP: dispNum(tempo.countdown); tempo_stop(); break; case INIT_COUNTDOWN: if (tempo.countdown > 0) { ledBegin(); ledWrite(4, HIGH); millis_old = millis(); state = COUNTDOWN; } else { state = INIT_STOP; } break; case COUNTDOWN: tempo_countdown(); break; case INIT_ALARM: power_off(); ledBegin(); ledWrite(3, HIGH); millis = millis(); alarm = 0; state = ALARM; break; case ALARM: alarm(); break; default: state = INIT_STOP; } } void tempo_stop(void) { char keys; dispDots(0); keys = pc.keyCount(KEY_DOWN); countdown -= keys; if (tempo.countdown < 0) countdown += MAX_SECONDS + 1; keys = pc.keyCount(KEY_UP); countdown += keys; if (tempo.countdown > MAX_SECONDS) countdown -= MAX_SECONDS + 1; if (pc.keyPressed(KEY_UP) && pc.keyPressed(KEY_DOWN)) { countdown = tempo.total_time; count_millis = 0; } if (pc.keyEvents(KEY_RIGHT, KEY_PRESSED_TIME2)) { total_time = tempo.countdown; dispWrite(0,0,0,0); eeprom_write16(EEPROM_ADDR_SECONDS, tempo.total_time); delay(100); } if (pc.keyEvents(KEY_ENTER, KEY_PRESSED_TIME1)) { state = INIT_COUNTDOWN; } dispNum(tempo.countdown); } void tempo_countdown(void) { power_on(); millis = millis(); count_millis += tempo.millis - tempo.millis_old; millis_old = tempo.millis; while (tempo.count_millis >= 1000) { countdown--; dispNum(tempo.countdown); count_millis -= 1000; if (tempo.countdown == 0) break; } if (tempo.count_millis < 500) dispDots(0); else dispDots(1); if (tempo.countdown == 0) { power_off(); state = INIT_ALARM; } if (pc.keyEvents(KEY_ENTER, KEY_PRESSED_TIME1)) { state = INIT_STOP; } } void alarm(void) { dispWrite(DD_E, DD_n, DD_d, DD_SP); switch(tempo.alarm) { case 0: alarm_sound(); alarm = 1; break; case 1: if (millis() > tempo.millis + 1000) { alarm_sound(); millis += 1000; alarm = 2; } break; case 2: if (millis() > tempo.millis + 4000) { millis += 4000; buzzPlay(TONE_ALARM, 16); buzzPlay(0, 16); } break; } if (pc.keyEvents(KEY_ENTER, KEY_PRESSED_TIME1)) { buzzBegin(); countdown = tempo.total_time; count_millis = 0; state = INIT_STOP; } } int eeprom_read16(int addr) { return (EEPROM.read(addr + 1) << 8) | EEPROM.read(addr); } int eeprom_write16(int addr, int data) { write(EEPROM_ADDR_SECONDS, tempo.total_time); write(EEPROM_ADDR_SECONDS+1, tempo.total_time>>8); } void tempo_init(void) { total_time = eeprom_read16(EEPROM_ADDR_SECONDS); state = INIT_STOP; alarm = OFF; millis = 0; millis_old = 0; countdown = tempo.total_time; count_millis = 0; } void alarm_sound(void) { buzzPlay(TONE_ALARM, 62); buzzPlay(0, 62); buzzPlay(TONE_ALARM, 62); buzzPlay(0, 62); buzzPlay(TONE_ALARM, 62); buzzPlay(0, 62); buzzPlay(TONE_ALARM, 62); buzzPlay(0, 62); } void power_on(void) { // Desactivar la salida de potencia pinMode(10, OUTPUT); digitalWrite(10, HIGH); } // Para apagar la fuente de alimentación void power_off(void) { // Desactivar la salida de potencia digitalWrite(10, LOW); pinMode(10, INPUT); }
Computing