Autor Tema: Error al comparar dos strings con strcmp  (Leído 42620 veces)

0 Usuarios y 4 Visitantes están viendo este tema.

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #120 en: 20 de Enero de 2011, 10:57:39 »
Voy a probar eso con un cont a ver cuantas veces entra y lo mirare con un LED.
Ahora te cuento.

Edito: Ahora mismo ha hecho 2 return RCEG. Pero porque cambia y a veces hace una cosa y a veces una otra? madre mia...

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #121 en: 20 de Enero de 2011, 11:04:45 »
He hecho lo del LED en FERR y se enciende el LED3( por tanto, cont es 0, no entra nunca)
Código: [Seleccionar]
char getch()
{
int cont=0; 
while (RCIF == 0)
  {
    if (OERR == 1)
    {
      if (TXEN == 1)
      {
        TXEN=0;
        TXEN=1;
      }
      if (CREN == 1)
      {
        CREN=0;
        CREN=1;
      }
    }
 
    if (FERR == 1)
    {
      cont++;
dummy = RCREG;
      if (TXEN == 1)
      {
        TXEN=0;
       TXEN=1;
      }
    }
    CLRWDT();
 
if(cont==0)
LED3=1;
else
LED3=0;

  }
  return RCREG;
}

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Error al comparar dos strings con strcmp
« Respuesta #122 en: 20 de Enero de 2011, 11:15:10 »
  Me está volviendo loco este tema ya.  :5]
  Fijate, con el mismo sistema, si entra en el if de OERR. Ya no se que más pensar. ¿Será que por x motivo se apaga el RS232 del PIC y por ello se queda colgado? No se me ocurre nada  :x
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #123 en: 20 de Enero de 2011, 11:24:30 »
Código: [Seleccionar]

char getch()
{
int cont=0;
int cont1=0;
 
while (RCIF == 0)
  {
    if (OERR == 1)
    cont1++;
{
      if (TXEN == 1)
      {
        TXEN=0;
        TXEN=1;
      }
      if (CREN == 1)
      {
        CREN=0;
        CREN=1;
      }
    }
 
    if (FERR == 1)
    {
      cont++;
dummy = RCREG;
      if (TXEN == 1)
      {
        TXEN=0;
       TXEN=1;
      }
    }
    CLRWDT();
 
if(cont==0)
LED3=1;
else
LED3=0;

if(cont1==0)
LED2=1;
else
LED2=0;
  }
  return RCREG;
}

Se enciende el led3 y el led 2 no. Ahora si que esta entrando en FERR.... estoy alucinando... voy a seguir probando de desconectar y volverle  a dar alimentacion a ver si cada vez suceden cosas distintas

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #124 en: 20 de Enero de 2011, 11:27:05 »
Y si se trata de un tema del cable?

pero es que no puede ser, ese cable ya lo use cuando probe el programa y funciono bien. En esos tiempos metia los codigos AT a mano por el terminal y era mucho mas feliz jej.

Vamos que esto tiene que salir.. despues de las 24h de los dias dias que le estoy dedicando...

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Error al comparar dos strings con strcmp
« Respuesta #125 en: 20 de Enero de 2011, 11:31:41 »
Código: [Seleccionar]

char getch()
{
int cont=0;
int cont1=0;
 
while (RCIF == 0)
  {
    if (OERR == 1)
    cont1++;
{
      if (TXEN == 1)
      {
        TXEN=0;
        TXEN=1;
      }
      if (CREN == 1)
      {
        CREN=0;
        CREN=1;
      }
    }
 
    if (FERR == 1)
    {
      cont++;
dummy = RCREG;
      if (TXEN == 1)
      {
        TXEN=0;
       TXEN=1;
      }
    }
    CLRWDT();
 
if(cont==0)
LED3=1;
else
LED3=0;

if(cont1==0)
LED2=1;
else
LED2=0;
  }
  return RCREG;
}

Se enciende el led3 y el led 2 no. Ahora si que esta entrando en FERR.... estoy alucinando... voy a seguir probando de desconectar y volverle  a dar alimentacion a ver si cada vez suceden cosas distintas

  Mirá que está mal el código. En el caso de OERR dejaste "cont1++" fuera de las llaves "{".
  Por otro lado está bien que se encienda el LED3 ya que eso pasa cuando no hay FERR. Y que el LED2 no encienda tal vez se deba a que está mal ubicado el cont1++ en el OERR
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #126 en: 20 de Enero de 2011, 11:35:30 »
Perdon por el despiste, lo siento.. son ya demasiadas horas delante de este codigo..

