martes, 24 de mayo de 2016

Project

This project consist on measuring the temperature of our house from our school.

Material needed:
-1 House with internet and a router
-1 Computer with Labview and Arduino
-1 Relay
-1 TTL-RS232 Adapter (made by ourselves)
-Wires
-1 Raspberry Pi
-1 LM35
-1 smartphone with Putty installed on it

Steps:
1-We send a message which starts with an "h" on the browser, introducing our public IP. For this step, we will have our computer in our house, connected to the internet with LabVIEW and the port 8088.
2-We will take our smartphone with Putty and we introduce our public IP and the port 22, to connect our Raspberry Pi.
3-In putty, we will start the program.
4-LabVIEW will send the message to the Arduino, with the message that we have introduced on it.
5-If the message is wrong, the program will finish. If the message is right, the program will continue and we will see the message introduced in our smartphone.
6-The program will ask us if we want to continue. We will choose Y (yes) or N (no). If we choose yes, we will continue. Else, the program will stop.
7-The program will show the temperature of our house in our smartphone, reading the LM35.


We can see all the steps in this image, made by our teacher on the blackboard of our class:



LabVIEW Program:
Here, we will see the LabVIEW program. In the main screen of the program, we have the instructions of this project and how this program works, a part to introduce text and a part to see the text introduced. We also have a LED to see if the text starts with a "h" and a button to stop the program.


In the block diagram, we initialize the variables to zero, we will switch on the LED if the text introduced starts with an "h". Then, we will send the text through the Serial port all the time.


Open Ports:
To open ports in our router, it depends on the router. In our case, we have a router of Movistar, so we introduce the IP of the router, we introduce the key and then, we will see this:


Then, we go to: "Configuracion basica -> puertos -> puertos IP V4"
Here, we introduce the port that we want to connect to.





Arduino Program:

/*
////////////////////////////////////////////////////////////////////////////////////
//   AUTOR: CIFP nº UNO                                              Noviembre/2015
////////////////////////////////////////////////////////////////////////////////////
//   PROGRAMA:    PROYECTO RPi                         VERSIÓN:       1.0
//   DISPOSITIVO: ATMEL 328                            COMPILADOR:    AVR
//   Entorno IDE:   1.6.5                              SIMULADOR:  
//   TARJETA DE APLICACIÓN: ARDUINO / MSE              DEBUGGER:  
////////////////////////////////////////////////////////////////////////////////////
*/

///////////////////////////////////////////////////////////////////////////////////
// LIBRERÍAS //////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//Here, we introduce the libraries that we will use
#include <SoftwareSerial.h>
//We instantiate the class "SoftwareSerial" and create the object "nuevo_com"
SoftwareSerial nuevo_com(4, 7); //Rx:2 , Tx:3

///////////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES //////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
#define LM35 A4 //We connect the LM35 to the pin A4
#define rele 11 //We connect the relay to the pin 11
int leer_lm35; //We declare this variable as an integer
float temp; //We declare the temperature as a float number
boolean flag = false; //We declare the flags
boolean flag2 = true;
char cadena[100]; //We create an array to keep the characters introduced on the arduino, until a maximum of 100 characters
byte posicion=0;  //Variable to change the position of the characters of the array

////////////////////////////////////////////////////////////////////////////////////
// CONFIGURATION ///////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  pinMode(10, OUTPUT); //We set these pins as an output
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(11, OUTPUT);
  Serial.begin(9600); //The serial ports will work at 9600 bauds
  nuevo_com.begin(9600);
  analogReference(INTERNAL); //We set the analog reference as internal (1.1V)
}

