//Primer comando AT
putst ("AT/n");
if (getch_available() == true) //Comprueba si hay un caracter disponible recibido por el puerto serie
{
comando_recibido1 = getch(); // Lee el caracter ( tendria que recibir un "OK")
//Comprovar que reciba "OK"
while (strcmp(comando_recibido1, comando_recibido_ideal)== 1 ){ // Son distintos
error_comando=1;
}
if(strcmp(comando_recibido1, comando_recibido_ideal) == 0 ) // Son iguales
error_comando=0;
}
const char * comando_recibido_ideal[]="OK";
const char * comando_recibido1[2]; // Es 2 porque espero recibir un OK
//Primer comando AT
putst ("AT/n");
//Comprovar que reciba "OK"
while (getch_available() != false){ //Si hay un caracter disponible recibido por el puerto serie
if(getch_available()==true)
{
//comando_recibido1 = UsartReadChar_nonstop();
cgets(comando_recibido1);
while (strcmp(comando_recibido1,"OK")== 1 ) // Son distintos
error_comando=1;
if(strcmp(comando_recibido1,"OK") == 0 ) // Son iguales
error_comando=0;
}
}
char comando_recibido1[2];
...........
Que te parece? Como puedes ver utilitzo una funcion nueva que sirve para leer una linea entrante en el terminal.
Muchas gracias.
Código: [Seleccionar].....
while (strcmp(comando_recibido1,"OK")== 1 ) // Son distintos
error_comando=1;
if(strcmp(comando_recibido1,"OK") == 0 ) // Son iguales
error_comando=0;
.....
//Comprovar que reciba "OK"
while (getch_available() != false){ //Si hay un caracter disponible recibido por el puerto serie
if(getch_available()==true)
{
//comando_recibido1 = UsartReadChar_nonstop();
cgets(comando_recibido1);
Gracias. Tienes razon.
Por lo que respecta a la funcion cgets, te parece que lo hago bien?Código: [Seleccionar]//Comprovar que reciba "OK"
while (getch_available() != false){ //Si hay un caracter disponible recibido por el puerto serie
if(getch_available()==true)
{
//comando_recibido1 = UsartReadChar_nonstop();
cgets(comando_recibido1);
La funcion UsartReadChar_nonstop es la que implemente en el codigo pasado.
Antes me salian errores en la lectura, q te parece?
Gracias de antemano
Y con la funcion UsartReadChar_nonstop?
Ahora subire la implementacion de la funcion cgets.
Gracias de antemano
#include <conio.h>
#include <string.h>
char buffer[80];
void
main (void)
{
for(;;) {
cgets(buffer);
if(strcmp(buffer, "exit") == 0)
break;
cputs("Type ’exit’ to finish\n");
}
}
The cgets() function will read one line of input from the console into the buffer passed as an argument.
It does so by repeated calls to getche(). As characters are read, they are buffered, with
backspace deleting the previously typed character, and ctrl-U deleting the entire line typed so far.
Other characters are placed in the buffer, with a carriage return or line feed (newline) terminating
the function. The collected string is null terminated.
unsigned char UsartReadChar_nonstop(void)
{
if (!RCIF) // TRMT1 is set when TSR is empty
return 0;
return RCREG;
}
All commands are terminated by the carriage return character 0x0d, which is represented by the string <cr> in descriptions below this cannot be changed
All responses from the EZURiO device have carriage return and linefeed characters preceding and appending the response. These dual character sequences have the values 0x0D and 0x0A respectively and shall be represented by the string <cr,lf>.
Hola de nuevo
Me tira un error en la linia:
if (strcmp(&comando_recibido1,&comando_recibido_ideal)== 0 )
Tanto si lo pongo asi como si lo pongo:
if (strcmp(&comando_recibido1,"OK")== 0 )
En los dos casos: conflicting declarations for variable
Por otro lado, creo que la funcion cgets funcionara mejor que la otra despues de leer que el dispositivo devolvia las instrucciones con retorno de carro.
Voy a seguir trabajando
Gracias
char Palabra2[2];
const char * ComandoIdeal = "OK";
char * ComandoRecibido;
char resultado = 10;
//Primer comando AT
putst ("AT/n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ //Si hay un caracter disponible recibido por el puerto serie
LED0=0;
LED1=0;
LED2=1;
LED3=1;
if(getch_available()==true)
{
ComandoRecibido = Palabra2;
//cgets(ComandoRecibido);
resultado = strcmp (ComandoIdeal, ComandoRecibido);
if(resultado==0){ // Iguales
error_comando=0;
LED2=0;
LED3=0;
}
else
error_comando=1;
LED2=0;
LED3=0;
}
}
void getsUSART(unsigned char * buffer,unsigned char length );
Return Value: None
Remarks: This function only works in 8-bit transmit/receive mode. This function waits
for and reads len number of characters out of the specified USART. There is
no time out when waiting for characters to arrive. getsUSART should be used
on parts with a single USART peripheral. gets1USART and gets2USART
should be used on parts with multiple USART peripherals.
Filename: ugets.c
Code Example: char string[10];
getsUSART(string, 5);
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <conio.h>
#include <string.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);
/* =================================================================================
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;
char buffer[10]; // esto es lo que va para cgets
char * ComandoRecibido; // este es el puntero y lo voy a usar para strcmp
char resultado;
//ComandoRecibido = buffer;
/* =================================================================================
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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
ComandoRecibido = buffer;
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("AT/n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
resultado = strcmp (ComandoRecibido, "OK");
if(resultado==0){ // Iguales
error_comando=0;
}
else
error_comando=1;
}
}
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.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);
/* =================================================================================
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;
char buffer[10]; // esto es lo que va para cgets
char * ComandoRecibido; // este es el puntero y lo voy a usar para strcmp
char resultado;
/* =================================================================================
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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
ComandoRecibido = buffer;
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("AT\n");
LED0=1;
LED1=1;
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
/*
//Segundo comando AT
if (error_comando==0)
{
error_comando=1;
putst ("ATS0=1\n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
}
//Tercer comando AT
if (error_comando==0)
{
error_comando=1;
putst ("ATS512=4\n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
}
//Quarto comando AT
if (error_comando==0)
{
error_comando=1;
putst ("ATS502=1/n");
LED0=1;
LED1=1;
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
}
//Quinto comando AT
if (error_comando==0)
{
error_comando=1;
putst ("ATS536=1/n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
}
//Sexto comando AT
if (error_comando==0)
{
error_comando=1;
putst ("AT+BTK=1234/n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
}
//Septimo comando AT
if (error_comando==0)
{
error_comando=1;
putst ("AT&W/n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
}
//Octavo comando AT
if (error_comando==0)
{
error_comando=1;
putst ("ATZ/n");
LED0=1;
LED1=1;
//Comprovar que reciba "OK"
while (getch_available() != false){ // Este while hay que ponerlo? Puede ser que haya un pequeño tiempo donde aun no haya recibido el caracer?
if(getch_available()==true)
{
LED0=0;
LED1=0;
LED2=1;
LED3=1;
cgets(buffer);
if (strcmp(ComandoRecibido,"OK") == 0)
error_comando=0;
else
error_comando=1;
}
}
*/
/*
// El otro dispositivo se quiere connectar con nosotros
// Mensaje de aparejamiento : PAIR 0 008098E6A5F4 (19 caracteres)
if((getch_available()==true)&&(error_comando==0))
{
cgets(Palabra1_real);
resultado = strcmp (Palabra1_ideal, Palabra1_real);
if(resultado==0)
error_comando=0;
else
error_comando=1;
}
}
// Mensaje de llamada: RING 008098E6A5F4 (17 caracteres)
if((getch_available()==true)&&(error_comando==0))
{
cgets(Palabra2_real);
resultado = strcmp (Palabra2_ideal, Palabra2_real);
if(resultado==0)
error_comando=0;
else
error_comando=1;
}
}
// Mensaje de connexion: CONNECT 008098E6A5F4,1101 A (27 caracteres)
if((getch_available()==true)&&(error_comando==0))
{
cgets(Palabra3_real);
resultado = strcmp (Palabra3_ideal, Palabra3_real);
if(resultado==0)
error_comando=0;
else
error_comando=1;
}
}
*/
init_system();
setup_sensor();
setup_adc();
serial_setup();
while(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();
//time_delay(1000000000);
}
}
/* =================================================================================
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
CLRWDT();
clear_usart_errors_inline;
}
return RCREG;
}
//*****************************************************************************
//Leer datos (un buffer)
//*****************************************************************************
unsigned char UsartReadChar_nonstop(void)
{
if (!RCIF) // TRMT1 is set when TSR is empty // Cuando no es RCIF, cuando no es 1
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_error;
clear_usart_errors_inline;
CLRWDT();
}
return RCREG;
}
Hay que volver a inicializar el uart? Antes de hacer ese cambio ya estaba inicializado con la funcion serial_setup y en la funcion de inicializacion habia el TRISC correspondiente.
Ya me diras algo
Muchas gracias.
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.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);
/* =================================================================================
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 ESTOY.
char buffer1[10]; // esto es lo que va para cgets
char * ComandoRecibido1; // este es el puntero y lo voy a usar para strcmp
char buffer2[10];
char * ComandoRecibido2;
char buffer3[10];
char * ComandoRecibido3;
char buffer4[10];
char * ComandoRecibido4;
char buffer5[10];
char * ComandoRecibido5;
char buffer6[10];
char * ComandoRecibido6;
char buffer7[10];
char * ComandoRecibido7;
char buffer8[10];
char * ComandoRecibido8;
char buffer9[100];
char * ComandoRecibido9;
char buffer10[100];
char * ComandoRecibido10;
char buffer11[100];
char * ComandoRecibido11;
/* =================================================================================
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);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
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\n");
LED0=0;
//if(getch_available()==true){
if(prueba==1) // Prueba para saber si llega hasta aqui.
LED1=1;
else
LED2=1;
cgets(buffer1);
LED1=1;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("AT\n");
cgets(buffer1);
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Segundo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido2=buffer2;
putst ("ATS0=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer2);
if (strcmp(ComandoRecibido2,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS0=1\n");
cgets(buffer2);
if (strcmp(ComandoRecibido2,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Tercer comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido3=buffer3;
putst ("ATS512=4\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer3);
if (strcmp(ComandoRecibido3,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS512=4\n");
cgets(buffer3);
if (strcmp(ComandoRecibido3,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quarto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido4=buffer4;
putst ("ATS502=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer4);
if (strcmp(ComandoRecibido4,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS502=1\n");
cgets(buffer4);
if (strcmp(ComandoRecibido4,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quinto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido5=buffer5;
putst ("ATS536=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer5);
if (strcmp(ComandoRecibido5,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS536=1\n");
cgets(buffer5);
if (strcmp(ComandoRecibido5,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Sexto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido6=buffer6;
putst ("AT+BTK=1234\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer6);
if (strcmp(ComandoRecibido6,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT+BTK=1234\n");
cgets(buffer6);
if (strcmp(ComandoRecibido6,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Septimo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido7=buffer7;
putst ("AT&W\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer7);
if (strcmp(ComandoRecibido7,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT&W\n");
cgets(buffer7);
if (strcmp(ComandoRecibido7,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Octavo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido8=buffer8;
putst ("ATZ\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer8);
if (strcmp(ComandoRecibido8,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATZ\n");
cgets(buffer8);
if (strcmp(ComandoRecibido8,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
// El otro dispositivo se quiere connectar con nosotros.
//Mensaje de aparejamiento : PAIR 0 008098E6A5F4 (19 caracteres)
ComandoRecibido9=buffer9;
cgets(buffer9);
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
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)
ComandoRecibido10=buffer10;
cgets(buffer10);
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);
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
ComandoRecibido11=buffer11;
cgets(buffer11);
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
cgets(buffer11);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){
error_comando=0;
putst ("respuesta correcta");
putst ("\n"); //cambio de linea
}
}
}
while(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();
//time_delay(1000000000);
}
}
/* =================================================================================
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
CLRWDT();
clear_usart_errors_inline;
}
return RCREG;
}
//*****************************************************************************
//Leer datos (un buffer)
//*****************************************************************************
unsigned char UsartReadChar_nonstop(void)
{
if (!RCIF) // TRMT1 is set when TSR is empty // Cuando no es RCIF, cuando no es 1
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;
}
En principio cual crees que podria ser el error?
Ahora miro de crear una funcion.. Esta funcion tiene que hacer 6 llamadas a la getchar y almacenar cada caracter en una variable no? tendre que ir cogiendo cada caracter del buffer no?
Edito: tambien podria hacer un while no?
Edito1: El problema esta en que el programa no avanza de la sentencia cgets.. entonces no podre leerlo..
Es eso lo que me extraña, que no siga aunque lo haga mal
//Primer comando AT
ComandoRecibido1=buffer1;
putst ("AT\n");
LED0=0;
do
{
buffer1[indice]=getch();
indice++;
}
while(indice < 6);
//cgets(buffer1);
LED1=1;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("AT\n");
cgets(buffer1);
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.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);
/* =================================================================================
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;
char buffer1[100]; // esto es lo que va para cgets
char * ComandoRecibido1; // este es el puntero y lo voy a usar para strcmp
char buffer2[10];
char * ComandoRecibido2;
char buffer3[10];
char * ComandoRecibido3;
char buffer4[10];
char * ComandoRecibido4;
char buffer5[10];
char * ComandoRecibido5;
char buffer6[10];
char * ComandoRecibido6;
char buffer7[10];
char * ComandoRecibido7;
char buffer8[10];
char * ComandoRecibido8;
char buffer9[100];
char * ComandoRecibido9;
char buffer10[100];
char * ComandoRecibido10;
char buffer11[100];
char * ComandoRecibido11;
/* =================================================================================
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);
unsigned leer_palabra(char * buffer);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
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\n");
LED0=0;
leer_palabra(buffer1);
//cgets(buffer1);
LED1=1;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("AT\n");
leer_palabra(buffer1);
//cgets(buffer1);
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Segundo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido2=buffer2;
putst ("ATS0=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer2);
if (strcmp(ComandoRecibido2,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS0=1\n");
cgets(buffer2);
if (strcmp(ComandoRecibido2,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Tercer comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido3=buffer3;
putst ("ATS512=4\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer3);
if (strcmp(ComandoRecibido3,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS512=4\n");
cgets(buffer3);
if (strcmp(ComandoRecibido3,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quarto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido4=buffer4;
putst ("ATS502=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer4);
if (strcmp(ComandoRecibido4,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS502=1\n");
cgets(buffer4);
if (strcmp(ComandoRecibido4,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quinto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido5=buffer5;
putst ("ATS536=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer5);
if (strcmp(ComandoRecibido5,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS536=1\n");
cgets(buffer5);
if (strcmp(ComandoRecibido5,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Sexto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido6=buffer6;
putst ("AT+BTK=1234\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer6);
if (strcmp(ComandoRecibido6,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT+BTK=1234\n");
cgets(buffer6);
if (strcmp(ComandoRecibido6,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Septimo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido7=buffer7;
putst ("AT&W\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer7);
if (strcmp(ComandoRecibido7,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT&W\n");
cgets(buffer7);
if (strcmp(ComandoRecibido7,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Octavo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido8=buffer8;
putst ("ATZ\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer8);
if (strcmp(ComandoRecibido8,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATZ\n");
cgets(buffer8);
if (strcmp(ComandoRecibido8,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
// El otro dispositivo se quiere connectar con nosotros.
//Mensaje de aparejamiento : PAIR 0 008098E6A5F4 (19 caracteres)
ComandoRecibido9=buffer9;
cgets(buffer9);
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
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)
ComandoRecibido10=buffer10;
cgets(buffer10);
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);
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
ComandoRecibido11=buffer11;
cgets(buffer11);
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
cgets(buffer11);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){
error_comando=0;
putst ("respuesta correcta");
putst ("\n"); //cambio de linea
}
}
}
while(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();
//time_delay(1000000000);
}
}
/* =================================================================================
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
CLRWDT();
clear_usart_errors_inline;
}
return RCREG;
}
//*****************************************************************************
//Leer datos (un buffer)
//*****************************************************************************
unsigned char UsartReadChar_nonstop(void)
{
if (!RCIF) // TRMT1 is set when TSR is empty // Cuando no es RCIF, cuando no es 1
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;
}
unsigned leer_palabra(char * buffer)
{
do
{
buffer[indice]=getch();
indice++;
}
while(indice < 2);
return 0;
}
..........Código: [Seleccionar]
..........
unsigned leer_palabra(char * buffer)
{
do
{
buffer[indice]=getch();
indice++;
}
while(indice < 2);
return 0;
}
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.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);
/* =================================================================================
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;
char buffer1[100]; // esto es lo que va para cgets
char * ComandoRecibido1; // este es el puntero y lo voy a usar para strcmp
char buffer2[10];
char * ComandoRecibido2;
char buffer3[10];
char * ComandoRecibido3;
char buffer4[10];
char * ComandoRecibido4;
char buffer5[10];
char * ComandoRecibido5;
char buffer6[10];
char * ComandoRecibido6;
char buffer7[10];
char * ComandoRecibido7;
char buffer8[10];
char * ComandoRecibido8;
char buffer9[100];
char * ComandoRecibido9;
char buffer10[100];
char * ComandoRecibido10;
char buffer11[100];
char * ComandoRecibido11;
/* =================================================================================
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);
unsigned leer_palabra(char * buffer);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
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\n");
LED0=0;
leer_palabra(buffer1);
LED1=1;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putst ("\n"); //cambio de linea
LED0=1;
LED1=1;
LED2=1;
LED3=1;
}
else{ // No es el comando bueno
error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putst ("\n"); //cambio de linea
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("AT\n");
leer_palabra(buffer1);
//cgets(buffer1);
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Segundo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido2=buffer2;
putst ("ATS0=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer2);
if (strcmp(ComandoRecibido2,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS0=1\n");
cgets(buffer2);
if (strcmp(ComandoRecibido2,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Tercer comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido3=buffer3;
putst ("ATS512=4\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer3);
if (strcmp(ComandoRecibido3,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS512=4\n");
cgets(buffer3);
if (strcmp(ComandoRecibido3,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quarto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido4=buffer4;
putst ("ATS502=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer4);
if (strcmp(ComandoRecibido4,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS502=1\n");
cgets(buffer4);
if (strcmp(ComandoRecibido4,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quinto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido5=buffer5;
putst ("ATS536=1\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer5);
if (strcmp(ComandoRecibido5,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS536=1\n");
cgets(buffer5);
if (strcmp(ComandoRecibido5,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Sexto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido6=buffer6;
putst ("AT+BTK=1234\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer6);
if (strcmp(ComandoRecibido6,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT+BTK=1234\n");
cgets(buffer6);
if (strcmp(ComandoRecibido6,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Septimo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido7=buffer7;
putst ("AT&W\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer7);
if (strcmp(ComandoRecibido7,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT&W\n");
cgets(buffer7);
if (strcmp(ComandoRecibido7,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Octavo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido8=buffer8;
putst ("ATZ\n");
LED0=1;
//if(getch_available()==true)
cgets(buffer8);
if (strcmp(ComandoRecibido8,"OK") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATZ\n");
cgets(buffer8);
if (strcmp(ComandoRecibido8,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
// El otro dispositivo se quiere connectar con nosotros.
//Mensaje de aparejamiento : PAIR 0 008098E6A5F4 (19 caracteres)
ComandoRecibido9=buffer9;
cgets(buffer9);
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
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)
ComandoRecibido10=buffer10;
cgets(buffer10);
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);
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
ComandoRecibido11=buffer11;
cgets(buffer11);
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
cgets(buffer11);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){
error_comando=0;
putst ("respuesta correcta");
putst ("\n"); //cambio de linea
}
}
}
while(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();
//time_delay(1000000000);
}
}
/* =================================================================================
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
CLRWDT();
clear_usart_errors_inline;
}
return RCREG;
}
//*****************************************************************************
//Leer datos (un buffer)
//*****************************************************************************
unsigned char UsartReadChar_nonstop(void)
{
if (!RCIF) // TRMT1 is set when TSR is empty // Cuando no es RCIF, cuando no es 1
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;
}
unsigned leer_palabra(char * buffer)
{
do
{
buffer[indice]=getch();
indice++;
}
while(indice < 10);
return 0;
}
Código: [Seleccionar]All responses from the EZURiO device have carriage return and linefeed characters preceding and appending the response. These dual character sequences have the values 0x0D and 0x0A respectively and shall be represented by the string <cr,lf>.
Si pongo el buffer y el indice a 3 y en el terminal pongo OK + enter
En la condicion pongo OK\r y funciona!!
Lo que no funciona es que si fallo y pongo ok por ejemplo, pone respuesta incorrecta y solo me deja poner un caracter... sabes que puede ser?
Muchas gracias por la ayuda amigo. Te dejo q me contestes estas preguntas que sino voy demasiado rapido jej
Gracias
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.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);
/* =================================================================================
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[3]; // esto es lo que va para cgets.
char * ComandoRecibido1; // este es el puntero y lo voy a usar para strcmp
char buffer2[3];
char * ComandoRecibido2;
char buffer3[3];
char * ComandoRecibido3;
char buffer4[3];
char * ComandoRecibido4;
char buffer5[3];
char * ComandoRecibido5;
char buffer6[3];
char * ComandoRecibido6;
char buffer7[3];
char * ComandoRecibido7;
char buffer8[3];
char * ComandoRecibido8;
char buffer9[100];
char * ComandoRecibido9;
char buffer10[100];
char * ComandoRecibido10;
char buffer11[100];
char * ComandoRecibido11;
/* =================================================================================
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);
unsigned leer_palabra(char * buffer);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
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\n");
LED0=1;
leer_palabra(buffer1);
LED1=1;
if (strcmp(ComandoRecibido1,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putst ("\n"); //cambio de linea
LED0=1;
LED1=1;
LED2=1;
LED3=1;
}
else{ // No es el comando bueno
error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putst ("\n"); //cambio de linea
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("AT\n");
//leer_palabra(buffer1);
cgets(buffer1);
LED0=1;
LED1=1;
LED2=1;
LED3=1;
if (strcmp(ComandoRecibido1,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Segundo comando AT
ComandoRecibido2=buffer2;
putst ("ATS0=1\n");
LED0=1;
leer_palabra(buffer2);
LED1=1;
if (strcmp(ComandoRecibido2,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
putst ("\n"); //cambio de linea
LED0=1;
LED1=1;
LED2=1;
LED3=1;
}
else{ // No es el comando bueno
error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putst ("\n"); //cambio de linea
LED0=0;
LED1=0;
LED2=0;
LED3=0;
putst ("ATS0=1\n");
leer_palabra(buffer2);
//cgets(buffer1);
if (strcmp(ComandoRecibido2,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
*/
//Tercer comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido3=buffer3;
putst ("ATS512=4\n");
LED0=1;
//if(getch_available()==true)
//cgets(buffer3);
leer_palabra(buffer3);
if (strcmp(ComandoRecibido3,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS512=4\n");
//cgets(buffer3);
leer_palabra(buffer3);
if (strcmp(ComandoRecibido3,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quarto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido4=buffer4;
putst ("ATS502=1\n");
LED0=1;
//if(getch_available()==true)
//cgets(buffer3);
leer_palabra(buffer4);
if (strcmp(ComandoRecibido4,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS502=1\n");
//cgets(buffer3);
leer_palabra(buffer4);
if (strcmp(ComandoRecibido4,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Quinto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido5=buffer5;
putst ("ATS536=1\n");
LED0=1;
//if(getch_available()==true)
//cgets(buffer5);
leer_palabra(buffer5);
if (strcmp(ComandoRecibido5,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATS536=1\n");
//cgets(buffer5);
leer_palabra(buffer5);
if (strcmp(ComandoRecibido5,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Sexto comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido6=buffer6;
putst ("AT+BTK=1234\n");
LED0=1;
//if(getch_available()==true)
leer_palabra(buffer6);
//cgets(buffer6);
if (strcmp(ComandoRecibido6,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT+BTK=1234\n");
//cgets(buffer6);
leer_palabra(buffer6);
if (strcmp(ComandoRecibido6,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Septimo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido7=buffer7;
putst ("AT&W\n");
LED0=1;
//if(getch_available()==true)
//cgets(buffer7);
leer_palabra(buffer7);
if (strcmp(ComandoRecibido7,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("AT&W\n");
//cgets(buffer7);
leer_palabra(buffer7);
if (strcmp(ComandoRecibido7,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
//Octavo comando AT
LED0=0;
LED1=0;
LED2=0;
LED3=0;
ComandoRecibido8=buffer8;
putst ("ATZ\n");
LED0=1;
//if(getch_available()==true)
leer_palabra(buffer8);
//cgets(buffer8);
if (strcmp(ComandoRecibido8,"OK\r") == 0){ // Todo a ido bien
error_comando=0;
putst ("respuesta correcta");
LED0=1;
LED1=1;
LED2=1;
LED3=1;
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
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
putst ("ATZ\n");
//cgets(buffer8);
leer_palabra(buffer8);
if (strcmp(ComandoRecibido8,"OK\r") == 0){
error_comando=0;
putst ("respuesta correcta");
LED3=1;
putst ("\n"); //cambio de linea
}
}
}
/*
// El otro dispositivo se quiere connectar con nosotros.
//Mensaje de aparejamiento : PAIR 0 008098E6A5F4 (19 caracteres+4)
ComandoRecibido9=buffer9;
cgets(buffer9);
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
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)
ComandoRecibido10=buffer10;
cgets(buffer10);
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);
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
ComandoRecibido11=buffer11;
cgets(buffer11);
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
cgets(buffer11);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){
error_comando=0;
putst ("respuesta correcta");
putst ("\n"); //cambio de linea
}
}
}
*/
while(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();
//time_delay(1000000000);
}
}
/* =================================================================================
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
CLRWDT();
clear_usart_errors_inline;
}
return RCREG;
}
//*****************************************************************************
//Leer datos (un buffer)
//*****************************************************************************
unsigned char UsartReadChar_nonstop(void)
{
if (!RCIF) // TRMT1 is set when TSR is empty // Cuando no es RCIF, cuando no es 1
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;
}
unsigned leer_palabra(char * buffer)
{
indice = 0;
do
{
buffer[indice]=getch();
indice++;
}
while(indice < 3); // Cambiar a 6 para el dispositivo
return 0;
}
Acabo de grabarlo al PIC y sigue sin funcionar... nunca ejecuta mas alla del leer_respuesta(buffer1). Estoy "debugando" a partir de los LEDS y se me encienden los dos primeros ( que los hago encender antes de esta sentencia). Despues de esta enciendo otro que ya no va...
La verdad es que no se que hacer...
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.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);
/* =================================================================================
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]; // esto es lo que va para cgets.
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;
/* =================================================================================
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);
void leer_respuesta(char * palabra);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
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;
LED0=1;
putst ("AT\n");
time_delay(999999999);
LED1=1;
leer_respuesta(ComandoRecibido1);
LED0=0;
LED1=0;
LED2=1;
if (strcmp(ComandoRecibido1,"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\n");
leer_respuesta(ComandoRecibido1);
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
LED3=1;
}
}
}
//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(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();
//time_delay(1000000000);
}
}
/* =================================================================================
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
CLRWDT();
clear_usart_errors_inline;
}
return RCREG;
}
//*****************************************************************************
//Leer datos (un buffer)
//*****************************************************************************
unsigned char UsartReadChar_nonstop(void)
{
if (!RCIF) // TRMT1 is set when TSR is empty // Cuando no es RCIF, cuando no es 1
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;
}
//*****************************************************************************
//FUNCION Leer_palabra
//*****************************************************************************
void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
do
{
CaracterLeido = getch();
if ((CaracterLeido != '\f') && (CaracterLeido != '\r'))
{
*palabra = CaracterLeido;
*palabra++;
}
indice++;
}
while(indice < 6); // Cambiar a 6 para el dispositivo
}
void leer_respuesta_dispositivo(char * palabra)
{
char indice = 0;
char CaracterLeido;
do
{
CaracterLeido = getch();
if ((CaracterLeido != '\f') && (CaracterLeido != '\r'))
{
*palabra = CaracterLeido;
*palabra++;
}
indice++;
}
while(indice < 6); // Cambiar a 6 para el dispositivo
}
//Primer comando AT
ComandoRecibido1=buffer1;
putst ("AT\n");
LED0=1;
time_delay(999999999);
leer_respuesta(ComandoRecibido1);
LED1=1;
time_delay(999999999);
/*
LED0=0;
LED1=0;
LED2=0;
LED3=0;
time_delay(999999999);
buffer1[0]=getch();
LED0=1;
time_delay(999999999);
buffer1[1]=getch();
LED1=1;
time_delay(999999999);
buffer1[2]=getch();
LED2=1;
time_delay(999999999);
buffer1[3]=getch();
LED3=1;
time_delay(999999999);
buffer1[4]=getch();
LED0=0;
time_delay(999999999);
buffer1[5]=getch();
LED1=0;
time_delay(999999999);
*/
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
LED2=1;
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
}
else{ // No es el comando bueno
LED3=1;
error_comando=1;
while(error_comando==1){
putst ("respuesta incorrecta");
putch ('\r');
putst ("AT\n");
leer_respuesta(ComandoRecibido1);
/*
LED0=0;
LED1=0;
LED2=0;
LED3=0;
buffer1[0]=getch();
LED2=1;
buffer1[1]=getch();
LED3=1;
*/
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
}
}
}
else{ // No es el comando bueno
time_delay(999999999);
error_comando=1;
time_delay(999999999);
while(error_comando==1){
time_delay(999999999);
putst ("respuesta incorrecta");
putch ('\r');
putst ("AT\n");
leer_respuesta(ComandoRecibido1);
/*
LED0=0;
LED1=0;
LED2=0;
LED3=0;
buffer1[0]=getch();
LED2=1;
buffer1[1]=getch();
LED3=1;
*/
if (strcmp(ComandoRecibido1,"OK") == 0){
LED3=1;
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
}
else
LED3=0;
}
}
if (strcmp(ComandoRecibido1,"OK") == 0){
LED3=1;
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
}
Ya se donde falla el programa. Cuando envio el AT!!. La explicacion al post anterior es que cuando recibe un comando erroneo devuelve "ERROR 05", por eso devolvia caracteres.
Estoy probando desde el puerto serie del PIC al hyperterminal enviando distintos comandos y recibo esto:
Enviando AT\r 41 54 0D 0A
Enviando AT\f 41 54 0C
Enviando AT\n 41 54 0A 0D
Por lo tanto ahi estara el error. Lo que no entiendo es que en el primer caso por ejemplo.. envie solo retorno de carro y se le "sume" 0A que es lo de linefeed...
Ahora mismo no me entra en la funcion leer_palabra.. lo tengo declarado en 6..
Es posible que falle algo de la funcion o sera el buffer..?
Como puedo testear eso?
Edito: No sale de ella, ya lo he probado.
Puedes explicarme estas dos lineas:
*palabra= CaracterLeido;
*palabra++;
Muchas gracias de nuevo.
Lo he entendido bien. Ahora hablare con mi profesor para ver si podemos conseguir observar que es lo que se envia con el "OK" de vuelta. Cuando lo sepamos espero que problema solucionado...
Por otra parte, entonces en la parte de la funcion que pone \f lo quito no? y lo sustituto por \n, no?
void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
do
{
CaracterLeido = getch();
if((CaracterLeido !='O')&&(CaracterLeido!='K'))
cont++;
if(cont==1)
LED1=1;
if (cont==2)
LED2=1;
if(cont==3)
LED3=1;
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
}
//*palabra = '\0';
indice++;
time_delay(999999999999999);
}
//while (CaracterLeido != '\n'); //\n
while(indice<7);
//LED2=1;
}
LED0=0;
LED1=0;
LED2=0;
LED3=0;
buffer1[0]=getch();
LED0=1;
buffer1[1]=getch();
LED1=1;
buffer1[2]=getch();
LED2=1;
buffer1[3]=getch();
LED3=1;
buffer1[4]=getch();
LED0=0;
buffer1[5]=getch();
LED1=0;
buffer1[6]=getch();
LED2=0;
No devuelve el comando que mande, lo devuelve bien!
fijate:
Read data:
00000000: 41 54 0d 0d 0a 4f 4b 0d | 0a 0a 41 54 53 30 3d 31 AT...OK...ATS0=1
00000010: 0d 0d 0a 4f 4b 0d 0a 0a | 41 54 53 35 31 32 3d 34 ...OK...ATS512=4
00000020: 0d 0d 0a 4f 4b 0d 0a 0a | 41 54 53 35 30 32 3d 31 ...OK...ATS502=1
00000030: 0d 0d 0a 4f 4b 0d 0a 0a | 41 54 53 35 33 36 3d 31 ...OK...ATS536=1
00000040: 0d 0d 0a 4f 4b 0d 0a 0a | 41 54 2b 42 54 4b 3d 22 ...OK...AT+BTK="
00000050: 31 32 33 34 22 0d 0d 0a | 4f 4b 0d 0a 0a 41 54 26 1234"...OK...AT&
00000060: 57 0d 0d 0a 4f 4b 0d 0a | 0a 41 54 5a 0d 0d 0a 4f W...OK...ATZ...O
00000070: 4b 0d 0a
Esta sequencia marcada en negrita es el "OK" con el retorno de carro etc.. y como ves se va repitiendo. Esta claro que la contestacion del modulo es lo que hay en negrita.
Si te fijas tambien todos los comndos empiezan por AT, por lo que tambien se ve ahi. Fijate que AT es 41 54 y tambien se va repitiendo en todos.
Eso esta bien. Lo hay que hacer es que acabe de leer la funcion cuando se encuentre a dos 0a 0a
Te dejo el link de donde estan colgados los docs: http://www.filefactory.com/file/b51043c/n/Documentos.zip
En el documento "blue2i Quick Start Guide" en la pagina 8 esta el ejemplo de comandos AT que utilizo.
En el documento "AT command Set" en la pag 5 esta la explicacion de lo que envia el modulo y lo que recibe.
Muchas gracias
void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
int cont1=0;
do
{
LED1=1;
CaracterLeido = getch();
LED2=1;
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
}
if(CaracterLeido == '\r'){
//*palabra = '\0';
*palabra++;
}
if(CaracterLeido=='\n'){
//*palabra='\0';
*palabra++;
cont++;
}
if(indice==1)
LED3=1;
indice++;
time_delay(999999999999);
}
//while (CaracterLeido != '\n'); //\n
while(cont!=2);
}
void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
do
{
CaracterLeido = getch();
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
}
if(CaracterLeido == '\r'){
//*palabra = '\0';
*palabra++;
}
if(CaracterLeido=='\n'){
//*palabra='\0';
*palabra++;
cont++;
}
}
//while (CaracterLeido != '\n'); //\n
while(cont!=2);
}
A ver es que seguro que es una tonteria.. hay que tener en cuenta que: 0d es \r y 0a es \n
Hay que leer 7 caracteres : 0d 0a 4f 4b 0d 0a 0a
Primero de todo entra y no entra en el if porque es \r. En este caso hay q saber si dejar ese sitio como \0(nulo) o no. En el siguiente caso pasa lo mismo para \n. Con O y K entra en el if y despues vuelve a no entrar para \r \n \n.
Al final hay un cont que detecta dos \n..
Yo lo que no veo muy claro es la actualizacion del caracter. Una vez haya hecho la "O" por ejemplo, como va a la "K"?
void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
int cont1=0;
int cont2=0;
while(indice<6)
{
CaracterLeido = getch();
cont2++;
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
cont1++;
}
indice++;
if (indice==2)
{
LED1=1;
}
}
LED3=1;
}
Atencion:
Hago esto de aqui:Código: [Seleccionar]void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
int cont1=0;
int cont2=0;
while(indice<6)
{
CaracterLeido = getch();
cont2++;
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
cont1++;
}
indice++;
if (indice==2)
{
LED1=1;
}
}
LED3=1;
}
Y indice vale 2. Eso significa que con el caracter \n pasa algo raro. Que detecta que se acaba o que no lo lee bien.
void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
int cont1=0;
int cont2=0;
while(indice<6)
{
CaracterLeido = getch();
cont2++;
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
cont1++;
}
indice++;
if (indice==2)
LED1=1;
else
LED1=0;
}
LED3=1;
}
Para contestar a lo que me has dicho en el post anterior he hecho lo siguiente:Código: [Seleccionar]void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
int cont1=0;
int cont2=0;
while(indice<6)
{
CaracterLeido = getch();
cont2++;
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
cont1++;
}
indice++;
if (indice==2)
LED1=1;
else
LED1=0;
}
LED3=1;
}
De esta forma ya no tendria que estar siempre encendido el led1 y SI que lo esta. De esta forma comprobamos que el error se encuentra en quanto acaba \n
void leer_respuesta(char * palabra)
{
char indice = 0;
char CaracterLeido;
int cont=0;
int cont1=0;
int cont2=0;
while(indice<6)
{
CaracterLeido = getch();
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*palabra = CaracterLeido;
*palabra++;
cont1++;
}
else
cont2++;
if(cont2==0)
LED3=1;
else
LED3=0;
indice++;
if (cont1==2)
LED2=1;
else
LED2=0;
if (indice==2)
LED1=1;
else
LED1=0;
}
//LED3=1;
}
unsigned char getch(void)
{
LED0=1;
while (RCIF != 1)
{ //1 = The EUSART receive buffer, RCREG, is full
CLRWDT();
clear_usart_errors_inline;
}
return RCREG;
LED0=0;
}
unsigned char getch(void)
{
while (RCIF != 1)
{ //1 = The EUSART receive buffer, RCREG, is full
CLRWDT();
clear_usart_errors_inline;
contador++;
}
if (contador==0)
LED0=1;
else
LED0=0;
return RCREG;
}
#include <htc.h>
#include <stdlib.h> // para poder usar la funcion itoa
#include <string.h>
#include <stdio.h>
#include <conio.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[2]; // 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);
void leer_respuesta(char * palabra);
/* =================================================================================
Main function
================================================================================= */
void main(void)
{
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(999999999);
leer_respuesta(ComandoRecibido1);
if (strcmp(ComandoRecibido1,"AT") == 0){ // Todo a ido bien
LED0=1;
LED1=1;
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
}
else{ // No es el comando bueno
time_delay(999999999);
error_comando=1;
time_delay(999999999);
while(error_comando==1){
time_delay(999999999);
putst ("respuesta incorrecta");
putch ('\r');
putst ("AT");
putch ('\r');
leer_respuesta(ComandoRecibido1);
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
putst ("respuesta correcta");
putch ('\r');
}
}
}
Yo he pensado lo mismo del registro RCREG. He visto que hay que borrar el valor poniendo a 0 el bit RCIF... prueba a ver con eso que dices o con esto que te digo. Yo seguire probando por otros sitios.
void main ()
{
char buffer[10]; // 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();
putst ("AT"); // envio el primer comando AT
putch('\r');
LED0=1;
LeerRespuesta (Respuesta);
LED1=1;
if (strcmp (Respuesta, "OK") == 0)
LED2=1;
else
LED3=1;
while (1);
}
void LeerRespuesta (char * mensaje)
{
char CaracterLeido;
getch();
getch();
do
{
CaracterLeido = getch();
if ((CaracterLeido != '\r') && (CaracterLeido != '\n'))
{
*mensaje = CaracterLeido;
*mensaje++;
}
*mensaje = '\0';
}
while (CaracterLeido != '\n');
}
void LeerRespuesta(char *mensaje) // Recibimos \n \r O K \n \r por lo tanto 6 caracteres.
{
int i=0;
int cont=0;
char buffer_todos_caracteres[6];
while(indice<6){
*mensaje=getche();
cont++;
}
if(cont==0)
LED3=1;
else
LED3=0;
indice++;
}
void SacarCaracteres (char buffer_todos_caracteres) //Sacamos los caracteres recibidos en falso
{
int i=0;
char buffer_caracteres_buenos[2];
while(i<5){
if(buffer_todos_caracteres[i]=='O'){
buffer_caracteres_buenos[0]=buffer_todos_caracteres[i];
}
else if (buffer_todos_caracteres[i]=='K')
buffer_caracteres_buenos[1]=buffer_todos_caracteres[i];
i++;
}
}
void LeerRespuesta(char *mensaje) // Recibimos \n \r O K \n \r por lo tanto 6 caracteres.
{
int i=0;
int cont=0;
while(indice<6){
*mensaje=getch();
cont++;
}
if(cont==0)
LED3=1;
else
LED3=0;
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++;
}
}
Estoy probando la nueva funcion getch. Ha salido y a aumentado el cont 2 veces creo pero ahora se ha metido en el while(RCIF==0) y no entra en ninguno de los if. Va saltando de while a if (del OERR) a if(del FERR) y vuelve a empezar...
Edito: El problema esta en que RCIF siempre es 0. Y eso porque puede pasar..? eso es lo que hay que pensar bien. No entiendo como el buffer puede estar vacio..
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;
}
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;
}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
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;
}
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++;
}
}
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
#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;
}
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();
}
}
#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');
}
}
}
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;
}
Creo que si a veces funciona y a veces no es debido a los retardos. Me explico
putst ("AT");
putch ('\r');
//time_delay(999999999999);
LeerRespuesta (ComandoRecibido1);
Con ese retardo de ahi funciona, en cambio sin el no. Fijate tu! Un reetardo!
/*
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++;
}
}
*/
void LeerRespuesta(char *mensaje) // Recibimos \n \r O K \n \r por lo tanto 6 caracteres.
{
int indice=0;
int cont=0;
time_delay(99);
while(indice<4){
*mensaje=getch();
*mensaje++;
indice++;
}
}
Estoy controlando el registro RCREG y pone 0x41 ( que coincide con la A) y 0x54 que coincide con la T. Porque recibo AT? ese es el problema..
Acabo de ejecutar y he visto que en el RCREG hay 0x0A y en el buffer no lo coge.. sale un caracter extraño. AHI SI QUE ESTA EL PROBLEMA! que puedo hacer?
Osea ahora mismo estoy viendo el caracter 0x0d y despues viene el 0x0a. Cuando coge estos dos para. No los guarda bien en el buffer.. no se si me explico cuando digo que los guarda como un quadrado..
dime algo si no lo entiendes. Ya sabes por donde puede ir el problema? tiene que haber otra forma de guardar los datos...
Y si lo hacemos por punteros? Comprobamos que tal direccion sea 0x0d etc..
RESUMEN DE LA SITUACION: estoy enviando ATE0 y ahora estoy viendo el registro RCREG. La primera vez veo que vale 0x0d ( el retorno de carro) pero cuando lo quiere meter en el buffer sale ese caracter raro. Lo mismo pasa en el segundo con 0x0a. Una vez hay esos dos caracteres salta al while y ya no sale.
Ayudame por favor.
ABDEN: Auto-Baud Detect Enable bit
Asynchronous mode:
1 = Enable baud rate measurement on the next character. Requires reception of a Sync field (55h);
cleared in hardware upon completion.
0 = Baud rate measurement disabled or completed
Fijate:Código: [Seleccionar]ABDEN: Auto-Baud Detect Enable bit
Asynchronous mode:
1 = Enable baud rate measurement on the next character. Requires reception of a Sync field (55h);
cleared in hardware upon completion.
0 = Baud rate measurement disabled or completed
Puede que este relacionado con la velocidad no? no se eh ya casi digo por decir algo..
To set up an Asynchronous Reception:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the asynchronous serial port by clearing
bit, SYNC, and setting bit, SPEN.
3. If the signal at the RX pin is to be inverted, set
the RXDTP bit.
4. If interrupts are desired, set enable bit, RCIE.
5. If 9-bit reception is desired, set bit, RX9.
6. Enable the reception by setting bit, CREN.
7. Flag bit, RCIF, will be set when reception is
complete and an interrupt will be generated if
enable bit, RCIE, was set.
8. Read the RCSTA register to get the 9th bit (if
enabled) and determine if any error occurred
during reception.
9. Read the 8-bit received data by reading the
RCREG register.
10. If any error occurred, clear the error by clearing
enable bit, CREN.
11. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
SPEN: Serial Port Enable bit
1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins)
0 = Serial port disabled (held in Reset)
RX y TX si que lo configuramos pero DT Y CK no... Puede ser esto? Cuando abro el terminal y tengo conectado el modulo sale una configuracion distinta que cuando lo abro con el PIC conectado.
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char * RespuestaRecibida;
char Respuesta[6];
char ok[2];
int i=0;
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("ATE0"); // Desconnectar el echo.
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
while(i<6)
{
if(Respuesta[i]=='O')
{
ok[0]=Respuesta[i];
}
if(Respuesta[i]=='K')
{
ok[1]=Respuesta[i];
}
i++;
}
ComandoRecibido=ok;
if (strcmp(ComandoRecibido1,"\r\nOK\r\n") == 0){ // Todo a ido bien
LED0=1;
error_comando=0;
//putst ("respuesta correcta");
//putch ('\r');
}
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char * RespuestaRecibida;
char Respuesta[9];
char ok[2];
int i=0;
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
//while(1);
while(i<9)
{
if(Respuesta[i]=='O')
{
ok[0]=Respuesta[i];
}
if(Respuesta[i]=='K')
{
ok[1]=Respuesta[i];
}
i++;
}
//while(1);
ComandoRecibido1=ok;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
while(1);
LED0=1;
error_comando=0;
//putst ("respuesta correcta");
//putch ('\r');
}
else{ // No es el comando bueno
while(1);
Sigue sin ir... porque no probamos de pasarle un puntero con un OK declarado des de fuera en vez de poner OK ahi?
#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;
char buffer_caracteres[7];
/* =================================================================================
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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
unsigned char getch(void);
/* =================================================================================
Main function
================================================================================= */
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char * RespuestaRecibida;
char Respuesta[9];
char ok[2];
register const char *ComandoRecibido1;
register const char *ComandoIdeal = "OK";
int i=0;
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
//while(1);
while(i<9)
{
if(Respuesta[i]=='O')
{
ok[0]=Respuesta[i];
}
if(Respuesta[i]=='K')
{
ok[1]=Respuesta[i];
}
i++;
}
ComandoRecibido1=ok;
if (strcmp(ComandoRecibido1,ComandoIdeal) == 0){ // Todo a ido bien
while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
while(1);
error_comando=1;
while(error_comando==1){
putst ("ATE0");
putch ('\r');
// LeerRespuesta (ComandoRecibido1);
if (strcmp(ComandoRecibido1,"OK") == 0){
error_comando=0;
}
}
}
Que puede pasar? el buffer esta bien....
Ahi es donde pongo los puntos de parada con el debugador para ver donde entro, si en uno o en otro.
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char primera_respuesta[9];
char primer_ok[10];
register const char *ComandoIdeal = "OK";
register const char *ComandoRecibido1;
int i=0;
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("AT"); // Desconnectar el echo.
putch ('\r');
primera_respuesta[0] = getch();
primera_respuesta[1] = getch();
primera_respuesta[2] = getch();
primera_respuesta[3] = getch();
primera_respuesta[4] = getch();
primera_respuesta[5] = getch();
primera_respuesta[6] = getch();
primera_respuesta[7] = getch();
primera_respuesta[8] = getch();
//while(1);
while(i<9)
{
if(primera_respuesta[i]=='O')
{
primer_ok[0]=primera_respuesta[i];
}
if(primera_respuesta[i]=='K')
{
primer_ok[1]=primera_respuesta[i];
}
i++;
}
ComandoRecibido1=primer_ok;
if (strcmp(ComandoRecibido1,ComandoIdeal) == 0){ // Todo a ido bien
while(1);
error_comando=0;
}
else{ // No es el comando bueno
while(1);
error_comando=1;
while(error_comando==1){
putst ("AT");
putch ('\r');
primera_respuesta[0] = getch();
primera_respuesta[1] = getch();
primera_respuesta[2] = getch();
primera_respuesta[3] = getch();
primera_respuesta[4] = getch();
primera_respuesta[5] = getch();
primera_respuesta[6] = getch();
primera_respuesta[7] = getch();
primera_respuesta[8] = getch();
while(i<9)
{
if(primera_respuesta[i]=='O')
{
primer_ok[0]=primera_respuesta[i];
}
if(primera_respuesta[i]=='K')
{
primer_ok[1]=primera_respuesta[i];
}
i++;
}
if (strcmp(ComandoRecibido1,ComandoIdeal) == 0)
error_comando=0;
}
}
Entonces como lo hago? indicame que pongo exactamente..
Lo raro es que funcionaba antes..
#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;
/*
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;
char buffer_caracteres[7];
*/
/* =================================================================================
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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
unsigned char getch(void);
/* =================================================================================
Main function
================================================================================= */
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char Respuesta[9];
char ok[3];
register const char *ComandoIdeal = "OK";
register const char *ComandoRecibido1;
int i=0;
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
//while(1);
while(i<9)
{
if(Respuesta[i]=='O')
{
ok[0]=Respuesta[i];
}
if(Respuesta[i]=='K')
{
ok[1]=Respuesta[i];
}
i++;
}
ComandoRecibido1=ok;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
while(1);
error_comando=0;
}
else{ // No es el comando bueno
while(1);
error_comando=1;
while(error_comando==1){
putst ("AT");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
while(i<9)
{
if(Respuesta[i]=='O')
{
ok[0]=Respuesta[i];
}
if(Respuesta[i]=='K')
{
ok[1]=Respuesta[i];
}
i++;
}
if (strcmp(ComandoRecibido1,ComandoIdeal) == 0)
error_comando=0;
}
}
Es que el modulo tiene que enviar lo que envia sino es un follon. Intento hacerlo de esta forma, debo haber tocado el valor de algun buffer.. a ver si puedes verlo. Leo bien los dos buffers.
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;
/*
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;
char buffer_caracteres[7];
*/
/* =================================================================================
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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
unsigned char getch(void);
/* =================================================================================
Main function
================================================================================= */
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char Respuesta[9];
char ok[3];
register const char *ComandoIdeal = "OK";
register const char *ComandoRecibido1;
int i=0;
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//Primer comando AT
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
//while(1);
while(i<9)
{
if(Respuesta[i]=='O')
{
ok[0]=Respuesta[i];
}
if(Respuesta[i]=='K')
{
ok[1]=Respuesta[i];
}
i++;
}
ComandoRecibido1=ok;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
while(1);
error_comando=0;
}
else{ // No es el comando bueno
while(1);
error_comando=1;
while(error_comando==1){
putst ("AT");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
while(i<9)
{
if(Respuesta[i]=='O')
{
ok[0]=Respuesta[i];
}
if(Respuesta[i]=='K')
{
ok[1]=Respuesta[i];
}
i++;
}
if (strcmp(ComandoRecibido1,ComandoIdeal) == 0)
error_comando=0;
}
}
while(j<9)
{
if(Respuesta2[j]=='O')
{
ok2[0]=Respuesta2[j];
}
if(Respuesta2[j]=='K')
{
ok2[1]=Respuesta2[j];
}
if(Respuesta2[j-1]=='K')
{
ok2[2]='\0';
}
j++;
}
//Una condicion para saber que ya ha acabado de hacer los comandos AT
{
// Hay que esperar a recibir los mensajes y para eso hay que ir leyendo el buffer
// El otro dispositivo se quiere connectar con nosotros.
//Mensaje de aparejamiento : "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//Mensaje de llamada: "RING 008098E6A5F4 (17 caracteres)" +4 =21
// Mensaje de connexion establecida CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4
Bueno ya tengo esto casi funcionando. Los comandos AT funcionan todos menos uno que no me da un error:
putst (""AT+BTK="1234"");
Como el numero ( que es el PIN de la conexion) va entre " tira un error ya que esta al lado de los otros que son para encerrar la expresion.
Bueno ya tengo esto casi funcionando. Los comandos AT funcionan todos menos uno que no me da un error:
putst (""AT+BTK="1234"");
Como el numero ( que es el PIN de la conexion) va entre " tira un error ya que esta al lado de los otros que son para encerrar la expresion.
Por otro lado, ahora que lo de los comandos AT ya esta falta lo ultimo del proyecto. Hay que esperar tres mensajes: de emparejamiento, y dos mas para la connexion. Dejo aqui un poco la idea principal:Código: [Seleccionar]//Una condicion para saber que ya ha acabado de hacer los comandos AT
{
// Hay que esperar a recibir los mensajes y para eso hay que ir leyendo el buffer
// El otro dispositivo se quiere connectar con nosotros.
//Mensaje de aparejamiento : "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//Mensaje de llamada: "RING 008098E6A5F4 (17 caracteres)" +4 =21
// Mensaje de connexion establecida CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4
Que se te ocurre? voy a dormir yo.. que ya es muy tarde.
Muchas gracias por la ayuda.
//*****************************************************************************
//MENSAJE DE APAREJAMIENTO: "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//*****************************************************************************
ComandoRecibido9=ok9;
LeerRespuesta(ComandoRecibido9);
//while(1);
if (strcmp(ComandoRecibido9,"PAIR 0 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE LLAMADA: "RING 008098E6A5F4 (17 caracteres)" +4 =21
//*****************************************************************************
ComandoRecibido10=ok10;
LeerRespuesta(ComandoRecibido10);
//while(1);
if (strcmp(ComandoRecibido10,"RING 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE CONEXION: CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4
//*****************************************************************************
ComandoRecibido11=ok11;
LeerRespuesta(ComandoRecibido11);
//while(1);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
Si, me refiero a esos que dices. He hecho lo siguiente ( con tu funcion) y me sale un error comun en las tres veces que la he utilizado
"illegal conversion between pointer types" en la linia que asigno hago ComandoRecibido=ok..Código: [Seleccionar]//*****************************************************************************
//MENSAJE DE APAREJAMIENTO: "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//*****************************************************************************
ComandoRecibido9=ok9;
LeerRespuesta(ComandoRecibido9);
//while(1);
if (strcmp(ComandoRecibido9,"PAIR 0 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE LLAMADA: "RING 008098E6A5F4 (17 caracteres)" +4 =21
//*****************************************************************************
ComandoRecibido10=ok10;
LeerRespuesta(ComandoRecibido10);
//while(1);
if (strcmp(ComandoRecibido10,"RING 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE CONEXION: CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4
//*****************************************************************************
ComandoRecibido11=ok11;
LeerRespuesta(ComandoRecibido11);
//while(1);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
Por otro lado.. me sale un error que si que me preocupa un poco.. ayer me caduco la version del Hitech y la volvi a bajar. La tengo en mode PRO(o eso creo) y ahora con tanto vector.. me tira dos errores de espacio..
Error [1253] C:\Archivos de programa\HI-TECH Software\PICC-18\PRO\9.65\sources\ftneg.c; 20. could not find space (341 bytes) for auto/param block
Error [1253] C:\Archivos de programa\HI-TECH Software\PICC-18\PRO\9.65\sources\lwmod.c; 21. could not find space (341 bytes) for auto/param block
Por favor, ayudame
Muchas gracias de antemano, como siempre :)
#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 final=1;
int prueba=1; // PRUEBA PARA SABER DONDE ESTO
char indice=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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
unsigned char getch(void);
char * LeerRespuesta(char * mensaje);
/* =================================================================================
Main function
================================================================================= */
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char Respuesta1[12];
char ok1[3]; // ES FIJO!!
register const char *ComandoRecibido1;
char Respuesta2[13];
char ok2[3]; // ES FIJO!!
register const char *ComandoRecibido2;
char Respuesta3[15];
char ok3[3]; // ES FIJO!!
register const char *ComandoRecibido3;
char Respuesta4[15];
char ok4[3]; // ES FIJO!!
register const char *ComandoRecibido4;
char Respuesta5[15];
char ok5[3]; // ES FIJO!!
register const char *ComandoRecibido5;
char Respuesta6[20];
char ok6[3]; // ES FIJO!!
register const char *ComandoRecibido6;
char Respuesta7[11];
char ok7[3]; // ES FIJO!!
register const char *ComandoRecibido7;
char Respuesta8[10];
char ok8[3]; // ES FIJO!!
register const char *ComandoRecibido8;
char Respuesta9[23];
char ok9[19]; // OJO aqui son 19 caracteres + 4
register const char *ComandoRecibido9;
char Respuesta10[21];
char ok10[17]; // OJO aqui son 19 caracteres + 4
register const char *ComandoRecibido10;
char Respuesta11[31];
char ok11[27]; // OJO aqui son 19 caracteres + 4
register const char *ComandoRecibido11;
register const char *ComandoIdeal = "OK";
int i=0;
int j=0;
int z=0;
int v=0;
int w=0;
int q=0;
int t=0;
int d=0;
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//*****************************************************************************
//PRIMER COMANDO AT
//*****************************************************************************
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta1[0] = getch();
Respuesta1[1] = getch();
Respuesta1[2] = getch();
Respuesta1[3] = getch();
Respuesta1[4] = getch();
Respuesta1[5] = getch();
Respuesta1[6] = getch();
Respuesta1[7] = getch();
Respuesta1[8] = getch();
while(i<9)
{
if(Respuesta1[i]=='O')
{
ok1[0]=Respuesta1[i];
}
if(Respuesta1[i]=='K')
{
ok1[1]=Respuesta1[i];
}
if(Respuesta1[i-1]=='K')
{
ok1[2]='\0';
}
i++;
}
ComandoRecibido1=ok1;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//SEGUNDO COMANDO AT
//*****************************************************************************
putst ("ATS0=1"); // Desconnectar el echo.
putch ('\r');
Respuesta2[0] = getch();
Respuesta2[1] = getch();
Respuesta2[2] = getch();
Respuesta2[3] = getch();
Respuesta2[4] = getch();
Respuesta2[5] = getch();
Respuesta2[6] = getch();
Respuesta2[7] = getch();
Respuesta2[8] = getch();
Respuesta2[9] = getch();
Respuesta2[10] = getch();
Respuesta2[11] = getch();
Respuesta2[12] = getch();
while(j<13) // OJO CAMBIAR ESTO DE UN COMANDO A OTRO. SINO SE QUEDA Y NO ACABA
{
if(Respuesta2[j]=='O')
{
ok2[0]=Respuesta2[j];
}
if(Respuesta2[j]=='K')
{
ok2[1]=Respuesta2[j];
}
if(Respuesta2[j-1]=='K')
{
ok2[2]='\0';
}
j++;
}
//while(1);
ComandoRecibido2=ok2;
if (strcmp(ComandoRecibido2,"OK") == 0){ // Todo a ido bien
// while(1);
LED1=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//TERCER COMANDO AT
//*****************************************************************************
putst ("ATS512=4"); // Desconnectar el echo.
putch ('\r');
Respuesta3[0] = getch();
Respuesta3[1] = getch();
Respuesta3[2] = getch();
Respuesta3[3] = getch();
Respuesta3[4] = getch();
Respuesta3[5] = getch();
Respuesta3[6] = getch();
Respuesta3[7] = getch();
Respuesta3[8] = getch();
Respuesta3[9] = getch();
Respuesta3[10] = getch();
Respuesta3[11] = getch();
Respuesta3[12] = getch();
Respuesta3[13] = getch();
Respuesta3[14] = getch();
while(z<15)
{
if(Respuesta3[z]=='O')
{
ok3[0]=Respuesta3[z];
}
if(Respuesta3[z]=='K')
{
ok3[1]=Respuesta3[z];
}
if(Respuesta3[z-1]=='K')
{
ok3[2]='\0';
}
z++; // CAMBIAR
}
//while(1);
ComandoRecibido3=ok3;
if (strcmp(ComandoRecibido3,"OK") == 0){ // Todo a ido bien
//while(1);
LED2=1;
error_comando=0;
}
else{ // No es el comando bueno
//while(1);
error_comando=1;
}
//*****************************************************************************
//QUARTO COMANDO AT
//*****************************************************************************
putst ("ATS502=1"); // Desconnectar el echo.
putch ('\r');
Respuesta4[0] = getch();
Respuesta4[1] = getch();
Respuesta4[2] = getch();
Respuesta4[3] = getch();
Respuesta4[4] = getch();
Respuesta4[5] = getch();
Respuesta4[6] = getch();
Respuesta4[7] = getch();
Respuesta4[8] = getch();
Respuesta4[9] = getch();
Respuesta4[10] = getch();
Respuesta4[11] = getch();
Respuesta4[12] = getch();
Respuesta4[13] = getch();
Respuesta4[14] = getch();
while(v<15) // OJO CAMBIAR ESTO DE UN COMANDO A OTRO. SINO SE QUEDA Y NO ACABA
{
if(Respuesta4[v]=='O')
{
ok4[0]=Respuesta4[v];
}
if(Respuesta4[v]=='K')
{
ok4[1]=Respuesta4[v];
}
if(Respuesta4[v-1]=='K')
{
ok4[2]='\0';
}
v++; // CAMBIAR
}
//while(1);
ComandoRecibido4=ok4;
if (strcmp(ComandoRecibido4,"OK") == 0){ // Todo a ido bien
// while(1);
LED3=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//QUINTO COMANDO AT
//*****************************************************************************
putst ("ATS536=1"); // Desconnectar el echo.
putch ('\r');
Respuesta5[0] = getch();
Respuesta5[1] = getch();
Respuesta5[2] = getch();
Respuesta5[3] = getch();
Respuesta5[4] = getch();
Respuesta5[5] = getch();
Respuesta5[6] = getch();
Respuesta5[7] = getch();
Respuesta5[8] = getch();
Respuesta5[9] = getch();
Respuesta5[10] = getch();
Respuesta5[11] = getch();
Respuesta5[12] = getch();
Respuesta5[13] = getch();
Respuesta5[14] = getch();
while(w<15) // OJO CAMBIAR ESTO DE UN COMANDO A OTRO. SINO SE QUEDA Y NO ACABA
{
if(Respuesta5[w]=='O')
{
ok5[0]=Respuesta5[w];
}
if(Respuesta5[w]=='K')
{
ok5[1]=Respuesta5[w];
}
if(Respuesta5[w-1]=='K')
{
ok5[2]='\0';
}
w++; // CAMBIAR
}
//while(1);
ComandoRecibido5=ok5;
if (strcmp(ComandoRecibido5,"OK") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
LED0=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//SEXTO COMANDO AT
//*****************************************************************************
putst ("AT+BTK=\"1234\"");
putch ('\r');
Respuesta6[0] = getch();
Respuesta6[1] = getch();
Respuesta6[2] = getch();
Respuesta6[3] = getch();
Respuesta6[4] = getch();
Respuesta6[5] = getch();
Respuesta6[6] = getch();
Respuesta6[7] = getch();
Respuesta6[8] = getch();
Respuesta6[9] = getch();
Respuesta6[10] = getch();
Respuesta6[11] = getch();
Respuesta6[12] = getch();
Respuesta6[13] = getch();
Respuesta6[14] = getch();
Respuesta6[15] = getch();
Respuesta6[16] = getch();
Respuesta6[17] = getch();
Respuesta6[18] = getch();
Respuesta6[19] = getch();
//while(1);
while(q<20) // OJO CAMBIAR ESTO DE UN COMANDO A OTRO. SINO SE QUEDA Y NO ACABA
{
if(Respuesta6[q]=='O')
{
ok6[0]=Respuesta6[q];
}
if(Respuesta6[q]=='K')
{
ok6[1]=Respuesta6[q];
}
if(Respuesta6[q-1]=='K')
{
ok6[2]='\0';
}
q++; // CAMBIAR
}
//while(1);
ComandoRecibido6=ok6;
if (strcmp(ComandoRecibido6,"OK") == 0){ // Todo a ido bien
// while(1);
LED1=0;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//SEPTIMO COMANDO AT
//*****************************************************************************
putst ("AT&W");
putch ('\r');
Respuesta7[0] = getch();
Respuesta7[1] = getch();
Respuesta7[2] = getch();
Respuesta7[3] = getch();
Respuesta7[4] = getch();
Respuesta7[5] = getch();
Respuesta7[6] = getch();
Respuesta7[7] = getch();
Respuesta7[8] = getch();
Respuesta7[9] = getch();
Respuesta7[10] = getch();
while(t<11) // OJO CAMBIAR ESTO DE UN COMANDO A OTRO. SINO SE QUEDA Y NO ACABA
{
if(Respuesta7[t]=='O')
{
ok7[0]=Respuesta7[t];
}
if(Respuesta7[t]=='K')
{
ok7[1]=Respuesta7[t];
}
if(Respuesta7[t-1]=='K')
{
ok7[2]='\0';
}
t++;
}
//while(1);
ComandoRecibido7=ok7;
if (strcmp(ComandoRecibido7,"OK") == 0){ // Todo a ido bien
// while(1);
LED2=0;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//OCTAVO COMANDO AT
//*****************************************************************************
putst ("ATZ");
putch ('\r');
Respuesta8[0] = getch();
Respuesta8[1] = getch();
Respuesta8[2] = getch();
Respuesta8[3] = getch();
Respuesta8[4] = getch();
Respuesta8[5] = getch();
Respuesta8[6] = getch();
Respuesta8[7] = getch();
Respuesta8[8] = getch();
Respuesta8[9] = getch();
while(d<10) // OJO CAMBIAR ESTO DE UN COMANDO A OTRO. SINO SE QUEDA Y NO ACABA
{
if(Respuesta8[d]=='O')
{
ok8[0]=Respuesta8[d];
}
if(Respuesta8[d]=='K')
{
ok8[1]=Respuesta8[d];
}
if(Respuesta8[d-1]=='K')
{
ok8[2]='\0';
}
d++;
}
//while(1);
ComandoRecibido8=ok8;
if (strcmp(ComandoRecibido8,"OK") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
LED3=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//Una condicion para saber que ya ha acabado de hacer los comandos AT
// Hay que esperar a recibir los mensajes y para eso hay que ir leyendo el buffer
// El otro dispositivo se quiere connectar con nosotros.
//Mensaje de aparejamiento : "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//*****************************************************************************
//MENSAJE DE APAREJAMIENTO: "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//*****************************************************************************
ComandoRecibido9=ok9;
LeerRespuesta(ok9);
//while(1);
if (strcmp(ComandoRecibido9,"PAIR 0 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE LLAMADA: "RING 008098E6A5F4 (17 caracteres)" +4 =21
//*****************************************************************************
ComandoRecibido10=ok10;
LeerRespuesta(ok10);
//while(1);
if (strcmp(ComandoRecibido10,"RING 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE CONEXION: CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4
//*****************************************************************************
ComandoRecibido11=ok11;
LeerRespuesta(ok11);
//while(1);
if (strcmp(ComandoRecibido11,"CONNECT 008098E6A5F4,1101 A") == 0){ // Todo a ido bien
// while(1);
error_comando=0;
final=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
Gracias de nuevo. Perdon, no me fije bien como iba la funcion Respuesta. Entonces esa funcion es capaz de quedarse con los mensajes:
PAIR 0 008098E6A5F4
RING 008098E6A5F
CONNECT 008098E6A5F4,1101 A
Porque veo que se acaba cuando hay un \n. Habria que modificarla no?
Por otro lado, ahora ya solo me aparecen esos errores por lo del espacio. Creo que es porque uso muchos vectores, hechale un vistazo al codigo:
.................
Desinstalo el compilador y me bajo ese programa y limpio los registros?
Pero el buffer de respuesta yo lo tengo con la medida exacta para que no se cuelen caracteres extraños, ayer me pasaba.
Y si cuando debugo quiero ver el valor de cada buffer de esta manera resulta mas senzillo..
He probado eso que dices de limpiar los registros y sigue saliendo el error.. habra que tirar por donde tu dices pero creo que si ponemos un unico vector sera peor..
No se la verdad.
//*****************************************************************************
//PRIMER COMANDO AT
//*****************************************************************************
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta1[0] = getch();
Respuesta1[1] = getch();
Respuesta1[2] = getch();
Respuesta1[3] = getch();
Respuesta1[4] = getch();
Respuesta1[5] = getch();
Respuesta1[6] = getch();
Respuesta1[7] = getch();
Respuesta1[8] = getch();
while(i<9)
{
if(Respuesta1[i]=='O')
{
ok1[0]=Respuesta1[i];
}
if(Respuesta1[i]=='K')
{
ok1[1]=Respuesta1[i];
}
if(Respuesta1[i-1]=='K')
{
ok1[2]='\0';
}
i++;
}
ComandoRecibido1=ok1;
if (strcmp(ComandoRecibido1,"OK") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//SEGUNDO COMANDO AT
//*****************************************************************************
putst ("ATS0=1"); // Desconnectar el echo.
putch ('\r');
Respuesta2[0] = getch();
Respuesta2[1] = getch();
Respuesta2[2] = getch();
Respuesta2[3] = getch();
Respuesta2[4] = getch();
Respuesta2[5] = getch();
Respuesta2[6] = getch();
Respuesta2[7] = getch();
Respuesta2[8] = getch();
Respuesta2[9] = getch();
Respuesta2[10] = getch();
Respuesta2[11] = getch();
Respuesta2[12] = getch();
while(j<13) // OJO CAMBIAR ESTO DE UN COMANDO A OTRO. SINO SE QUEDA Y NO ACABA
{
if(Respuesta2[j]=='O')
{
ok2[0]=Respuesta2[j];
}
if(Respuesta2[j]=='K')
{
ok2[1]=Respuesta2[j];
}
if(Respuesta2[j-1]=='K')
{
ok2[2]='\0';
}
j++;
}
//while(1);
ComandoRecibido2=ok2;
if (strcmp(ComandoRecibido2,"OK") == 0){ // Todo a ido bien
// while(1);
LED1=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
En el caso que por ejemplo el primer comando tenga 15 caracteres y el segundo tenga 12 hara que queden esos 3 alli con el valor anterior..
Voy a probar entonces! Ya te voy contando!
Por cierto antes declaraste indice como char.. fue un error no?
#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 final=1;
int prueba=1; // PRUEBA PARA SABER DONDE ESTO
/* =================================================================================
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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
unsigned char getch(void);
char * LeerRespuesta(char * mensaje);
/* =================================================================================
Main function
================================================================================= */
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char indice;
register const char *ComandoIdeal = "OK";
char Respuesta[30];
char ok[3]; // ES FIJO!!
register const char *ComandoRecibido;
/*
char Respuesta2[13];
char ok2[3]; // ES FIJO!!
register const char *ComandoRecibido2;
char Respuesta3[15];
char ok3[3]; // ES FIJO!!
register const char *ComandoRecibido3;
char Respuesta4[15];
char ok4[3]; // ES FIJO!!
register const char *ComandoRecibido4;
char Respuesta5[15];
char ok5[3]; // ES FIJO!!
register const char *ComandoRecibido5;
char Respuesta6[20];
char ok6[3]; // ES FIJO!!
register const char *ComandoRecibido6;
char Respuesta7[11];
char ok7[3]; // ES FIJO!!
register const char *ComandoRecibido7;
char Respuesta8[10];
char ok8[3]; // ES FIJO!!
register const char *ComandoRecibido8;
char Respuesta9[23];
char ok9[19]; // OJO aqui son 19 caracteres + 4
register const char *ComandoRecibido9;
char Respuesta10[21];
char ok10[17]; // OJO aqui son 19 caracteres + 4
register const char *ComandoRecibido10;
char Respuesta11[31];
char ok11[27]; // OJO aqui son 19 caracteres + 4
register const char *ComandoRecibido11;
*/
/*
int i=0;
int j=0;
int z=0;
int v=0;
int w=0;
int q=0;
int t=0;
int d=0;
*/
init_system();
setup_sensor();
setup_adc();
serial_setup();
/* =================================================================================
Establecer connexion con comandos AT
================================================================================= */
//*****************************************************************************
//PRIMER COMANDO AT
//*****************************************************************************
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]='\0';
indice=0;
indice = 0;
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
}
ok[2] = '\0';
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
while(1);
error_comando=1;
}
//***********************************************************//
//ESPERAR A QUE UN DISPOSITIVO SE QUIERA CONNECTAR AL NUESTRO//
//***********************************************************//
//*****************************************************************************
//MENSAJE DE APAREJAMIENTO: "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//*****************************************************************************
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]= getch();
Respuesta[14]= getch();
Respuesta[15]= getch();
Respuesta[16]= getch();
Respuesta[17]= getch();
Respuesta[18]= getch();
Respuesta[19]= getch();
Respuesta[20]= getch();
Respuesta[21]= getch();
Respuesta[22]= getch();
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
// RETOCAR ESTA FUNCION
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
aparejamiento[0] = Respuesta[indice];
aparejamiento[1] = Respuesta[indice + 1];
}
indice++;
aparejamiento[2] = '\0';
}
//while(1);
ComandoRecibido=aparejamiento;
if (strcmp(ComandoRecibido,"PAIR 0 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE LLAMADA: "RING 008098E6A5F4 (17 caracteres)" +4 =21
//*****************************************************************************
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]= getch();
Respuesta[14]= getch();
Respuesta[15]= getch();
Respuesta[16]= getch();
Respuesta[17]= getch();
Respuesta[18]= getch();
Respuesta[19]= getch();
Respuesta[20]= getch();
Respuesta[21]= '\0';
Respuesta[22]= '\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
// RETOCAR ESTA FUNCION
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ring[0] = Respuesta[indice];
ring[1] = Respuesta[indice + 1];
}
indice++;
ring[2] = '\0';
}
//while(1);
ComandoRecibido=ring;
if (strcmp(ComandoRecibido,"RING 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE CONEXION: CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4=31
//*****************************************************************************
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]= getch();
Respuesta[14]= getch();
Respuesta[15]= getch();
Respuesta[16]= getch();
Respuesta[17]= getch();
Respuesta[18]= getch();
Respuesta[19]= getch();
Respuesta[20]= getch();
Respuesta[21]= getch();
Respuesta[22]= getch();
Respuesta[23]= getch();
Respuesta[24]= getch();
Respuesta[25]= getch();
Respuesta[26]= getch();
Respuesta[27]= getch();
Respuesta[28]= getch();
Respuesta[29]= getch();
Respuesta[30]= getch();
Respuesta[31]= '\0';
indice = 0;
//while(1);
// RETOCAR ESTA FUNCION
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
connexion[0] = Respuesta[indice];
connexion[1] = Respuesta[indice + 1];
}
indice++;
connexion[2] = '\0';
}
//while(1);
ComandoRecibido=connexion;
if (strcmp(ComandoRecibido,"CONNECT 008098E6A5F4,1101 A") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
Ya funciona todo otra vez ( lo de los comandos AT) y con mucha menos memoria, si señor! hago la implementacion para leer los mensajes y no se queja del compilador.
Te queria comentar que habria que hacer un while.. porque claro los comandos se envian, el dispositivo se configura para poder ser encontrado y para poder ser connectable con los otros pero eso no te garantiza que sea al instante. Tiene que estar un rato en estado de "idle" monitorizando si le llega eso o no. Creo que una vez que viene el primer mensaje ya vienen los otros dos seguidos. Osea solo habria que hacer esto para el primero.
Te dejo el codigo aqui. Hay que hacer la funcion que lea exactamente el caracter, se te ocurre algo para no tener que hacer lo del ok[0]=='O'.. en este caso son muchos caracteres.. demasiados!
Si no hay mas remedio pues se hara pero yo pregunto a ver..Código: [Seleccionar]//***********************************************************//
//ESPERAR A QUE UN DISPOSITIVO SE QUIERA CONNECTAR AL NUESTRO//
//***********************************************************//
//*****************************************************************************
//MENSAJE DE APAREJAMIENTO: "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//*****************************************************************************
.........
//*****************************************************************************
//MENSAJE DE LLAMADA: "RING 008098E6A5F4 (17 caracteres)" +4 =21
//*****************************************************************************
............
//*****************************************************************************
//MENSAJE DE CONEXION: CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4=31
//*****************************************************************************
Lo de poner hasta el numero 31 de espacios vacios lo dejare asi porque no me molesta y lo probe de tu manera y no me funciono. Total, funciona bien.
Si, el mensaje tiene la misma estructura que antes. El datasheet pone que todas las respuestas del modulo empiezan y acaban con \n. Respecto a leer cada caracter, harias la misma estructura que antes?
que vaya corriendo y ir cogiendo por los caracteres? o un if de esta forma:
if((buffer='P')&& buffer[i+1]=='A') etc etc.. hasta completar el mensaje.
#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 final=1;
int prueba=1; // PRUEBA PARA SABER DONDE ESTO
/* =================================================================================
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);
void clear_usart_errors(void);
unsigned char read_spi (void);
unsigned int read_adc(void);
unsigned char getch(void);
char * LeerRespuesta(char * mensaje);
/* =================================================================================
Main function
================================================================================= */
void main ()
{
valor_potenciometro = 0;
valor_sensor_temperatura = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
char indice;
register const char *ComandoIdeal = "OK";
char Respuesta[32];
char ok[3]; // ES FIJO!!
char aparejamiento[23];
char ring[21];
char connexion[31];
register const char *ComandoRecibido;
int i=9;
init_system();
setup_sensor();
setup_adc();
serial_setup();
//*****************************************************************************
// Establecer connexion con comandos AT
//*****************************************************************************
//*****************************************************************************
//PRIMER COMANDO AT
//*****************************************************************************
putst ("AT"); // Desconnectar el echo.
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]='\0';
Respuesta[10]='\0';
Respuesta[11]='\0';
Respuesta[12]='\0';
Respuesta[13]='\0';
Respuesta[14]='\0';
Respuesta[15]='\0';
Respuesta[16]='\0';
Respuesta[17]='\0';
Respuesta[18]='\0';
Respuesta[19]='\0';
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//SEGUNDO COMANDO AT
//*****************************************************************************
putst ("ATS0=1");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]='\0';
Respuesta[14]='\0';
Respuesta[15]='\0';
Respuesta[16]='\0';
Respuesta[17]='\0';
Respuesta[18]='\0';
Respuesta[19]='\0';
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED1=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//TERCER COMANDO AT
//*****************************************************************************
putst ("ATS512=4");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]= getch();
Respuesta[14]= getch();
Respuesta[15]='\0';
Respuesta[16]='\0';
Respuesta[17]='\0';
Respuesta[18]='\0';
Respuesta[19]='\0';
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED2=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//CUARTO COMANDO AT
//*****************************************************************************
putst ("ATS502=1");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]= getch();
Respuesta[14]= getch();
Respuesta[15]='\0';
Respuesta[16]='\0';
Respuesta[17]='\0';
Respuesta[18]='\0';
Respuesta[19]='\0';
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED3=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//QUINTO COMANDO AT
//*****************************************************************************
putst ("ATS536=1");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]= getch();
Respuesta[14]= getch();
Respuesta[15]='\0';
Respuesta[16]='\0';
Respuesta[17]='\0';
Respuesta[18]='\0';
Respuesta[19]='\0';
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED0=0;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//SEXTO COMANDO AT
//*****************************************************************************
putst ("AT+BTK=\"1234\"");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= getch();
Respuesta[12]= getch();
Respuesta[13]= getch();
Respuesta[14]= getch();
Respuesta[15]= getch();
Respuesta[16]= getch();
Respuesta[17]= getch();
Respuesta[18]= getch();
Respuesta[19]= getch();
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED1=0;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//SEPTIMO COMANDO AT
//*****************************************************************************
putst ("AT&W");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= getch();
Respuesta[11]= '\0';
Respuesta[12]= '\0';
Respuesta[13]= '\0';
Respuesta[14]= '\0';
Respuesta[15]= '\0';
Respuesta[16]= '\0';
Respuesta[17]= '\0';
Respuesta[18]= '\0';
Respuesta[19]= '\0';
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED2=0;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//OCTAVO COMANDO AT
//*****************************************************************************
putst ("ATZ");
putch ('\r');
Respuesta[0] = getch();
Respuesta[1] = getch();
Respuesta[2] = getch();
Respuesta[3] = getch();
Respuesta[4] = getch();
Respuesta[5] = getch();
Respuesta[6] = getch();
Respuesta[7] = getch();
Respuesta[8] = getch();
Respuesta[9]= getch();
Respuesta[10]= '\0';
Respuesta[11]= '\0';
Respuesta[12]= '\0';
Respuesta[13]= '\0';
Respuesta[14]= '\0';
Respuesta[15]= '\0';
Respuesta[16]= '\0';
Respuesta[17]= '\0';
Respuesta[18]= '\0';
Respuesta[19]= '\0';
Respuesta[20]='\0';
Respuesta[21]='\0';
Respuesta[22]='\0';
Respuesta[23]='\0';
Respuesta[24]='\0';
Respuesta[25]='\0';
Respuesta[26]='\0';
Respuesta[27]='\0';
Respuesta[28]='\0';
Respuesta[29]='\0';
Respuesta[30]='\0';
Respuesta[31]= '\0';
indice = 0;
//while(1);
while (Respuesta[indice] != '\0')
{
if ((Respuesta[indice] == 'O') && (Respuesta[indice + 1] == 'K'))
{
ok[0] = Respuesta[indice];
ok[1] = Respuesta[indice + 1];
}
indice++;
ok[2] = '\0';
}
//while(1);
ComandoRecibido=ok;
if (strcmp(ComandoRecibido,"OK") == 0){ // Todo a ido bien
// while(1);
LED3=0;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//***********************************************************//
//ESPERAR A QUE UN DISPOSITIVO SE QUIERA CONNECTAR AL NUESTRO//
//***********************************************************//
//*****************************************************************************
//MENSAJE DE APAREJAMIENTO: "PAIR 0 008098E6A5F4" (19 caracteres) + 4 =23
//*****************************************************************************
LeerRespuesta(aparejamiento);
if (strcmp(ComandoRecibido,"PAIR 0 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE LLAMADA: "RING 008098E6A5F4 (17 caracteres)" +4 =21
//*****************************************************************************
LeerRespuesta(ring);
ComandoRecibido=ring;
if (strcmp(ComandoRecibido,"RING 008098E6A5F4") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
//*****************************************************************************
//MENSAJE DE CONEXION: CONNECT 008098E6A5F4,1101 A (27 caracteres) + 4=31
//*****************************************************************************
LeerRespuesta(connexion);
ComandoRecibido=connexion;
if (strcmp(ComandoRecibido,"CONNECT 008098E6A5F4,1101 A") == 0){ // Todo a ido bien
// while(1);
LED0=1;
error_comando=0;
}
else{ // No es el comando bueno
// while(1);
error_comando=1;
}
Muchas gracias por estos ejemplos. Ya lo he preparado todo para cuando mañana lo pruebe en el lab.
De esta manera el programa se quedara esperando a los tres mensajes o hay que poner algun while para que este por alli y vaya mirandolo todo? Crees que de esta forma funcionara?
Adjunto el codigo entero de esta parte de comandos AT que es como lo tengo actualmente:
......