Ahora si que se enciende. Se encienden los dos leds.

Código: [Seleccionar]
char getch()
{
int cont=0;
int cont1=0;
 
while (RCIF == 0)
  {
    if (OERR == 1)
    {
    cont1++; 
if (TXEN == 1)
      {
        TXEN=0;
        TXEN=1;
      }
      if (CREN == 1)
      {
        CREN=0;
        CREN=1;
      }
    }
 
    if (FERR == 1)
    {
      cont++;
dummy = RCREG;
      if (TXEN == 1)
      {
        TXEN=0;
       TXEN=1;
      }
    }
    CLRWDT();
 
if(cont==0)
LED3=1;
else
LED3=0;

if(cont1==0)
LED2=1;
else
LED2=0;
  }
  return RCREG;
}


Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #127 en: 20 de Enero de 2011, 11:38:18 »
http://www.ucontrol.com.ar/forosmf/programacion-en-asm/rx-no-activa-bandera-en-16f887/?wap2

Miremos los diagramas en el datasheet de la recepcion a ver como tiene que estar esa bandera.. no?

"geronimox:
Hola LucasBols.
Tengo entendido (en otros micros), que la bandera RCIF se pone a cero automaticamente al atender la interrupcion. Lo que te ahora el echo de tener que hacerlo a mano.
Asi que, si compruebas el estado de la bandera dentro de la rutina de interrupcion, siempre vas a leer cero.
Saludos!
"



Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #128 en: 20 de Enero de 2011, 11:47:20 »
Miremos bien en el datasheet cuando se activa y desactiva el bit.
Por ejemplo en la pag 254 (FIGURE 20-1: AUTOMATIC BAUD RATE CALCULATION)

Y por ahi salen cosas..

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #129 en: 20 de Enero de 2011, 12:24:42 »
Ojo, habia un error aquí:
Código: [Seleccionar]
void LeerRespuesta(char *mensaje) // Recibimos \n \r O K \n \r por lo tanto 6 caracteres.
{
int indice=0;
int cont=0;

while(indice<2){
*mensaje=getch();
*mensaje++;
indice++;
}

}

La variable indice se incrementaba fuera del while.. no me habia dado cuenta. Ahora SI hace return RCREG pero se queda ahi colgado. Eso es porque el indice es mayor al que tiene  que ser. Osea, pasa de estar a RCIF=0 a RCIF=1, lee los dos caracteres y vuelve a RCIF=0

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #130 en: 20 de Enero de 2011, 12:32:11 »
char getch()
{
int cont=0;
int cont1=0;
int cont2=0;
 
while (RCIF == 0)
  {
    if (OERR == 1)
    {
       cont1++; 
   if (TXEN == 1)
      {
        TXEN=0;
        TXEN=1;
      }
      if (CREN == 1)
      {
        CREN=0;
        CREN=1;
      }
    }
 
    if (FERR == 1)
    {
         cont++;
      dummy = RCREG;
      if (TXEN == 1)
      {
        TXEN=0;
       TXEN=1;
      }
    }
    CLRWDT();
 
   if(cont==0)
      LED3=1;
   else   
      LED3=0;

   if(cont1==0)
   LED2=1;
   else
   LED2=0;
  }
     cont2++;
   if(cont2==1)
   LED0=1;
   else
   LED0=0;
   return RCREG;
}

Envia un caracter.. se enciende el led0..

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Error al comparar dos strings con strcmp
« Respuesta #131 en: 20 de Enero de 2011, 12:36:37 »
Ojo, habia un error aquí:
Código: [Seleccionar]
void LeerRespuesta(char *mensaje) // Recibimos \n \r O K \n \r por lo tanto 6 caracteres.
{
int indice=0;
int cont=0;

while(indice<2){
*mensaje=getch();
*mensaje++;
indice++;
}

}

La variable indice se incrementaba fuera del while.. no me habia dado cuenta. Ahora SI hace return RCREG pero se queda ahi colgado. Eso es porque el indice es mayor al que tiene  que ser. Osea, pasa de estar a RCIF=0 a RCIF=1, lee los dos caracteres y vuelve a RCIF=0

  Si indice fuera mayor que el que tiene que ser, saldrías del while y por ende saldrías de la función.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #132 en: 20 de Enero de 2011, 12:39:11 »
Con indice <1 y este programa ( lo pongo todo porque hace tiempo q no lo subo) puedo ver como buffer1 es 'A'. Supongo que esta retornando el AT...
que cosas pruebo?

Código: [Seleccionar]

#include <htc.h>
#include <stdlib.h>  // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.h>


