V

Dependencies:   mbed FatFileSystemCpp TextLCD

main.cpp

Committer:
bertonieto
Date:
2019-08-12
Revision:
2:73cbcff90232
Parent:
1:93d8becc35f9

File content as of revision 2:73cbcff90232:

#include "mbed.h"
#include "TextLCD.h"
#include <string>
#include "MSCFileSystem.h"

#define FSNAME "msc"

MSCFileSystem msc(FSNAME);

LocalFileSystem local("local");    

int saleBicho;
//definimos la bascula para despues obtener el peso 
Serial serialBascula(p9, p10); //Tx,Rx
Serial serialBt(p13, p14);

Serial pc(USBTX, USBRX);

//Led que usamos para ver si leeemos
DigitalOut led3(LED3);

//Definimos los LED
DigitalOut ledAux1(p15);
DigitalOut ledAux2(p29);
DigitalOut ledAux3(p30);
DigitalOut ledManual(p16);          //Led de estado manual por defecto apagado
DigitalOut ledEntrada(p17);         //Led de puerta de entrada por defecto apagado
DigitalOut ledSalida(p18);          //Led de puerta de salida
DigitalOut ledIzquierda(p19);       //Led de puerta Izquierda
DigitalOut ledDerecha(p20);         //Led de puerta Derecha

//Definimos las entradas
DigitalIn manual(p21);              //Botón Manual
DigitalIn entrada(p5);              //Botón Entrada
DigitalIn salida(p6);               //Botón Salida
DigitalIn izquierda(p7);            //Botón Izquierda
DigitalIn derecha(p8);              //Botón Derecha
DigitalIn masMax(p22);              //Botón Sumar Peso Max
DigitalIn menosMax(p23);            //Botón Restar Peso Max
DigitalIn masMin(p24);              //Botón Sumar Peso Min
DigitalIn menosMin(p25);            //Botón Restar Peso Min

DigitalIn sensorPiston(p26);        //Sensor Piston
DigitalIn presenciaEntrada(p11);    //Sensor Entrada
DigitalIn btnBT(p12);     //Se cambia por lo de ABAJO
//DigitalIn presenciaSalida(p12);     //Sensor Salida --> se cambia a btnBT

int btnBTBorra=0;

//Escribimos los datos del archivo de los pesos en el MBED en el puerto serie para que pase por el BT
void esBT()
{
    char buf[20480];
    memset(buf,'\0',20480);
    
    FILE *f = NULL;
    f = fopen("/local/PESOS.txt", "r");
    
    if(f==NULL) {
       serialBt.printf("Problema con el BT\r\n");
    }
    size_t br;

    while((br=fread(buf,1,20480,f))!=0) {
       serialBt.printf(buf);
       serialBt.printf("\r\n");
       serialBt.printf("FIN PESOS------------\r\n");
    }
    fclose(f);

    wait(1);

    memset(buf,'\0',20480);

    f = fopen("/local/TOTAL.txt", "r");
    
    if(f==NULL) {
       serialBt.printf("Problema con el BT\r\n");
    }

    while((br=fread(buf,1,20480,f))!=0) {
       serialBt.printf("TOTAL:   ");
       serialBt.printf(buf);
       serialBt.printf("\r\n");

    }
    fclose(f);

    wait(1);

    memset(buf,'\0',20480);

    f = fopen("/local/PINTA.txt", "r");
    
    if(f==NULL) {
       serialBt.printf("Problema con el BT\r\n");
    }

    while((br=fread(buf,1,20480,f))!=0) {
       serialBt.printf("PINTADOS:   ");
       serialBt.printf(buf);
       serialBt.printf("\r\n");

    }
    fclose(f);

    wait(1);


    memset(buf,'\0',20480);

    f = fopen("/local/CLASIF.txt", "r");
    
    if(f==NULL) {
       serialBt.printf("Problema con el BT\r\n");
    }

    while((br=fread(buf,1,20480,f))!=0) {
       serialBt.printf("CLASIFICADOS:   ");
       serialBt.printf(buf);
       serialBt.printf("\r\n");

    }
    fclose(f);
    wait(1);
}
//escribir los pesos en el archivo correspondiente PESOS.txt                                          --------------------------------------------------------
void escribirPesos(int i)
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/PESOS.txt", "a");  // Open "out.txt" on the local file system for writing
    fprintf(fp,  "%d \r\n", i);
    fclose(fp);
    }