////////////////////////////////////////////////////////////////////////////////////
// MAIN ///////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
void loop()
{
digitalWrite(rele, 0); //We set the relay to 0

///////////////////////////// first WHILE ////////////////////////////////////////////////////////////////////

flag = true;
while (flag == true)
  {
  if (Serial.available())
    {
    char c = Serial.read(); //We keep the read character in a variable
    if (c == 'Y')
      {
      digitalWrite(10, 1);
      while (flag2 == true)
          {
          if(nuevo_com.available()) //We test if we have characters inside the buffer
               {
               digitalWrite(6, 1);
               while (nuevo_com.available()>0)
                    {
                    cadena[posicion]=nuevo_com.read();
                    posicion++;
                    delay(100);
                    }
               cadena[posicion] =' '; //This is if we want to read again
               posicion++;
               Serial.println(cadena);
               flag = false;
               flag2 = false;
              }          
         }
       }
    }
  }
///////////////////////////// second WHILE ////////////////////////////////////////////////////////////////////
/*
Here, the raspberry will see if we want to keep reading data or stop the program
*/

flag = true;
while (flag == true)
    {
    if (Serial.available())
      {
      char d = Serial.read(); //We save the data read in a variable
      if (d == 'Y')
        {
          digitalWrite(9, 1);
          flag = false;
          //We set the input pin of the raspberry to 1
          digitalWrite(rele, 1);
          delay(3000);
          digitalWrite(rele, 0);
        }
       delay (100);
      }
    }
///////////////////////////// third WHILE ////////////////////////////////////////////////////////////////////
/*
Here, we will send all the time the temperature read from the LM35 to the raspberry.
The LM35 is a sensor of temperature with a precision of 1ºC
It measures from -55°C to 150°C.
*/
while (1)
{
leer_lm35=analogRead(LM35);
temp = map(leer_lm35,0,1024,0,(1.1*100));
Serial.print("Temperatura leida mediante el LM35: ");
Serial.print(temp);
Serial.println(" C");
delay(1000);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} // End of the program


Raspberry Pi program:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#Here, we have said that we will use the keyboard of our computer and we say the raspberry that it's a python program

#Here, we import the libraries that we need
import RPi.GPIO as GPIO
import time
import sys
import serial

##########################################################################
## We configure the ports and we declare the variables
##########################################################################
GPIO.setmode(GPIO.BCM) #We configure the ports in BCM mode
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #We say that if the input pin is at the air, the input is like if had a 0
#We create the object "ser" (our arduino)
ser = serial.Serial('/dev/ttyUSB0', 9600)

flag=False

##########################################################################
# FUNCTIONS
##########################################################################
def mi_evento(canal):
    global flag
    flag=True
    print('Se ha detectado que se ha activado el pin %s' % canal)
If we find out that a pin has been activated (the relay), we came to this function

##########################################################################
# MAIN
##########################################################################
#We say the user if he wants to see what have we send
#Then, we print on the screen what we have sent
from serial import Serial

respuesta_correcta=False
while respuesta_correcta==False:
    print('¿Desea iniciar el programa?')
    print('Seleccione: Y/N')
    Letra = str(input())
    if Letra=='N':
        respuesta_correcta=True
        Variable_Seguir=0
    elif Letra=='Y':
        respuesta_correcta=True
        Variable_Seguir=1
    else:
        print('Respuesta erronea')
ser.write(bytes(Letra.encode('ascii')))

#We print on the screen that we are waiting for the arduino answer and when it arrives, we print it
#If the phrase is not correct, we close the program
#We test if the phrase is correct comparing the first letter
if Variable_Seguir==1:
    print('Esperando respuesta del Arduino...')


#We will clean the buffer here
Primera_Letra='error'
if Variable_Seguir==1:
    inicio=0
    while inicio==0:
        ValorLeido=ser.read()
        if ValorLeido== b' ':
            inicio=1

    Texto=[]
    Seguimos_Leyendo=1
    i=0
    Primera_Letra=0
    while Seguimos_Leyendo==1:
        UltimaLetra=ser.read()
        if i==0:
            Primera_Letra=UltimaLetra.decode('UTF-8')
            i=1
        Texto=Texto+[UltimaLetra.decode('UTF-8')]
        if UltimaLetra== b' ':
            Seguimos_Leyendo=0
         
    #print('Texto leido:')
    #print(Texto)
    TextoUnido=''.join(Texto)
    print('Texto Leido:')
    print(TextoUnido)


Respuesta_Correcta=False
if Primera_Letra=='h':
    print('Respuesta correcta!!')
    while Respuesta_Correcta==False:
        print('¿Enviar "Y" al arduino?')
        print('Selecciona: Y/N')
        Letra_Seguir=str(input())
        if Letra_Seguir=='N':
            Respuesta_Correcta=True
            Variable_Seguir=0
            print('FIN DEL PROGRAMA')
            N=0
        elif Letra_Seguir=='Y':
            Respuesta_Correcta=True
            N=1
        else:
            print('Respuesta erronea')
            N=0
        ser.write(bytes(Letra_Seguir.encode('ascii')))

else:
    print('Frase incorrecta')
    N=0
    print('FIN DEL PROGRAMA')


#We clear the buffer:
Temperatura=ser.readline()

try:
    if N==1:
        print('Esperando interrupción desde Arduino...')
        while flag==False:
            time.sleep(1)
            if GPIO.input(17) == GPIO.HIGH:
                flag=True
                ser.write(bytes(Letra_Seguir.encode('ascii')))
                mi_evento(17)
    while N==1:
        #here, we will wait for the interruption of the arduino
        ser.write(bytes(Letra_Seguir.encode('ascii')))
        Temperatura=ser.readline()
        Temperatura2=Temperatura.decode('UTF-8')
        print(Temperatura2)
        time.sleep(1)
       
         
except KeyboardInterrupt: #Se ha pulsado CTRL+C
    print(' FIN')
    ser.close()
    GPIO.cleanup()
    sys.exit()                                



This would all the system with all the wires connected:




You can download all the files from here:
https://drive.google.com/folderview?id=0B20kHfrc3NnpRGV6Ykk3QzZCa00&usp=sharing


No hay comentarios:

Publicar un comentario