//#conio.h, e #iostream.h


 
__CONFIG (1, HS & CPUDIV4 & USBPLL & PLLDIV5 & FCMDIS & IESODIS); // Con 20 CPUDIV1
__CONFIG (2, BORDIS & WDTDIS & PWRTDIS);
__CONFIG (3, MCLRDIS); // estoy deshabilitando el pin de MasterClear, tal vez haya que habilitarlo, eso hay que probarlo
__CONFIG (4, LVPDIS &  DEBUGEN);
 
/* =================================================================================
Definitions
    ================================================================================= */
#define PORTBIT(adr, bit) ( (unsigned)(&adr)*8 + (bit) )
 
#define Idle_Low 1 // No envia datos
#define Idle_High 2 // Envia datos

#define true 1
#define false 0
 
#define BAUD  9600 // Configuramos la velocidad, tanto puede ser 19200 o de 9600 kbaud/s pero hay q cambiarlo tb en la simulacion de proteus
#define PIC_CLK      5000000
 
#define CS RB2

/* =================================================================================
Global variables 
  ================================================================================= */


static bit LED0 @ PORTBIT(PORTD, 0);
static bit LED1 @ PORTBIT(PORTD, 1);
static bit LED2 @ PORTBIT(PORTD, 2);
static bit LED3 @ PORTBIT(PORTD, 3);
char present_state = Idle_Low; // state variable
char future_state = Idle_Low; // state variable
unsigned int  valor_potenciometro;
unsigned int  valor_sensor_temperatura;
unsigned char pote_buf[6];
unsigned char sensor_buf[10];
char * valor_pote_en_texto;           // un puntero para almacenar el numero en texto
char * valor_sensor_en_texto;         // un puntero para almacenar el numero en texto
char byte_alto, byte_bajo;
unsigned char caracter_recibido;
unsigned char dummy;

int error_comando=1;
int error_connexion=1;
int comando_disponible=1; // No hay comando disponible
int final=1;
int prueba=1; // PRUEBA PARA SABER DONDE ESTO
char indice=0;



//CAMBIAR A 6 CON EL DISPOSITIVO
char buffer1[6];  // es 6
char * ComandoRecibido1; // este es el puntero y lo voy a usar para strcmp

char buffer2[6]; 
char * ComandoRecibido2;

char buffer3[6]; 
char * ComandoRecibido3;

char buffer4[6]; 
char * ComandoRecibido4;

char buffer5[6]; 
char * ComandoRecibido5;

char buffer6[6]; 
char * ComandoRecibido6;

char buffer7[6]; 
char * ComandoRecibido7;

char buffer8[6]; 
char * ComandoRecibido8;

char buffer9[100]; 
char * ComandoRecibido9;

char buffer10[100]; 
char * ComandoRecibido10;

char buffer11[100]; 
char * ComandoRecibido11;

int contador=0;

/* =================================================================================
Function prototypes
  ================================================================================= */
 
void init_system (void);
void time_delay (unsigned int );
char output_logic(void);
char future_state_logic(void);
 
void setup_sensor(void);
void setup_adc(void);
void serial_setup(void);
 
void putst(const char *str);
void putch(unsigned char c);

unsigned char getch(void);
unsigned char UsartReadChar_nonstop(void);
unsigned char getch_available(void);
unsigned char getche (void);
void clear_usart_errors(void);
 
unsigned char read_spi (void);
unsigned int read_adc(void);


char getch();
void LeerRespuesta(char *mensaje);
void SacarCaracteres (char buffer_todos_caracteres);


/* =================================================================================
Main function
  ================================================================================= */
 

 

void main ()
{
  //char buffer[2]; // aqui se almacena la respuesta
 
 
  //inicializar el puerto serie RS2326.
  valor_potenciometro = 0;
  valor_sensor_temperatura = 0;
  LED0 = 0;
  LED1 = 0;
  LED2 = 0;
  LED3 = 0;
 

  init_system();
  setup_sensor();
  setup_adc();
  serial_setup();


 
/* =================================================================================
Establecer connexion con comandos AT
  ================================================================================= */


//Primer comando AT

ComandoRecibido1=buffer1;

putst ("AT");
putch ('\r');

time_delay(999999999999);
LeerRespuesta (ComandoRecibido1);


if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien

error_comando=0;
//putst ("respuesta correcta");
//putch ('\r');

}
else{                                    // No es el comando bueno
   

error_comando=1;

while(error_comando==1){
//putst ("respuesta incorrecta");
//putch ('\r');
putst ("AT");
putch ('\r');
LeerRespuesta (ComandoRecibido1);

if (strcmp(ComandoRecibido1,"OK") == 0){

error_comando=0;
//putst ("respuesta correcta");
//putch ('\r');
}

}
}






