Arduino projects

Here I will be posting some of the arduino projects I make :)

Blink project


  // the setup function runs once when you press reset or power the board
  void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  }

  // the loop function runs over and over again forever
  void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  }
  

RGB LED project

 
    // Define Pins
  #define BLUE 3
  #define GREEN 5
  #define RED 6

  void setup()
  {
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  digitalWrite(RED, HIGH);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, LOW);
  }

  // define variables
  int redValue;
  int greenValue;
  int blueValue;
  
  // main loop
  void loop()
  {
  #define delayTime 10 // fading time between colors
  
  redValue = 255; // choose a value between 1 and 255 to change the color.
  greenValue = 0;
  blueValue = 0;
  
  // this is unnecessary as we've either turned on RED in SETUP
  // or in the previous loop ... regardless, this turns RED off
  // analogWrite(RED, 0);
  // delay(1000);
  
  for(int i = 0; i < 255; i ++) // fades out red bring green full when i=255
  {
  redValue += 1;
  greenValue += 1;
  // The following was reversed, counting in the wrong directions
  analogWrite(RED, 255 - redValue);
  analogWrite(GREEN, 255 - greenValue);
  analogWrite(RED, redValue);
  analogWrite(GREEN, greenValue);
  delay(delayTime);
  }
  
  redValue = 0;
  greenValue = 255;
  blueValue = 0;
  
  for(int i = 0; i < 255; i += 1) // fades out green bring blue full when i=255
  {
  greenValue += 1;
  blueValue += 1;
  // The following was reversed, counting in the wrong directions
  // analogWrite(GREEN, 255 - greenValue);
  // analogWrite(BLUE, 255 - blueValue);
  analogWrite(GREEN, greenValue);
  analogWrite(BLUE, blueValue);
  delay(delayTime);
  }
  
  redValue = 0;
  greenValue = 0;
  blueValue = 255;
  
  for(int i = 0; i < 255; i += 1) // fades out blue bring red full when i=255
  {
  // The following code has been rearranged to match the other two similar sections
  blueValue -= 1;
  redValue += 1;
  // The following was reversed, counting in the wrong directions
  // analogWrite(BLUE, 255 - blueValue);
  // analogWrite(RED, 255 - redValue);
  analogWrite(BLUE, blueValue);
  analogWrite(RED, redValue);
  delay(delayTime);
  }
  }
  

Passive buzzer project

 
  #include "pitches.h"
   
  // notes in the melody:
  int melody[] = {
  NOTE_C5, NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5, NOTE_C6};
  int duration = 500;  // 500 miliseconds
   
  void setup() {
   
  }
   
  void loop() {  
  for (int thisNote = 0; thisNote < 8; thisNote++) {
  // pin8 output the voice, every scale is 0.5 sencond
  tone(8, melody[thisNote], duration);
       
  // Output the voice after several minutes
  delay(1000);
  }
     
  // restart after two seconds 
  delay(2000);
  }
 
  

Servo project

Turns an LED on for one second, then off for one second, repeatedly.


    #include 
  Servo myservo;

  void setup(){
    myservo.attach(9);
    myservo.write(90);// move servos to center position -> 90°
  } 
  void loop(){
    myservo.write(90);// move servos to center position -> 90°
    delay(1000);
    myservo.write(30);// move servos to center position -> 60°
    delay(1000);
    myservo.write(90);// move servos to center position -> 90°
    delay(1000);
    myservo.write(150);// move servos to center position -> 120°
    delay(1000);
  }

  

Sound sensor project

This module has two outputs: AO: analog output, real-time output voltage signal of microphone DO: when the intensity of the sound reaches a certain threshold, the output is a high or low level signal. The threshold sensitivity can be achieved by adjusting the potentiometer.

When you speak into the microphone or inflate, you can observe that our waveforms have changed


    void setup()
  {
  Serial.begin(9600); // The IDE settings for Serial Monitor/Plotter (preferred) must match this
  speed
  pinMode(sensorDigitalPin,INPUT); // Define pin 7 as an input port, to accept digital input
  pinMode(Led13,OUTPUT); // Define LED13 as an output port, to indicate digital trigger reached
  }
  void loop(){
  analogValue = analogRead(sensorAnalogPin);

  // Read the value of the analog interface A0 assigned to digitalValue

  digitalValue=digitalRead(sensorDigitalPin);

  // Read the value of the digital interface 7 assigned to digitalValue

  Serial.println(analogValue);

  // Send the analog value to the serial transmit interface

  if(digitalValue==HIGH) // When the Sound Sensor sends signla, via voltage present, light LED13 (L)
  {
  digitalWrite(Led13,HIGH);
  }
  else
  {
  digitalWrite(Led13,LOW);
  }
  delay(50); // Slight pause so that we don't overwhelm the serial interface
  }
  