void borrarPesos()
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/PESOS.txt", "w");  // Open "out.txt" on the local file system for writing
    fprintf(fp,  "");
    fclose(fp);
    }
    
int leeTotal()
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/TOTAL.txt", "r");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    int total;
    fgets(buffer,10,fp);
    fclose(fp);
    total=atoi(buffer);
    return total;
}


void escribeTotal(int i)
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/TOTAL.txt", "w");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    sprintf (buffer, "%d", i);
    fprintf(fp, buffer);
    fclose(fp);
}

int leeClasificados()
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/CLASIF.txt", "r");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    int clasificados;
    fgets(buffer,10,fp);
    fclose(fp);
    clasificados=atoi(buffer);
    return clasificados;
}


void escribeClasificados(int i)
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/CLASIF.txt", "w");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    sprintf (buffer, "%d", i);
    fprintf(fp, buffer);
    fclose(fp);
}

int leePintados()
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/PINTA.txt", "r");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    int pintados;
    fgets(buffer,10,fp);
    fclose(fp);
    pintados=atoi(buffer);
    return pintados;
}


void escribePintados(int i)
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/PINTA.txt", "w");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    sprintf (buffer, "%d", i);
    fprintf(fp, buffer);
    fclose(fp);
}

//Escribimos en el USB
void escribirUSB(int peso)
{
    FILE *fp = fopen( "/" FSNAME "/basculapesos.txt", "a");
    fprintf(fp, "%d \r\n", peso);
    fclose(fp); 
    }

//Iniciamos los led auxiliares.
void iniciaAux()
{
    ledAux1 = 0;
    ledAux2 = 0;
    ledAux3 = 0;
    }
//leemos de memoria flash la variable del peso minimo de clasificacion.
int leeMinMem()
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/MIN", "r");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    int minim;
    fgets(buffer,10,fp);
    fclose(fp);
    minim=atoi(buffer);
    return minim;
    }

//leemos de memoria flash la variable del peso maximo de clasificacion.
int leeMaxMem()
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp1 = fopen("/local/MAX", "r");  // Open "out.txt" on the local file system for writing
    char buffer1 [10];
    int max;
    fgets(buffer1,10,fp1);
    fclose(fp1);
    max=atoi(buffer1);
    return max;
    }

//Iniciamos pesos Max y Min
int pesoMax = leeMaxMem();
int pesoMin = leeMinMem();

//Iniciamos total de pesos
int total=leeTotal();
int clasificados=leeClasificados();
int pintados=leePintados();


//Iniciamos I2C Communication
I2C i2c_lcd(p28,p27); // SDA, SCL
TextLCD_I2C lcd(&i2c_lcd, 0x4E, TextLCD::LCD16x2, TextLCD::HD44780); // I2C bus, PCF8574 Slaveaddress, LCD Type, Device Type

//Iniciamos el LCD.
void iniciaLCD()
{
    lcd.setMode(TextLCD::DispOn); //DispOff, DispOn
    lcd.setBacklight(TextLCD::LightOff);//LightOff, LightOn
    lcd.setCursor(TextLCD::CurOff_BlkOff);//CurOff_BlkOff, CurOn_BlkOff, CurOff_BlkOn, CurOn_BlkOn
}