/*
//Segundo comando AT

ComandoRecibido2=buffer2;
putst ("ATS0=1\n");
LED0=1;

leer_respuesta(ComandoRecibido2);
LED1=1;

if (strcmp(ComandoRecibido2,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED0=1;
LED1=1;
LED2=1;
LED3=1;

}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("ATS0=1\n");

leer_respuesta(ComandoRecibido2);

if (strcmp(ComandoRecibido2,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;

}
}
}


//Tercer comando AT

ComandoRecibido3=buffer3;
putst ("ATS512=4\n");
LED0=1;

leer_respuesta(ComandoRecibido3);
LED1=1;

if (strcmp(ComandoRecibido3,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED0=1;
LED1=1;
LED2=1;
LED3=1;

}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("ATS512=4\n");

leer_respuesta(ComandoRecibido3);

if (strcmp(ComandoRecibido3,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;

}
}
}


//Quarto comando AT

ComandoRecibido4=buffer4;
putst ("ATS502=1\n");
LED0=1;

leer_respuesta(ComandoRecibido4);
LED1=1;

if (strcmp(ComandoRecibido4,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED0=1;
LED1=1;
LED2=1;
LED3=1;

}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("ATS502=1\n");

leer_respuesta(ComandoRecibido4);

if (strcmp(ComandoRecibido4,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;

}
}
}


//Quinto comando AT

ComandoRecibido5=buffer5;
putst ("ATS536=1\n");
LED0=1;

leer_respuesta(ComandoRecibido5);
LED1=1;

if (strcmp(ComandoRecibido5,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED0=1;
LED1=1;
LED2=1;
LED3=1;

}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("ATS536=1\n");

leer_respuesta(ComandoRecibido5);

if (strcmp(ComandoRecibido5,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;

}
}
}



//Sexto comando AT

ComandoRecibido6=buffer6;
putst ("AT+BTK=1234\n");
LED0=1;

leer_respuesta(ComandoRecibido6);
LED1=1;

if (strcmp(ComandoRecibido6,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED0=1;
LED1=1;
LED2=1;
LED3=1;

}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("AT+BTK=1234\n");

leer_respuesta(ComandoRecibido6);

if (strcmp(ComandoRecibido6,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;

}
}
}



//Septimo comando AT

ComandoRecibido7=buffer7;
putst ("AT&W\n");
LED0=1;

leer_respuesta(ComandoRecibido7);
LED1=1;

if (strcmp(ComandoRecibido7,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED0=1;
LED1=1;
LED2=1;
LED3=1;

}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("AT&W\n");

leer_respuesta(ComandoRecibido7);

if (strcmp(ComandoRecibido7,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;

}
}
}




//Octavo comando AT

ComandoRecibido8=buffer8;
putst ("ATZ\n");
LED0=1;

leer_respuesta(ComandoRecibido8);
LED1=1;

if (strcmp(ComandoRecibido8,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED0=1;
LED1=1;
LED2=1;
LED3=1;

}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("ATZ\n");

leer_respuesta(ComandoRecibido8);

if (strcmp(ComandoRecibido8,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;

}
}
}


















// El otro dispositivo se quiere connectar con nosotros.

//Mensaje de aparejamiento : PAIR 0 008098E6A5F4 (19 caracteres) + 4 =23
ComandoRecibido9=buffer9;
//cgets(buffer9);
leer_palabra(buffer9,19);

if (strcmp(ComandoRecibido9,"PAIR 0 008098E6A5F4") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putst ("\n");  //cambio de linea
}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putst ("\n");  //cambio de linea

leer_palabra(buffer9,19);
//cgets(buffer9);
if (strcmp(ComandoRecibido9,"PAIR 0 008098E6A5F4") == 0){
error_comando=0;
putst ("respuesta correcta");
putst ("\n");  //cambio de linea
}
}
}




// Mensaje de llamada: RING 008098E6A5F4 (17 caracteres) +4 =21
ComandoRecibido10=buffer10; 
//cgets(buffer10);
leer_palabra(buffer10,17);
if (strcmp(ComandoRecibido10,"RING 008098E6A5F4") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putst ("\n");  //cambio de linea
}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putst ("\n");  //cambio de linea

//cgets(buffer10);
leer_palabra(buffer10,17);
if (strcmp(ComandoRecibido10,"RING 008098E6A5F4") == 0){
error_comando=0;
putst ("respuesta correcta");
putst ("\n");  //cambio de linea
}
}
}


// Mensaje de connexion establecida CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4
ComandoRecibido11=buffer11; 
//cgets(buffer11);
leer_palabra(buffer11,27);

if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putst ("\n");  //cambio de linea
}
else{                                    // No es el comando bueno
    error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putst ("\n");  //cambio de linea

leer_palabra(buffer11,27);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){
error_comando=0;
putst ("respuesta correcta");
putst ("\n");  //cambio de linea
}
}
}

*/