Ultrasonic sensor project

Ultrasonic sensor is great for all kind of projects that need distance measurements, avoiding obstacles as examples. The HC-SR04 is inexpensive and easy to use since I used a Library specifically designed for these sensor.

Ultrasonic sensor module HC-SR04 provides 2cm-400cm non-contact measurement function, the ranging accuracy can reach to 3mm. The modules includes ultrasonic transmitters, receiver and control circuit. The basic principle of work:

Test distance = (high level time × velocity of sound (340m/s) /2 The Timing diagram is shown below. You only need to supply a short 10us pulse to the trigger input to start the ranging, and then the module will send out an 8 cycle burst of ultrasound at 40 kHz and raise its echo. The Echo is a distance object that is pulse width and the range in proportion .You can calculate the range through the time interval between sending trigger signal and receiving echo signal. Formula: us / 58 = centimeters or us / 148 =inch; or: the range = high level time * velocity (340M/S) / 2; we suggest to use over 60ms measurement cycle, in order to prevent trigger signal to the echo signal.

Using a Library designed for these sensors will make our code short and simple. We include the library at the beginning of our code, and then by using simple commands we can control the behavior of the sensor.


     #include "SR04.h"
  #define TRIG_PIN 12
  #define ECHO_PIN 11
  SR04 sr04 = SR04(ECHO_PIN,TRIG_PIN);
  long a;

  void setup() {
     Serial.begin(9600);
     delay(1000);
  }

  void loop() {
     a=sr04.Distance();
     Serial.print(a);
     Serial.println("cm");
     delay(1000);
  }

  

RTC (REAL Time Clock) project

The DS1307 real-time clock is a low-power chip. Address and data are transferred serially through an I2C, which can be used unless being connected to UNO with only three data cables. DS1307 provides seconds, minutes, hours, day, date, month, and year information. Timekeeping operation continues while the part operates from the backup supply.

Using a Library designed for these sensors will make our code short and simple. We include the library at the beginning of our code:


     #include 
  #include 

  DS3231 clock;
  RTCDateTime dt;

  void setup()
  {
    Serial.begin(9600);

    Serial.println("Initialize RTC module");
    // Initialize DS3231
    clock.begin();

  
    // Manual (YYYY, MM, DD, HH, II, SS
    // clock.setDateTime(2016, 12, 9, 11, 46, 00);
  
    // Send sketch compiling time to Arduino
    clock.setDateTime(__DATE__, __TIME__);    
    /*
    Tips:This command will be executed every time when Arduino restarts. 
         Comment this line out to store the memory of DS3231 module
    */
  }

  void loop()
  {
    dt = clock.getDateTime();
  
    // For leading zero look to DS3231_dateformat example

    Serial.print("Raw data: ");
    Serial.print(dt.year);   Serial.print("-");
    Serial.print(dt.month);  Serial.print("-");
    Serial.print(dt.day);    Serial.print(" ");
    Serial.print(dt.hour);   Serial.print(":");
    Serial.print(dt.minute); Serial.print(":");
    Serial.print(dt.second); Serial.println("");
  
    delay(1000);
  }
  

LCD display project

Before you can run this, make sure that you have installed the < LiquidCrystal > library or re-install it, if necessary. Otherwise, your code won't work.

 
   #include < LiquidCrystal.h >
  
  // initialize the library with the numbers of the interface pins
  LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
  
  void setup() {
    // set up the LCD's number of columns and rows:
    lcd.begin(16, 2);
    // Print a message to the LCD.
    lcd.print("Hello, World!");
  }
  
  void loop() {
    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(60, -1);
    // print the number of seconds since reset:
    lcd.print(millis() / 1000);
  }

 
  

Thermometer (LCD display) project

 
    #include < LiquidCrystal.h >
  int tempPin = 0;
  //  BS  E  D4 D5  D6 D7
  LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
  void setup()
  {
    lcd.begin(16, 2);
  }
  void loop()
  {
    int tempReading = analogRead(tempPin);
    // This is OK
    double tempK = log(10000.0 * ((1024.0 / tempReading - 1)));
    tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );       //  Temp Kelvin
    float tempC = tempK - 273.15;            // Convert Kelvin to Celcius
    float tempF = (tempC * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
    /*  replaced
      float tempVolts = tempReading * 5.0 / 1024.0;
      float tempC = (tempVolts - 0.5) * 10.0;
      float tempF = tempC * 9.0 / 5.0 + 32.0;
    */
    // Display Temperature in C
    lcd.setCursor(0, 0);
    lcd.print("TempC  ");
    // Display Temperature in F
    //lcd.print("TempF  ");
    lcd.setCursor(6, 0);
    // Display Temperature in C
    lcd.print(tempC);
    // Display Temperature in F
    //lcd.print(tempF);
    delay(500);
  }

 
  

Timer (LCD display) project

 
   #include < LiquidCrystal.h >   //Libreria del display LCD
  #define TONO_ERROR 600
  #define TIME_INTERVAL 3000
  
  LiquidCrystal lcd(7, 8, 9, 10, 11, 12);    //Inicializamos la libreria con el numero de los pines a utilizar
  
  int buzzer = 5;            //Alarma
  int ahoras = 0;            //Variable a mostrar por LCD de las horas
  int aminutos = 0;          //Variable a mostrar por LCD de los minutos
  int asegundos = 0;         //Variable a mostrar por LCD de los segundos
  int segundostotal = 0;     //Tiempo total
  int msg= 0;                //Barrera para el mensaje de bienvenida
  int start = A1;            //Pulsador de arranque
  int empieza = 1024;        // Variable para almacenaje del pulsador de arranque
  int buth = A5;             //Pulsador de Horas
  int butm = A4;             //Pulsador de Minutos
  int buts = A3;             //Pulsador de segundos
  int varbuth = 0;           //Variable para almacenar el valor del pulsador de horas
  int varbutm = 0;           //Variable para almacenar el valor del pulsador de minutos
  int varbuts = 0;           //Variable para almacenar el valor del pulsador de segundos
  
  void setup() 
  {
  
     lcd.begin(16, 2);         // Configuramos el numero de columnas y filas del LCD. 
     pinMode(buzzer, OUTPUT);  //Pin de alarma --> Salida
     pinMode(buth, INPUT);     //Pin de pulsador de horas --> Entrada
     pinMode(butm, INPUT);     //Pin de pulsador de minutos --> Entrada
     pinMode(buts, INPUT);     //Pin de pulsador de segundos --> Entrada
     pinMode(start, INPUT);    //Pin de pulsador de arranque --> Entrada
  
     msg = 0;                  //Barrera del mensaje de bienvenida
     empieza = 1024;           //Barrera de arranque  
     varbuth = 1;              //Barrera de horas
     varbutm = 1;              //Barrera de minutos
     varbuts = 1;              //Barrera de segundos

     Serial.begin(9600);
  }
  
  void loop()
  {
  
       if(msg==0)             //Mostramos el mensaje de bienvenida solo una vez
       {
  
         lcd.setCursor(0,0);
         lcd.print("Temporizador con");
         lcd.setCursor(1,1);
         lcd.print("Arduino + LCD");
         delay(2500);
         msg = 1;
         lcd.clear();
       }
       //-------------------------------------------------------------------------------------------------
       // LECTURA DE LOS BOTONES Y ELECCIÓN DEL TIEMPO, NO SALE DEL BUCLE HASTA PULSAR
       // EL BOTON DE ARRANQUE
       //-------------------------------------------------------------------------------------------------
       do                  
       {
  
         varbuth = analogRead(buth);   //Leemos boton de horas
         varbutm = analogRead(butm);   //Leemos boton de minutos
         varbuts = analogRead(buts);   //Leemos boton de segundos  
         if(varbuth > 0)              //Si el boton ha sido pulsado, aumentamos las horas en una unidad
         {
          ahoras = ahoras + 1 ;
          delay(250);
         } 
          if(varbutm > 0)            //Si el boton ha sido pulsado, aumentamos los minutos en una unidad
         {
           aminutos = aminutos + 1;
           if(aminutos == 60) aminutos = 0;
           delay(250);
         } 
          if(varbuts > 0)            //Si el boton ha sido pulsado, aumentamos los segundos en una unidad
         {
           asegundos = asegundos + 1;
           if(asegundos == 60) asegundos = 0;
           delay(250);
         } 
         lcd.setCursor(0,0);
         lcd.print("Elige el tiempo");  //Muestra mensaje y las HH:MM:SS que vayamos aumentan      
         lcd.setCursor(4,1);    
      
        if (ahoras < 10) lcd.print("0");    // Si las horas son menor que 10, pone un "0" delante.
         lcd.print(ahoras);                 // Sin este codigo, se muestra asi: H:M:S  (1:M:S)
         lcd.print(":");
  
        if (aminutos < 10) lcd.print("0");  // Si los minutos son menor que 10, pone un "0" delante.
         lcd.print(aminutos);               // Sin este codigo, se muestra asi: H:M:S  (H:1:S)
         lcd.print(":");
  
        if (asegundos < 10) lcd.print("0"); // Si los segundos son menor que 10, pone un "0" delante.
         lcd.print(asegundos);              // Sin este codigo, se muestra asi: H:M:S  (H:M:1)
       } while(analogRead(start) == 0);  // Se repite el menu de elegir tiempo hasta que pulsemos el boton de arranque.
       segundostotal = asegundos + (aminutos * 60) + (ahoras * 60 * 60);  //Convierte el tiempo elegido en segundos!!
        //-------------------------------------------------------------------------------------------------
        // UNA VEZ PULSADO EL BOTON DE ARRANQUE Y ACUMULADO EL TIEMPO, ENTRA EN EL SIGUIENTE WHILE
        // Y NO FINALIZA HASTA TERMINAR LA CUENTA.
        //-------------------------------------------------------------------------------------------------
        while (segundostotal > 0)
        {
          delay (1000);          //Descontamos en periodos de 1 segundo
          segundostotal--;    
          ahoras = ((segundostotal / 60)/ 60);   //Convertimos los segundos totales en horas
          aminutos = (segundostotal / 60) % 60;  //Convertimos los segundos totales en minutos
          asegundos = segundostotal % 60;        //Convertimos los segundos totales en periodos de 60 segundos
          lcd.setCursor(0,0);
          lcd.print("Tiempo restante");        //Mostramos mensaje de tiempo restante
          lcd.setCursor(4,1);
          if (ahoras < 10) lcd.print("0");     // Si las horas son menor que 10, pone un "0" delante.
          lcd.print(ahoras);                   // Sin este codigo, se muestra asi: H:M:S  (1:M:S)
          lcd.print(":");
          if (aminutos < 10) lcd.print("0");   // Si los minutos son menor que 10, pone un "0" delante.
          lcd.print(aminutos);                 // Sin este codigo, se muestra asi: H:M:S  (H:1:S)
          lcd.print(":");
          if (asegundos < 10) lcd.print("0");  // si el valor de segundo esta por debajo de 9 (unidad) antepone un cero
          lcd.print(asegundos);                // Sin este codigo, se muestra asi: H:M:S  (H:M:1)
            if (segundostotal == 0)            //Si finaliza el tiempo
            {          
               while(1)                        //Bucle infinito mostrando mensaje y haciendo sonar el zumbador intermitentemente
               {              
                    lcd.clear();
                    lcd.setCursor(5,0);
                    lcd.print("Tiempo");
                    lcd.setCursor(3,1);
                    lcd.print("Finalizado");
                   sonarTono(TONO_ERROR,TIME_INTERVAL);
                   exit(0);
               }     
            }
       }
  }
      //------------------------------------
      // SONAR TONO
      //------------------------------------
      void sonarTono(int tono, int duracion)
      {
        tone(buzzer,tono,duracion);
        delay(duracion);
      }
   
  

Analog joystick module project

 
   // Arduino pin numbers
  const int SW_pin = 2; // digital pin connected to switch output
  const int X_pin = 0; // analog pin connected to X output
  const int Y_pin = 1; // analog pin connected to Y output
  
  void setup() {
    pinMode(SW_pin, INPUT);
    digitalWrite(SW_pin, HIGH);
    Serial.begin(9600);
  }
  
  void loop() {
    Serial.print("Switch:  ");
    Serial.print(digitalRead(SW_pin));
    Serial.print("\n");
    Serial.print("X-axis: ");
    Serial.print(analogRead(X_pin));
    Serial.print("\n");
    Serial.print("Y-axis: ");
    Serial.println(analogRead(Y_pin));
    Serial.print("\n\n");
    delay(1000);
  }
 
  

HC-SR501 PIR Sensor project

 
    int ledPin = 13;  // LED on Pin 13 of Arduino
  int pirPin = 7; // Input for HC-S501
  
  int pirValue; // Place to store read PIR Value
  
  
  void setup() {
    
    pinMode(ledPin, OUTPUT);
    pinMode(pirPin, INPUT);
   
    digitalWrite(ledPin, LOW);
    
    
    
  }
  
  void loop() {
    pirValue = digitalRead(pirPin);
    digitalWrite(ledPin, pirValue);
  
  }
 
  

MAX7219 LED Dot Matrix Module project

VCC and Ground are connected to the Arduino. Pin 12 is connected to DIN, Pin 11 is connected to CS and Pin 10 is connected to CLK.

 
  #include "pitches.h"
   
  // notes in the melody:
  int melody[] = {
  NOTE_C5, NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5, NOTE_C6};
  int duration = 500;  // 500 miliseconds
   
  void setup() {
   
  }
   
  void loop() {  
  for (int thisNote = 0; thisNote < 8; thisNote++) {
  // pin8 output the voice, every scale is 0.5 sencond
  tone(8, melody[thisNote], duration);
       
  // Output the voice after several minutes
  delay(1000);
  }
     
  // restart after two seconds 
  delay(2000);
  }