//Pintamos en el LCD linea 1.
void pintaLCD1(bool manual){
    if (manual){
        lcd.locate(0,0);
        lcd.printf("     MANUAL     ");

        }
        else{
            lcd.locate(0,0);
            lcd.printf("Salida1  Salida2");
            }
    }
    
//Pintamos en el LCD linea 2.
void pintaLCD2(){
    lcd.locate(0,1);
    lcd.printf("<%dKg. ", pesoMin);
    lcd.locate(7,1);
    lcd.printf("  >%dKg.", pesoMax);
}

int leerPeso(){
    char buffer1[30];
    string pesoss ="";
    int ipesoss =0;
    serialBascula.printf("2005002D:<CR><LF>\n");   //\r\n   2005002D:<CR><LF>\n
        
    pesoss = serialBascula.gets(buffer1,30);
    if (buffer1[0]=='9'){
        pesoss = pesoss.substr(11,3);
        ipesoss = atoi(pesoss.c_str());
    }   
             
    return ipesoss; 
}

void escribeMaxMem(int i)
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/max", "w");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    sprintf (buffer, "%d", i);
    fprintf(fp, buffer);
    fclose(fp);
    }
    
void escribeMinMem(int i)
{
    LocalFileSystem local("local");       // Create the local filesystem under the name "local"
    FILE *fp = fopen("/local/min", "w");  // Open "out.txt" on the local file system for writing
    char buffer [10];
    sprintf (buffer, "%d", i);
    fprintf(fp, buffer);
    fclose(fp);
    }
void BtBorraArchivos()
{
    //TODO Borramos todos los archivos para que queden inicializados.
    pc.printf("\r\nBORRAMOS TODOS ARCHIVOS\r\n");
    escribeTotal(0);
    escribePintados(0);
    escribeClasificados(0);
    borrarPesos();
    }