while(error_comando==1){

time_delay(10000000);
CS = 0;
    byte_alto = read_spi();
    byte_bajo = read_spi();
    CS = 1;
    valor_sensor_temperatura = (byte_alto << 8) + byte_bajo;
    valor_sensor_temperatura = valor_sensor_temperatura >> 7;
    valor_potenciometro = read_adc();
    valor_pote_en_texto = itoa (pote_buf, valor_potenciometro, 10);
    valor_sensor_en_texto = itoa (sensor_buf, valor_sensor_temperatura, 10);
    output_logic();
    future_state_logic();


}


}


 
/* =================================================================================
Function definitions
  ================================================================================= */
 
//*****************************************************************************
//Future_state_logic routine
//*****************************************************************************
char future_state_logic(void)
{
  char error = 0;
  switch (present_state)
  {
    case Idle_Low:
                 
                  if ((valor_sensor_temperatura < 10) || (valor_potenciometro < 200))
                  {
                    present_state = Idle_High;
                  }
                  else
                  if (getch_available() == true) //Si hay un caracter disponible recibido por el puerto serie
                  {
                    caracter_recibido = getch();
                    if (caracter_recibido == 'a')
                    {
present_state = Idle_High;
                    LED0 = 1;
LED1 = 1;
LED2 = 1;
LED3 = 1;
                    error = 0;
                    }
                    else
                    {
                      present_state = Idle_Low;
                    LED0 = 1;
LED1 = 1;
LED2 = 1;
LED3 = 1;
                    error = 1;
                    }
                  }
                  break;
    case Idle_High:
                   if (TXIF == 0) // Buffer de transmision vacio
                   {
                     present_state = Idle_Low;
                   }
                   else
                  {
                     error = 1; // Ojo, esto antes estaba y estaba funcionando
present_state=Idle_High;
                   }
                   break;
    default:
  error = 1;
  }
  return (error);
}
 
//*****************************************************************************
//Output logic routine
//*****************************************************************************
char output_logic(void)
{
  unsigned char error = 1;
  switch (present_state)
  {
    case Idle_Low:
                    LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;

                   error = 0;
                   break;
    case Idle_High:
                   putst ("\n");  //cambio de linea
   putst ("Valor del pot: ");
                   putst (valor_pote_en_texto);
                   putst ("\n");  //cambio de linea
                   putst ("Valor del sensor: ");
                  putst (valor_sensor_en_texto);
                   putst ("\n");
                    LED0 = 1;
LED1 = 1;
LED2 = 1;
LED3 = 1;
                   error = 0;
                   break;
    default:
                   error = 1;
                   

                   break;
  }
  return (error);
}
 
//*****************************************************************************
//Init operations 
//*****************************************************************************
void init_system (void)
{
  TRISA = 255;
  CS = 1;
  TRISB = 1; // SDI. El bit 0 a 1.Configurado en master mode (bit 1 cleared, en mode slave bit 1 set)
  TRISC = 192; // SDO. Tots els bits a 1 menys la sortida 7
  TRISD=0;
}

 
//*****************************************************************************
//Time delay routine.   
//*****************************************************************************
void time_delay(unsigned int delay)
{
  unsigned int i;

  for (i = 0; i <= delay; i++)
  {
    NOP();
  }
}
//*****************************************************************************
// SERIAL SETUP 
//*****************************************************************************
void serial_setup(void)
{
  #define SPBRG_VALUE ((PIC_CLK/(16UL*BAUD)) -1)
  BRGH = 1;
  BRG16 = 0;
  SPBRG = SPBRG_VALUE;
  SPEN = 1; // Enable serial port
  SYNC = 0; // Asincrono
  TXIE = 0; // Desactivar interrupciones en tx
  TXEN = 1; // Enable the transmitter
  TX9 = 0; // 8 bits transmission
  RCIE = 1; // Activar interrupciones en rx
  RX9 = 0; // 8 bits reception
  CREN = 1; //Enable reception
  #define clear_usart_errors_inline if (OERR)\
                                    {\
                                     TXEN = 0;\
                                      TXEN = 1;\
                                      CREN = 0;\
                                      CREN = 1;\
                                    }\
                                    if (FERR)\
                                    {\
                                      dummy = RCREG;\
                                     TXEN = 0;\
                                      TXEN = 1;\
                                    }
}


