3

I am making an Infrared text message sender and receiver with the help of a couple diodes.

It basically can be seen as two diferent circuits, the one that sends, and the one that receives.

The one that sends is working properly, encoding the message in a base 4 number and sending the appropiate frequencies that I set up for it.

The one that receives seems to be having trouble, when It calculates the period of the incoming wave, it just hangs up, and I have to reset the arduino for it to be able to process another command. (This function is calculator(), other functions that enter in the reconstructing part are measure and reconstruye)

I have done a little bit of debugging, and found out that it hangs up when it enters the function to calculate the period, but I don't know what could possibly be doing that.

Now I don't know what I could do to fix the arduino hanging up, here next I attach the code I did, if spanish comments are a problem, I could turn them to english.

Thanks for the help in advance!

    #define Tonepin 11  //Pin where tone will play
    #define Interrupt 2 //Pin to interrupt
    #define maxNchars 8 //Array size
    #define mil 1000 //Number 1000 in lettres

    struct  Alfabeto  //We define an structure that contains both arrays for our alphabet
    {
      const char Mean[maxNchars] =           //Array of letters
      { 'a', 'b', 'c', 'd', 'e', 'f', 'g' , 'k' };
      const int Meaning [maxNchars] =       //Array of letter to number
      { 0, 1, 2, 3, 4, 5, 6, 7};
      const uint8_t  Freq[maxNchars] =    //Array of frequencies unmultiplied
      { 2,  3,  4,   5,  6,  7,  9,   16 };
      const int ExpPeriods[maxNchars] =  //Array of experimental periods in mS
      { 19968, 13312, 9984, 8000, 6656, 5696, 4416, 2496};
    };

    Alfabeto abc; //Create the abc member of the structure
    /* Frequency guide (Hz)for FreqFactor=25
     * a = 50
     * b = 75
     * c = 100
     * d = 125
     * e = 150
     * f = 175
     * g = 225
     * k = 400
     */


    int toneDur = 10; //Duration of the tone in mS
    int FreqFactor = 25; //Factor to be multiplied by frequency
    char vectorenviar[4];  // vector donde conservar el arreglo de letras
    int Vectorauxiliar[9];  //Vector para ayudar con la recepcion
    volatile int Decriptadorauxiliar[4];  //Arreglo auxiliar para decriptar mensaje
    bool decriptador = false;   //Condicional auxiliar para decriptar
    int r = 0;                    //indice auxiliar para arreglo decriptador

    volatile long time1 = 0;  
    volatile long time2 = 0;
    volatile unsigned long intaux = false;
    long period = 0;

    String inputSerial = "";     //String to hold input data
    String outputSerial = "";    //String to hold output data
    bool finished = false;       //check is string is complete


    String codigo4letras = "";   //string auxiliar para reconstruir

    void reconstruye()
    {
     // YA TENGO 4 potencias, convertir de vuelta a numero y luego
     // convertir dicho numero en la letraDelMensaje ex= codigo4letrsa=2310
      int n=0;
      for(int power=0; power<codigo4letras.length(); power++)
      {
        char o = codigo4letras[power];
        int u = (int)o;
        u -= 48;
        n += (u * (int)pow(4,power) );
      }
    char Letra= (char)n;

      outputSerial+= Letra;
      codigo4letras = "";

    Serial.print(outputSerial);
    Serial.println(" Is what you received\n");

    }

    int calculator()  //Calcula el periodo de la onda recibida
    {
    //  Serial.println("      *****Entering Calculator");  //calculator test
      period = abs( time2 - time1 );
      Serial.print(period);
      Serial.println(" us is the period");   //Period Test

    int i=0;

    double incerteza = 600;

    for ( i=0; i<sizeof(abc.ExpPeriods);i++)
    {

    double windowA = abc.ExpPeriods[i] + incerteza;
    double windowB = abc.ExpPeriods[i] - incerteza;
      if (period < windowA && period > windowB ) break;
    }

    //Serial.print("indice ");  //Indice test
    //Serial.println(i);

    int indiceasociado = i;

      return indiceasociado;
    }

    void measure()  //Mide la diferencia de tiempos entre las ondas recibidas
    {
      bool y = (bool)digitalRead(Interrupt);

      if(y == true && intaux == false)     //Primera ves que se mete en el interrupt
      {
        time1=micros();
        intaux=true;
      }

      else if(y == true && intaux == true)    //Segunda ves que se mete, calcula cosas.
      {
        time2=micros();
        intaux=false;
        int indice = 6;    //Reinicia el valor indice
        indice = calculator();   //calcula el indice
      for (int lalala=0;lalala<4;lalala++)
      {
        Serial.print(Decriptadorauxiliar[lalala]);
      }
        Serial.println("      *****Is The reconstructed number");            //Reconstructed number test

        while (r < 4)
        {
          if (indice == 0 || indice == 1 || indice == 2 || indice == 3 && decriptador == false)  //Si es un numero de 0 al 3, lo guarda en una matriz
          {
            Decriptadorauxiliar[r]=indice;         //Establece el contenido
            decriptador=true;
            break;
          }
         else if (indice == 7 && decriptador == true)  //Si es el numero 7, no lo guarda pero aumenta a la siguiente posicion
          {
          r++;  
          decriptador=false;
          break;
          }
        }
                //Si el ultimo contenido de la matriz, es un numero valido definido por nosotros, empieza a reconstruir
          if (Decriptadorauxiliar[3]== 0 || Decriptadorauxiliar[3]== 1 || Decriptadorauxiliar[3]== 2 || Decriptadorauxiliar[3]== 3)  
            {
              for(int j=0;j<4;j++)
              {
                codigo4letras += Decriptadorauxiliar[j];    //Llena un string auxiliar.
              }
      reconstruye();            //Reconstruye la letra
      for(int z=0;z<4;z++)  //Reinicia la matriz
      {
        Decriptadorauxiliar[z]=6;
      }
      r=0;        //Reinicia un auxiliar para cuando venga la siguiente letra
            }
         //   Serial.println("      *****Out of the else if");  //else if test
      }
     // Serial.println("      *****Out of the Interrupt");  //Interrupt test
    }

    void vectorizador(int numero, int base, char jey)  //Guarda el numero en un arreglo de cuatro letras, que representa un numero en base 4
    {

      for(int i=0;i<4;i++)
      {
        vectorenviar[i]=abc.Mean[0];
      }
     Serial.print(jey);
     Serial.print("  ");
     Serial.print(numero);
     Serial.println("  Character and number in ASCII table");

      for(int indice=0; indice<4; indice++)
      {
        char a = abc.Mean[numero%base];
        Serial.print(a);
        vectorenviar[indice]=a;
        numero=numero/base;
      }
      Serial.println("  Is the number in letters");

    //Serial.println("SALIO");

    Vectorauxiliar[0]=vectorenviar[0];
    Vectorauxiliar[1]=abc.Mean[7];
    Vectorauxiliar[2]=vectorenviar[1];
    Vectorauxiliar[3]=abc.Mean[7];
    Vectorauxiliar[4]=vectorenviar[2];
    Vectorauxiliar[5]=abc.Mean[7];
    Vectorauxiliar[6]=vectorenviar[3];
    Vectorauxiliar[7]=abc.Mean[7];
    }

    void tonesender()  //Manda los tonos correspondientes a las 4 letras del vector y guarda el periodo correspondiente a esa letra
    {


      for(int i=0; i< sizeof(Vectorauxiliar); i++)
      {
      int j = 0; //Auxiliar int to link both arrays
      char any = Vectorauxiliar[i];  //Selects the first character of the input array.
     // int index = 0;  //define the index, to link both arrays
        for(int j=0; j < sizeof(abc.Mean) ;j++)
        {
          if (any == abc.Mean[j])  //Sets the index to link to Freq array
            {
             break;  //if any == abc.Mean[index], break for loop
            }
        }
          int freqM = abc.Freq[j]; //defines the freq to use
          freqM *= FreqFactor;  //applies freq factor
          tone(Tonepin, freqM, toneDur);  //Sends tone from pin(tonepin), with freq(FreqM) and duration(toneDur)
          Serial.println("      *****Sending tone");  //tone test test
          delay(2*toneDur);
      }
    }


    void setup() {
    Serial.begin(9600);   //Inizialize serial comunications
    inputSerial.reserve(100);        //reserves 100 bytes for string
    pinMode(Tonepin, OUTPUT);
    pinMode(Interrupt, INPUT);
    attachInterrupt(digitalPinToInterrupt(Interrupt), measure, CHANGE);
    Serial.print("Enter your Message to be transmitted: ");
    Serial.println("");
    }

    void loop() {
      if(finished==true)
      {

        outputSerial = "";

      Serial.print(inputSerial);
      Serial.print(" Is what you typed");
      Serial.println("");

     for(int i=0; i<(inputSerial.length()-2); i++)
      {

        for(int z=0;z<4;z++)
              {
                Decriptadorauxiliar[z]=6;
              }  


      char h = inputSerial[i];
     // Serial.println(h);
     int k = (int) h;
     // Serial.println(k);
      vectorizador(k, 4, h);
      tonesender();
      }

      finished= false;
      inputSerial= "";
      }
    }

    void serialEvent()
    {
       if(Serial.available())
       {
        //Get new byte:
        char aux = (char)Serial.read();
        //add it to inputSerial:
        inputSerial += aux;
        // if incoming character is carriage return or newline, finish the string concatenation
          if (aux == '\n' || aux == '\rn')
          {
            finished= true;
          }
       }
    }
Ovog
  • 57
  • 5

1 Answers1

2

This code looks really strange (even for Arduino code in Spanish).

I don't know that you can do what you did there with the struct Alfabeto, i.e. show a template of the default initializers.

But this:

for ( i=0; i<sizeof(abc.ExpPeriods);i++)

must be wrong, even in Arduino-land sizeof should yield the size in bytes, not the array length. Since that's an array of int, this majorly oversteps the array, with random consequences. It should be:

for (i = 0; i < sizeof abs.ExpPeriods / sizeof *abs.ExpPeriods; ++i)'

Dividing by sizeof (int) is (in my opinion) a worse solution, since that hardcodes knowledge about the type of a variable in a second place, that will break if the type ever changes.

unwind
  • 391,730
  • 64
  • 469
  • 606