void cambioManual()
{
    if (ledManual == 1){
        //reescribimos el dato en MAX y MIN al volver de manual por si se ha cambiado
        escribeMaxMem(pesoMax);
        escribeMinMem(pesoMin);
        ledManual = 0;
        if (btnBTBorra == 1)
        {
            BtBorraArchivos();  //borramos los archivos de pesos que hemos rellenado
            btnBTBorra = 0;
            }
        pintaLCD1(0);
        wait(0.50);
    }
    else{
        ledManual = 1;
        pintaLCD1(1);
        wait(0.50);
    }
}

    
//Main, aqui ponemos todo el programa.
int main()
{
    
    pc.printf("INICIANDO...");
        
    wait(1);
    
    iniciaLCD(); //Iniciamos el LCD
    pintaLCD1(0);
    pintaLCD2();
    int pesoreal;
    
    //int estaPesado; //si esta pesado 1, si no esta pesado 0 

    while(1) {
        //Modo manual: se pueden cambiar pesos y mover las puertas
        while(ledManual == 1)
        {
            //Compruebo el BT
            if(btnBT ==1){
                esBT();
                btnBTBorra=1;   //bool para borrar si vuelve a manual.         
                wait(1);
                }
            
            //Fin de Compruebo el BT
            if (manual == 1)
            {
                cambioManual();}
            if (entrada == 1)
            {
                if(ledEntrada == 1)
                    {
                        ledEntrada = 0;
                        wait(0.50);
                        }
                    else
                    {
                        ledEntrada = 1;
                        wait(0.50);
                        }
                }
            if (salida == 1)
            {
                if(ledSalida == 1)
                    {
                        ledSalida = 0;
                        wait(0.50);
                        }
                    else
                    {
                        ledSalida = 1;
                        wait(0.50);
                        }
                }
            if (izquierda == 1)
            {
                ledIzquierda = 1;
                wait(0.50);
                ledIzquierda = 0;
                }
            if (derecha == 1)
            {
                if(ledDerecha == 1)
                    {
                        ledDerecha = 0;
                        wait(0.50);
                        }
                    else
                    {
                        ledDerecha = 1;
                        wait(0.50);
                        }
                }
            if (masMax == 1)
            {
                if (pesoMax < 2000)
                    {
                        pesoMax += 1;
                        wait(0.10);
                        pintaLCD2();
                        }
                }
            if (menosMax == 1)
            {
                    if (pesoMax > (pesoMin + 1))
                        {
                            pesoMax -= 1;
                            wait(0.10);
                            pintaLCD2();
                            }
                }
            if (masMin == 1)
            {   
                if(pesoMin < (pesoMax - 1))
                    {
                        pesoMin += 1;
                        wait(0.10);
                        pintaLCD2();
                        }
                }
            if (menosMin == 1)
                {if(pesoMin > 10)
                    {
                        pesoMin -= 1;
                        wait(0.10);
                        pintaLCD2();
                        }
                }
        }
        //empezamos el programa
        ledEntrada = 1;
        ledSalida = 0;
        ledDerecha = 0;
        ledIzquierda = 0;
        pesoreal = 0;
        saleBicho = 0;
        if (manual == 1){
            cambioManual();
        }
        
        //Bucle de entrada a la báscula y funcionamiento real
        wait(0.2);
        int tiempoSinSensorPiston = 0;
        while(presenciaEntrada == 1 && ledManual == 0){
            pc.printf("UNO");
            ledEntrada = 0;
            //Se Comprueba que el bicho no ha salido para no mover la puerta de salida
            if (saleBicho == 0){
                ledSalida = 0;
            }
            //Se comprueba que no se cambia a manual
            if (manual == 1){cambioManual();}
            wait(1);
            if(sensorPiston == 1){
                pc.printf("DOS");
                //Tiempo a esperar para que la bascula calcule el liveWeitgh
                int tiempoLectura = 0;
                //Bucle de espera para obtener el peso (3,5 s)
                while(tiempoLectura < 40 && ledManual == 0 && presenciaEntrada == 1){
                    wait(0.1);
                    if (manual == 1){cambioManual();}
                        tiempoLectura++;
                }
                if (saleBicho == 0){
                    pc.printf("DOS Y MEDIO");
                    pesoreal = leerPeso();
                    //estaPesado = 1;
                    //AQUI GUARDO LOS BICHOS EN EL FICHERO PESOS                      -------------------------------------------------> guardo en el fichero
                    pc.printf("TRES");
                    wait(0.8);
                    
                //} CAMBIO EN ESTE FINAL DEL IF despues de la comprobacion de abajo, para que solo cambie puertas una vez.
                //Comprobamos el pero obtenido para clasificar o salir
                if (pesoreal < 50000 && ledManual == 0 && presenciaEntrada == 1){
                    pc.printf("CUATRo");
                    
                    pc.printf("PESO: %d \r\n",pesoreal);
                    if (pesoreal > pesoMin && saleBicho == 0){
                        ledDerecha = 1;
                        clasificados += 1;
                        escribeClasificados(clasificados);
                        //escribimos el peso real de animales clasificados en el USB
                        //escribirUSB(pesoreal);
                        if (pesoreal < pesoMax){
                            ledIzquierda = 1;
                            wait(0.5);
                            ledIzquierda = 0;
                            pintados += 1;
                            escribePintados(pintados);
                        }
                        wait(0.50);
                    }
                }//cierro el if de salebicho == 0 
                    wait(0.1);
                    if(ledManual == 0){
                        ledSalida = 1;
                    }
                    saleBicho = 1;
                    total += 1;
                    escribeTotal(total);
                    escribirPesos(pesoreal);
                    
                    //escribimos todos los pesos de los animales que pasan en el USB
                    //escribirUSB(pesoreal);
                }
            }
            //Else del if del sensor del piston
            else{
                tiempoSinSensorPiston = tiempoSinSensorPiston +1;
                wait(0.5);
                if (tiempoSinSensorPiston > 10){
                    ledEntrada = 1;
                    wait(2);
                }
            }
        }  
    }
}