//*****************************************************************************
// Enviar datos ( un caracter)
//*****************************************************************************

void putch(unsigned char c)
{
  while (!TXIF)
  {
   // clear_usart_errors_inline;
    CLRWDT();
  }
  TXREG = c;
}
//*****************************************************************************
// Enviar datos (un buffer)
//*****************************************************************************
void putst(register const char *str)
{
  while ((*str) != 0)
  {
    putch (*str);
   if (*str == 13) putch (10);
    if (*str == 10) putch (13);
    str++;
  }
}

//*****************************************************************************
//Leer datos ( un caracter)
//*****************************************************************************
 /*
unsigned char getch(void)
{

while (RCIF != 1) //
  { //1 = The EUSART receive buffer, RCREG, is full
clear_usart_errors_inline;
CLRWDT();
  }

return RCREG;
}
*/

//*****************************************************************************
//Leer datos (un buffer)
//*****************************************************************************

unsigned char UsartReadChar_nonstop(void)
{
  if (!RCIF) // TRMT1 is set when TSR is empty //
    return 0;   
  return RCREG;
}



 
//*****************************************************************************
//Comprueba si aun faltan datos o no
//*****************************************************************************
unsigned char getch_available(void)
{
  if (RCIF)
    return true;
  else
    return false;
}

//*****************************************************************************
//Errores USART
//*****************************************************************************
void clear_usart_errors(void)
{
  clear_usart_errors_inline;
}

//*****************************************************************************
//Leer entradas.
//*****************************************************************************

//*****************************************************************************
//Leer bytes recibidos del bus del modulo SPI
//*****************************************************************************
 
void setup_sensor(void)  // SPI Master mode:
{
  SSPEN = 1; //Enables serial port and configures SCK, SDO, SDI and SS as serial port pins
  BF = 0;        //Receive not complete, SSPBUF is empty
  //SCK is the clock output (Master Mode)
  //Clock Polarity(Idle state of SCK)
  SMP = 0;      //Input data sampled at end of data output time
  CKE = 0;      //Transmit occurs on transition from Idle to active clock state
  SSPM3 = 0;
  SSPM2 = 0; //SPI Master mode, clock = FOSC/4
  SSPM1 = 0;
 SSPM0 = 0;
  CKP = 0; //Idle state for clock is a low level
  SSPIF = 0;   
}
 
void setup_adc(void)
{
  ADFM = 1;
  ADCON1 = 14; // PCFG3=1,PCFG2=1,PCFG1=1,PCFG0=0. Todas las entradas digitales
  CHS3 = 0;
  CHS2 = 0; // Seleccionamos el canal 0 (AN0) que es donde esta conectado el potenciometro
  CHS1 = 0;
  CHS0 = 0;
  //Tiempo de adquisicion
  ACQT2 = 0;
  ACQT1 = 1;  //Por tanto 2x1us =2us >= 1.65us( Tacq calculado teoricamente)
  ACQT0 = 0;
 
  ADCS2 = 1;
  ADCS1 = 0;    // valor que hace que sea superior a 0.7us( el minimo)
  ADCS0 = 0;
 
  ADON = 1; // A/D converter module is enabled
  /* Configure A/D interrupt*/
  ADIF = 0;
 
}
 
//*****************************************************************************
//Leer entradas.
//*****************************************************************************
 
//*****************************************************************************
//LEER DATOS SENSOR
//*****************************************************************************
unsigned char read_spi (void)
{
  TRISC7 = 1; // así pongo en alta impedancia el pin SDO
  SSPBUF = 16;
  while (SSPIF == 0);
  SSPIF = 0;
  return SSPBUF;
}
 
//*****************************************************************************
//LEER DATOS POTENCIOMETRO
//*****************************************************************************
unsigned int read_adc(void)
{
  //Empezar a leer
  GODONE = 1; // A/D conversion in progress
  while (GODONE == 1);
  ADIF = 0;
  return ((ADRESH << 8) + (ADRESL));
}
 
 
//*****************************************************************************
//FUNCION GETCHE ( SE USA EN LA FUNCION CGETS)
//*****************************************************************************
/*
unsigned char getche (void)
{
    while (RCIF != 1)
    {
clear_usart_errors_inline;
       CLRWDT();
    }
    return RCREG;
}
*/


