TODOPIC
Microcontroladores PIC => Lenguaje C para microcontroladores PIC => Mensaje iniciado por: churrinfunflais en 28 de Mayo de 2012, 15:17:40
-
Hola amigos!!!
Ando en un proyecto sencillo que utiliza el puerto USART del micro y estoy teniendo un poco de problemas al utilizar la función getsUSART(), les platico lo que intento hacer:
Mi objetivo es el de implementar una capa de seguridad en la conexión de la PC al micro (usuario y un password).
Solo que no encuentro la manera de recibir un string completo y compararlo con un valor.
Estoy utilizando un 18f4550 con crystal de 12mhz y un modulo bluetooth a serial en un compilador C18.
Aquí les dejo el código en el que estoy trabajando:
/********************************************************************
FileName: main.c
Dependencies: See INCLUDES section
Processor: PIC18, PIC24, and PIC32 USB Microcontrollers
Hardware: This demo is natively intended to be used on Microchip USB demo
boards supported by the MCHPFSUSB stack. See release notes for
support matrix. This demo can be modified for use on other hardware
platforms.
Complier: Microchip C18 (for PIC18), C30 (for PIC24), C32 (for PIC32)
********************************************************************/
/** INCLUDES *******************************************************/
#include "HardwareProfile.h"
#include "GenericTypeDefs.h"
#include <usart.h>
/** CONFIGURATION **************************************************/
#if defined(FOZZ_BOARD) // Configuration bits for PICDEM FS USB Demo Board (based on PIC18F4550)
#pragma config PLLDIV = 6
#pragma config CPUDIV = OSC1_PLL2
#pragma config USBDIV = 2 // Clock source from 96MHz PLL/2
#pragma config FOSC = HSPLL_HS
#pragma config FCMEN = OFF
#pragma config IESO = OFF
#pragma config PWRT = OFF
#pragma config BOR = ON
#pragma config BORV = 3
#pragma config VREGEN = ON //USB Voltage Regulator
#pragma config WDT = OFF
#pragma config WDTPS = 32768
#pragma config MCLRE = ON
#pragma config LPT1OSC = OFF
#pragma config PBADEN = OFF
// #pragma config CCP2MX = ON
#pragma config STVREN = ON
#pragma config LVP = OFF
// #pragma config ICPRT = OFF // Dedicated In-Circuit Debug/Programming
#pragma config XINST = OFF // Extended Instruction Set
#pragma config CP0 = OFF
#pragma config CP1 = OFF
// #pragma config CP2 = OFF
// #pragma config CP3 = OFF
#pragma config CPB = OFF
// #pragma config CPD = OFF
#pragma config WRT0 = OFF
#pragma config WRT1 = OFF
// #pragma config WRT2 = OFF
// #pragma config WRT3 = OFF
#pragma config WRTB = OFF // Boot Block Write Protection
#pragma config WRTC = OFF
// #pragma config WRTD = OFF
#pragma config EBTR0 = OFF
#pragma config EBTR1 = OFF
// #pragma config EBTR2 = OFF
// #pragma config EBTR3 = OFF
#pragma config EBTRB = OFF
#else
#error No hardware board defined, see "HardwareProfile.h" and __FILE__
#endif
/* ** PRIVATE PROTOTYPES ** */
void ProcessIO(void);
void ISRRecepcion(void);
/* ** Variables de uso general ** */
volatile char kbhit;
volatile unsigned char Buffer [3];
/* ** Seccion de codigo a partir de la direccion 0x0008 ** */
#pragma code interrupcion = 0x0008
void VectorInterrupcion(void) {
_asm goto ISRRecepcion _endasm
}
#pragma code // Cerramos seccion.-
#pragma interrupt ISRRecepcion
/********************************************************************
* Function: void ISRRecepcion(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: Interrupt Routine
*
* Note: None
*******************************************************************/
void ISRRecepcion(void) {
if (PIR1bits.RCIF == 1) {
getsUSART(Buffer, 3);
// Dato = getcUSART(); // Leemos dato recibido.-
kbhit = 1; // Indicamos que se ha recibido un dato.-
PIR1bits.RCIF = 0; // Borramos flag.-
}
}
/********************************************************************
* Function: void main(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: Main program entry point.
*
* Note: None
*******************************************************************/
void main(void) {
OpenUSART(USART_TX_INT_OFF & USART_RX_INT_ON & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, 155); // 19.200 baudios.-
RCONbits.IPEN = 0; // Desabilitamos Prioridades.-
INTCONbits.PEIE = 1; // Habilitamos Interrupcion de perifericos.-
INTCONbits.GIE = 1; // Habilitamos Interrupcion Global.-
putrsUSART("introducir Pasword \n");
while (1) {
ProcessIO();
}
}
/********************************************************************
* Function: void ProcessIO(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This function is a place holder for other user
* routines. It is a mixture of tasks.
*
* Note: None
*******************************************************************/
void ProcessIO(void) {
while (kbhit == 0) {
}; // Esperamos a recibir dato.-
kbhit = 0;
if (Buffer[] == "123") { //El pasword es 123
putsUSART("Access granted \n");
}else {
putsUSART("Access denied \n");
}
}Como puedo comparar el Buffer contra un valor??
-
El PLL está más configurado. Luego para comparar string tienes strcmp.
Saludos!
-
El PLL está más configurado. Luego para comparar string tienes strcmp.
Saludos!
Bueno creo que he resuelto estas sugerencias me esta corriendo bien.
/********************************************************************
FileName: main.c
Dependencies: See INCLUDES section
Processor: PIC18, PIC24, and PIC32 USB Microcontrollers
Hardware: This demo is natively intended to be used on Microchip USB demo
boards supported by the MCHPFSUSB stack. See release notes for
support matrix. This demo can be modified for use on other hardware
platforms.
Complier: Microchip C18 (for PIC18), C30 (for PIC24), C32 (for PIC32)
********************************************************************/
/** INCLUDES *******************************************************/
#include "HardwareProfile.h"
#include "GenericTypeDefs.h"
#include "string.h"
#include "usart.h"
/** CONFIGURATION **************************************************/
#if defined(FOZZ_BOARD) // Configuration bits for PICDEM FS USB Demo Board (based on PIC18F4550)
#pragma config PLLDIV = 3
#pragma config CPUDIV = OSC3_PLL4
#pragma config USBDIV = 2 // Clock source from 96MHz PLL/2
#pragma config FOSC = HSPLL_HS
#pragma config FCMEN = OFF
#pragma config IESO = OFF
#pragma config PWRT = OFF
#pragma config BOR = ON
#pragma config BORV = 3
#pragma config VREGEN = ON //USB Voltage Regulator
#pragma config WDT = OFF
#pragma config WDTPS = 32768
#pragma config MCLRE = ON
#pragma config LPT1OSC = OFF
#pragma config PBADEN = OFF
// #pragma config CCP2MX = ON
#pragma config STVREN = ON
#pragma config LVP = OFF
// #pragma config ICPRT = OFF // Dedicated In-Circuit Debug/Programming
#pragma config XINST = OFF // Extended Instruction Set
#pragma config CP0 = OFF
#pragma config CP1 = OFF
// #pragma config CP2 = OFF
// #pragma config CP3 = OFF
#pragma config CPB = OFF
// #pragma config CPD = OFF
#pragma config WRT0 = OFF
#pragma config WRT1 = OFF
// #pragma config WRT2 = OFF
// #pragma config WRT3 = OFF
#pragma config WRTB = OFF // Boot Block Write Protection
#pragma config WRTC = OFF
// #pragma config WRTD = OFF
#pragma config EBTR0 = OFF
#pragma config EBTR1 = OFF
// #pragma config EBTR2 = OFF
// #pragma config EBTR3 = OFF
#pragma config EBTRB = OFF
#else
#error No hardware board defined, see "HardwareProfile.h" and __FILE__
#endif
/* ** PRIVATE PROTOTYPES ** */
void ProcessIO(void);
void ISRRecepcion(void);
/* ** Variables de uso general ** */
volatile char kbhit, Dato;
volatile unsigned char Buffer [3];
/* ** Seccion de codigo a partir de la direccion 0x0008 ** */
#pragma code interrupcion = 0x0008
void VectorInterrupcion(void) {
_asm goto ISRRecepcion _endasm
}
#pragma code // Cerramos seccion.-
#pragma interrupt ISRRecepcion
/********************************************************************
* Function: void ISRRecepcion(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: Interrupt Routine
*
* Note: None
*******************************************************************/
void ISRRecepcion(void) {
if (PIR1bits.RCIF == 1) {
getsUSART(Buffer, 3);
Dato = getcUSART(); // Leemos dato recibido.-
kbhit = 1; // Indicamos que se ha recibido un dato.-
PIR1bits.RCIF = 0; // Borramos flag.-
}
}
/********************************************************************
* Function: void main(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: Main program entry point.
*
* Note: None
*******************************************************************/
void main(void) {
OpenUSART(USART_TX_INT_OFF & USART_RX_INT_ON & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, 155); // 19.200 baudios.-
RCONbits.IPEN = 0; // Desabilitamos Prioridades.-
INTCONbits.PEIE = 1; // Habilitamos Interrupcion de perifericos.-
INTCONbits.GIE = 1; // Habilitamos Interrupcion Global.-
putrsUSART("introducir Pasword \r");
while (1) {
ProcessIO();
}
}
/********************************************************************
* Function: void ProcessIO(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This function is a place holder for other user
* routines. It is a mixture of tasks.
*
* Note: None
*******************************************************************/
void ProcessIO(void) {
while (kbhit == 0) {
}; // Esperamos a recibir dato.-
kbhit = 0;
if (strcmp(Buffer, "123") == 0) { //El pasword es 123
putrsUSART("ok \r");
} else {
putrsUSART("fail \r");
}
}
Solo que siempre obtengo falso el resultado, nunca correcto,, que puedo estar haciendo mal???
saludos.
-
Para manejar String el buffer debe contemplar el espacio necesario para guardar el string y el carácter nulo ('\0'). Podes buscar en el foro, hay un tema que trata el tema de arreglo de caracteres, etc.
Saludos!
-
Muchas gracias por tu ayuda suky, buscare el tema que mensionas..
mientras dejo aquí un pantallazo debuggeando el micro y al parecer si me trae bien los valores , es la comparación la que falla.
Pantallazo (https://docs.google.com/open?id=0B1p64iClB1upOFVMRk5wTnZ6Vzg)
saludos.
-
Claro, porque le falta el espacio para el carácter nulo, declara Buffer[4] y seguro se soluciona ;-)
-
Claro, porque le falta el espacio para el carácter nulo, declara Buffer[4] y seguro se soluciona ;-)
eh agregado el espacio para el carácter null en Buffer[4], pero este se le envía desde la terminal o se lo agrego por software ?? no logro mandarlo desde la terminal...
como ago para que la cadena desde la terminal me llegue asi;
Buffer={'1','2','3','\0'};
-
Al momento de realizar la transmisión automaticamente se carga un caracter nulo al final del string
para que quede un poco mas claro si tu transmites 123 automaticamente el siguiente caracter sera un nulo, claro siempre y cuando la informacion que envies no sobrepase el tamaño de tu string.
tambien te aconsejo por seguridad utilizar la funcion memset antes de cada recepción, la cual que sirve para limpiar el contenido de tu string.
ejemplo:
memset(Buffer,0,sizeof(Buffer));
Espero y esto te sirva de algo
Saludos :-)
-
Hola.
Ojo con esa funcion memset ... en algunos micros causa problemas :? ... yo se utilizar un for para limpiar los buffer's desde que tuve problemas con esa funcion ...
Saludos
-
Yo utilizaba el for pero me consumia mas código, he usado esa funcion en Hi-tech y C18 y hasta el momento no me ha causado ningun problema
Saludos
-
Hola
Se me olvidaba :oops: en CCS es que da problemas :lol:
Saludos
-
Solo lo eh podido resolver de la siguiente manera, pero no se si sea la correcta,,
while (kbhit == 0) {}; // Esperamos a recibir dato.-
kbhit = 0;
Buffer[4] = 0;
if (strcmppgm2ram(Buffer, "1234") == 0) {
putrsUSART("Accsess Granted \r\n");
} else {
putrsUSART("Accsess Denied \r\n");
}
Nuevamente no se si el el valor nulo lo envio desde la terminal o lo agrego. un poko de ayuda please :-/
-
Hola amigos!!!
Eh realizado unas modificaciones al programa y me parece que esta funcionando muy bien , de entrada quite el uso de interrupciones en el usart y me esta funcionando mejor (pienso yo) y no se si el usar el usart sin interrupciones es malo?? que piensan?
/********************************************************************
FileName: main.c
Dependencies: See INCLUDES section
Processor: PIC18, PIC24, and PIC32 USB Microcontrollers
Hardware: This demo is natively intended to be used on Microchip USB demo
boards supported by the MCHPFSUSB stack. See release notes for
support matrix. This demo can be modified for use on other hardware
platforms.
Complier: Microchip C18 (for PIC18), C30 (for PIC24), C32 (for PIC32)
********************************************************************/
/** INCLUDES *******************************************************/
#include "HardwareProfile.h"
#include "GenericTypeDefs.h"
#include "string.h"
#include "usart.h"
#include "delays.h"
#include "xlcd.h"
/** CONFIGURATION **************************************************/
#if defined(FOZZ_BOARD) // Configuration bits for PICDEM FS USB Demo Board (based on PIC18F4550)
#pragma config PLLDIV = 3
#pragma config CPUDIV = OSC3_PLL4
#pragma config USBDIV = 2 // Clock source from 96MHz PLL/2
#pragma config FOSC = HSPLL_HS
#pragma config FCMEN = OFF
#pragma config IESO = OFF
#pragma config PWRT = OFF
#pragma config BOR = ON
#pragma config BORV = 3
#pragma config VREGEN = ON //USB Voltage Regulator
#pragma config WDT = OFF
#pragma config WDTPS = 32768
#pragma config MCLRE = ON
#pragma config LPT1OSC = OFF
#pragma config PBADEN = OFF
// #pragma config CCP2MX = ON
#pragma config STVREN = ON
#pragma config LVP = OFF
// #pragma config ICPRT = OFF // Dedicated In-Circuit Debug/Programming
#pragma config XINST = OFF // Extended Instruction Set
#pragma config CP0 = OFF
#pragma config CP1 = OFF
// #pragma config CP2 = OFF
// #pragma config CP3 = OFF
#pragma config CPB = OFF
// #pragma config CPD = OFF
#pragma config WRT0 = OFF
#pragma config WRT1 = OFF
// #pragma config WRT2 = OFF
// #pragma config WRT3 = OFF
#pragma config WRTB = OFF // Boot Block Write Protection
#pragma config WRTC = OFF
// #pragma config WRTD = OFF
#pragma config EBTR0 = OFF
#pragma config EBTR1 = OFF
// #pragma config EBTR2 = OFF
// #pragma config EBTR3 = OFF
#pragma config EBTRB = OFF
#else
#error No hardware board defined, see "HardwareProfile.h" and __FILE__
#endif
/* ** PRIVATE PROTOTYPES ** */
void BlinkBTStatus(void);
void PassOK(void);
void ProcessIO(void);
/* ** Variables de uso general ** */
volatile unsigned char BufferPass [64];
static BOOL BTControl;
BOOL blinkStatusValid = TRUE;
/********************************************************************
* Function: void main(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: Main program entry point.
*
* Note: None
*******************************************************************/
void main(void) {
mInitAllLEDs();
OpenUSART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, 155);
BTControl = 0;
while (BusyUSART());
putrsUSART("\fintroducir Pasword \r\n");
while (1) {
if (BTControl == 1) {
ProcessIO(); //This function is a place holder for other user routines. It is a mixture of tasks.
} else {
PassOK(); //Verificar contraseña
}
}
}
/********************************************************************
* Function: void ProcessIO(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This function is a place holder for other user
* routines. It is a mixture of tasks.
*
* Note: None
*******************************************************************/
void ProcessIO(void) {
//Blink the LEDs according to the USB device status
if (blinkStatusValid) {
BlinkBTStatus();
}
}
/********************************************************************
* Function: void PassOK(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: This function grant acces to the serial control
*
* Note:
*******************************************************************/
void PassOK(void) {
while (!DataRdyUSART());
memset(BufferPass,0,sizeof(BufferPass));
getsUSART(BufferPass, 4);
if (strcmppgm2ram(BufferPass, "1234") == 0) {
while (BusyUSART());
putrsUSART("Accsess Granted \r\n");
BTControl = 1;
} else {
while (BusyUSART());
putrsUSART("Accsess Denied \r\n");
BTControl = 0;
}
}
/********************************************************************
* Function: void BlinkBTStatus(void)
*
* PreCondition: None
*
* Input: None
*
* Output: None
*
* Side Effects: None
*
* Overview: BlinkBTStatus turns on and off LEDs
* corresponding to the control state.
*
* Note: mLED macros can be found in HardwareProfile.h
*******************************************************************/
void BlinkBTStatus(void) {
// No need to clear UIRbits.SOFIF to 0 here.
// Callback caller is already doing that.
static WORD led_count = 0;
if (led_count == 0)led_count = 10000U;
led_count--;
#define mLED_Both_Off() {mLED_1_Off();mLED_2_Off();}
#define mLED_Both_On() {mLED_1_On();mLED_2_On();}
#define mLED_Only_1_On() {mLED_1_On();mLED_2_Off();}
#define mLED_Only_2_On() {mLED_1_Off();mLED_2_On();}
if (BTControl == 1) {
if (led_count == 0) {
mLED_1_Toggle();
mLED_2_Off();
}//end if
}
}
-
No es malo el uso del USART como interrupción, mas bien depende de la aplicación o de la manera que vayas a realizar tu programa. Ya es de cada quien si decide hacerlo por interrupción o por polling....
Yo utilizo las 2 maneras y las dos me funcionan correctamente :P
Saludos
-
Creo que el problema esta en lo que te cito suky. Si envías "1234" en realidad envías 1234 y el \0 al final. Porque es una cadena de caracteres.
5 caracteres en total.
Agrandá el tamaño de Buffer[4] a Buffer[5].
Saludos
Jukinch