void LeerRespuesta(char *mensaje) // Recibimos \n \r O K \n \r por lo tanto 6 caracteres.
{
int indice=0;
int cont=0;

while(indice<1){
*mensaje=getch();
*mensaje++;
indice++;
}

}



/*
void SacarCaracteres (char buffer_todos_caracteres) //Sacamos los caracteres recibidos en falso
{
int i=0;
char buffer_caracteres[7];


while(i<8){
if(buffer_todos_caracteres[i]=='O'){
buffer_caracteres[0]=buffer_todos_caracteres[i];
}
else if (buffer_todos_caracteres[i]=='K')
buffer_caracteres[1]=buffer_todos_caracteres[i];

else
buffer_caracteres[i]=buffer_todos_caracteres[i];

i++;


}

*/



char getch()
{
int cont=0;
int cont1=0;
int cont2=0;
 
while (RCIF == 0)
  {
    if (OERR == 1)
    {
    cont1++; 
if (TXEN == 1)
      {
        TXEN=0;
        TXEN=1;
      }
      if (CREN == 1)
      {
        CREN=0;
        CREN=1;
      }
    }
 
    if (FERR == 1)
    {
      cont++;
dummy = RCREG;
      if (TXEN == 1)
      {
        TXEN=0;
       TXEN=1;
      }
    }
    CLRWDT();
 
if(cont==0)
LED3=1;
else
LED3=0;

if(cont1==0)
LED2=1;
else
LED2=0;
  }
  cont2++;
if(cont2==1)
LED0=1;
else
LED0=0;
return RCREG;
}





Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #133 en: 20 de Enero de 2011, 12:41:52 »
El segundo caracter es una T!! estoy recibiendo AT!! como puede ser eso? ( eso con indice <2)

Si subo el indice a < 3 los dos primeros los lee y el tercer caracter hace que entre en el while. VAAA QUE LO TENEEEMOS!

Estoy alucinando. Lo tenia funcionando y he cambiado el OK del AT del strcmp para que entrase y si lo cambio no funciona. Esta ligado el strcmp con el getch?

EDITO OTRA VEZ: CONCLUSION: el sistema no es robusto, a veces se mete en el while y a veces no. No debe enviar lo mismo cada vez.

Ayudaaa por faaavor!
« Última modificación: 20 de Enero de 2011, 12:53:02 por edu1989 »

Desconectado edu1989

  • PIC18
  • ****
  • Mensajes: 275
Re: Error al comparar dos strings con strcmp
« Respuesta #134 en: 20 de Enero de 2011, 12:56:34 »
Ahora he conseguido hacerlo entrarlo en el while. POR FIN!  Eso si, recibo AT y lo he comparado con AT.
Osea, todo lo que recibo ( recuerda que no utilitzo la funcion que coge el "OK") es AT.


Código: [Seleccionar]
while(error_comando==0){

time_delay(10000000);
CS = 0;
    byte_alto = read_spi();
    byte_bajo = read_spi();
    CS = 1;
    valor_sensor_temperatura = (byte_alto << 8) + byte_bajo;
    valor_sensor_temperatura = valor_sensor_temperatura >> 7;
    valor_potenciometro = read_adc();
    valor_pote_en_texto = itoa (pote_buf, valor_potenciometro, 10);
    valor_sensor_en_texto = itoa (sensor_buf, valor_sensor_temperatura, 10);
    output_logic();
    future_state_logic();


}


}


Código: [Seleccionar]

#include <htc.h>
#include <stdlib.h>  // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.h>


//#conio.h, e #iostream.h


 
__CONFIG (1, HS & CPUDIV4 & USBPLL & PLLDIV5 & FCMDIS & IESODIS); // Con 20 CPUDIV1
__CONFIG (2, BORDIS & WDTDIS & PWRTDIS);
__CONFIG (3, MCLRDIS); // estoy deshabilitando el pin de MasterClear, tal vez haya que habilitarlo, eso hay que probarlo
__CONFIG (4, LVPDIS &  DEBUGEN);
 
/* =================================================================================
Definitions
    ================================================================================= */
#define PORTBIT(adr, bit) ( (unsigned)(&adr)*8 + (bit) )
 
#define Idle_Low 1 // No envia datos
#define Idle_High 2 // Envia datos

#define true 1
#define false 0
 
#define BAUD  9600 // Configuramos la velocidad, tanto puede ser 19200 o de 9600 kbaud/s pero hay q cambiarlo tb en la simulacion de proteus
#define PIC_CLK      5000000
 
#define CS RB2

/* =================================================================================
Global variables 
  ================================================================================= */


static bit LED0 @ PORTBIT(PORTD, 0);
static bit LED1 @ PORTBIT(PORTD, 1);
static bit LED2 @ PORTBIT(PORTD, 2);
static bit LED3 @ PORTBIT(PORTD, 3);
char present_state = Idle_Low; // state variable
char future_state = Idle_Low; // state variable
unsigned int  valor_potenciometro;
unsigned int  valor_sensor_temperatura;
unsigned char pote_buf[6];
unsigned char sensor_buf[10];
char * valor_pote_en_texto;           // un puntero para almacenar el numero en texto
char * valor_sensor_en_texto;         // un puntero para almacenar el numero en texto
char byte_alto, byte_bajo;
unsigned char caracter_recibido;
unsigned char dummy;

int error_comando=1;
int error_connexion=1;
int comando_disponible=1; // No hay comando disponible
int final=1;
int prueba=1; // PRUEBA PARA SABER DONDE ESTO
char indice=0;



//CAMBIAR A 6 CON EL DISPOSITIVO
char buffer1[6];  // es 6
char * ComandoRecibido1; // este es el puntero y lo voy a usar para strcmp

char buffer2[6]; 
char * ComandoRecibido2;

char buffer3[6]; 
char * ComandoRecibido3;

char buffer4[6]; 
char * ComandoRecibido4;

char buffer5[6]; 
char * ComandoRecibido5;

char buffer6[6]; 
char * ComandoRecibido6;

char buffer7[6]; 
char * ComandoRecibido7;

char buffer8[6]; 
char * ComandoRecibido8;

char buffer9[100]; 
char * ComandoRecibido9;

char buffer10[100]; 
char * ComandoRecibido10;

char buffer11[100]; 
char * ComandoRecibido11;

int contador=0;

/* =================================================================================
Function prototypes
  ================================================================================= */
 
void init_system (void);
void time_delay (unsigned int );
char output_logic(void);
char future_state_logic(void);
 
void setup_sensor(void);
void setup_adc(void);
void serial_setup(void);
 
void putst(const char *str);
void putch(unsigned char c);

unsigned char getch(void);
unsigned char UsartReadChar_nonstop(void);
unsigned char getch_available(void);
unsigned char getche (void);
void clear_usart_errors(void);
 
unsigned char read_spi (void);
unsigned int read_adc(void);


char getch();
void LeerRespuesta(char *mensaje);
void SacarCaracteres (char buffer_todos_caracteres);


/* =================================================================================
Main function
  ================================================================================= */
 

 

void main ()
{
  //char buffer[2]; // aqui se almacena la respuesta
 
 
  //inicializar el puerto serie RS2326.
  valor_potenciometro = 0;
  valor_sensor_temperatura = 0;
  LED0 = 0;
  LED1 = 0;
  LED2 = 0;
  LED3 = 0;
 

  init_system();
  setup_sensor();
  setup_adc();
  serial_setup();


 
/* =================================================================================
Establecer connexion con comandos AT
  ================================================================================= */


//Primer comando AT

ComandoRecibido1=buffer1;

putst ("AT");
putch ('\r');

time_delay(999999999999);
LeerRespuesta (ComandoRecibido1);


if (strcmp(ComandoRecibido1,"AT") == 0){ // Todo a ido bien

error_comando=0;
//putst ("respuesta correcta");
//putch ('\r');

}
else{                                    // No es el comando bueno
   

error_comando=1;

while(error_comando==1){
//putst ("respuesta incorrecta");
//putch ('\r');
putst ("AT");
putch ('\r');
LeerRespuesta (ComandoRecibido1);

if (strcmp(ComandoRecibido1,"OK") == 0){

error_comando=0;
//putst ("respuesta correcta");
//putch ('\r');
}

}
}

Código: [Seleccionar]
char getch()
{
int cont=0;
int cont1=0;
int cont2=0;
 
while (RCIF == 0)
  {
    if (OERR == 1)
    {
    cont1++; 
if (TXEN == 1)
      {
        TXEN=0;
        TXEN=1;
      }
      if (CREN == 1)
      {
        CREN=0;
        CREN=1;
      }
    }
 
    if (FERR == 1)
    {
      cont++;
dummy = RCREG;
      if (TXEN == 1)
      {
        TXEN=0;
       TXEN=1;
      }
    }
    CLRWDT();
 
if(cont==0)
LED3=1;
else
LED3=0;

if(cont1==0)
LED2=1;
else
LED2=0;
  }
  cont2++;
if(cont2==1)
LED0=1;
else
LED0=0;
return RCREG;
}