Buenas,
Estuve mejorando un poco el codigo.
Logre que se vea la informacion correctamente pero a veces es necesario resetear la terminal en el Hyperterminal. No se a que se debe ese problema.
Este codigo es para conectarse al RN171 a traves de un pic ( 18F26J50 ) por RS232 y obtener informacion de algun servido. Usando el compilador CCS.
Hay una pagina web, que esta el codigo PHP abajo. donde modifica valores de una base de datos. El modulo hace una consulta a esa base de datos y manda el dato al PIC que maneja I/O.
Al ingresar al CMD sale el siguiente error ERR: ?-Cmd.
Si alguien tiene un codigo mejor o algo para poder mejorarlo seria bueno.
#include <18F26J50.h> // -> PCH
#device adc=16
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <pic18_usb.h> //Microchip PIC18Fxx5x Hardware layer for CCS's PIC USB driver
#include <usb_cdc.h> // Descripción de funciones del USB.
#include <usb_desc_cdc.h> // Descriptores del dispositivo USB.
#FUSES NOWDT //No Watch Dog Timer
//#FUSES NODEBUG //No Debug mode for ICD
#FUSES NOXINST //Extended set extension and Indexed Addressing mode disabled (Legacy mode)
#FUSES NOPROTECT //Code not protected from reading
#FUSES NOFCMEN
#FUSES NOIESO
#FUSES NOCPUDIV
//#FUSES HSPLL //High speed Osc (> 4mhz for PCM/PCH) (>10mhz for PCD)
#FUSES PLL3
#FUSES RTCOSC_INT
#use delay(crystal=12Mhz, clock=48Mhz)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, parity=N ,stop=1, bits=8, stream = RN171) //// RS232 Configuration with RN171
#use rs232(baud=9600, xmit=PIN_C4, rcv=PIN_C5, parity=N, stop=1, bits=8, stream = PC) // RS232 Configuration with PC
#use standard_io(c)
#use fast_io(b)
#define CTS PIN_B2 //wake RN171 to receive data RX GPIO_12 clear to send
#define RTS PIN_B1 //wake RN171 to receive data RX GPIO_13 ready to send
#define BUFFER_SIZE 150
char buffer[BUFFER_SIZE];
char palabra[BUFFER_SIZE];
char delimitar[] = "|||";
int next_in = 0;
int next_out = 0;
char *tokens[10];
int segundos=0 , segundos_ant = 0 ; // A running seconds counter
//int8 int_count = 0; // Number of interrupts left before a second has elapsed
int cant_tokens=0;
//Functions
void inicbuff(void){ // Inicia a \0 cbuff -------------------
int i;
for(i=0;i < BUFFER_SIZE;i++){ // Bucle que pone a 0 todos los
buffer[i]=0x00; // caracteres en el buffer
}
}
void inicpalabra(void){ // Inicia a \0 cbuff -------------------
int i;
for(i=0;i < BUFFER_SIZE;i++){ // Bucle que pone a 0 todos los
palabra[i]=""; // caracteres en palabra
}
}
#define bkbhit (next_in!=next_out)
BYTE bgetc()
{
BYTE c;
while(!bkbhit) ;
c = buffer[next_out];
next_out=(next_out+1) % BUFFER_SIZE;
return(c);
}
int almacenarDatos(char *string, char *delim) //, char *tokens[])
{
int count=0;
char *stringp;
stringp = string;
char* token;
for (token = strtok(stringp, delim); token; token = strtok(NULL, delim))
{
tokens[count]= token;
count++;
}
return count;
}
void mostrarDatos( int cant) //char *dat[],
{
int i;
//printf(usb_cdc_putc,"\n\rcount %d, %s , %s , %s , %s", cant, tokens[0], tokens[1], tokens[2], tokens[3]);
for (i = 0; i < cant; i++) // condicion final MIENTRAS QUE i sea menor a count
printf(usb_cdc_putc,"\n\r %d/%d - %s ",i,cant, tokens[i]);
}
/*
ps:Pre escaler 256
tinst:4/frecuencia del cristal (4/4000000) PLL3 -> 12000000/3 = 4000000 Hz
carga:Valor a cargar en el timer 0
temp: tiempo deseado a temporizar 1 seg
*
* temp = tinst * 256 * (65536 - carga)
* 1seg = 4/4000000 * 256 * (65536 - carga)
*
*/
//interrupts
#int_timer0
void TIMER0_isr(void)
{
segundos++;
if(segundos > 59)
segundos=0;
}
#int_rda
void serial_isr() {
int t=0;
buffer[next_in]= getch(RN171);
t=next_in;
next_in=(next_in+1) % BUFFER_SIZE;
if(next_in==next_out) {
next_in=t; // Buffer full !!
}
}
void main() {
//inputs 1, outputs 0
SET_TRIS_C( 0b11010111 ); // pone C como entradas y C4 y C6 como salidas (Sensor)
SET_TRIS_B(0x00 ); //Configuramos el puerto b como salidas
output_b(0x00);
usb_cdc_init(); // Configuramos al puerto virtual.
delay_ms(100);
usb_init(); // Inicializamos el stack USB.
usb_task(); //habilita periferico usb e interrupciones
usb_wait_for_enumeration(); //esperamos hasta que el PicUSB sea configurado por el host
while(!usb_cdc_connected()) {} // espera a detectar una transmisión de la PC
inicbuff(); // Borra buffer al inicio
inicpalabra();
setup_oscillator (OSC_PLL_ON); //IMPORTANTIIIISIMO SI NO NO FUNCIONA USB NI USART
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256);
set_timer0(3906);
//interrupts
enable_interrupts(int_rda);
enable_interrupts(INT_TIMER0);
enable_interrupts(global);
output_high(CTS); //ready to send
printf(usb_cdc_putc,"\n\r :--------------Start-----------------:\n\r");
while(TRUE)
{
delay_us(1000);
if(palabra[0]!=0x00)
{
buffer[BUFFER_SIZE-1]='\0';
palabra[BUFFER_SIZE-1]='\0';
//printf(usb_cdc_putc,"\n\r --------------PALABRA:%S", palabra); //ver en la PC lo que se manda al modulo
delay_ms(100);
fprintf(RN171,"%S",palabra); // manda la palabra del teclado al modulo
delay_ms(100);
inicpalabra();
}
delay_ms(100);
while(bkbhit)
{
putc( bgetc() );
}
delay_us(100);
usb_task();
if( !bkbhit )
{
cant_tokens = almacenarDatos(buffer,delimitar);
if (usb_enumerated())
{
if (usb_cdc_kbhit())
{
get_string_usb(palabra,BUFFER_SIZE); //obtiene la palabra escrita en el teclado
}
}
}
if(segundos != segundos_ant)
{
delay_us(50);
mostrarDatos(cant_tokens);
segundos_ant=segundos;
}
}
}
<?php
//data format -> |||tipo-valor|||tipo-valor|||tipo-valor|||tipo-valor|||
date_default_timezone_set('America/Argentina/Buenos_Aires');
include_once 'action/conexion.php';
$sql = "SELECT * FROM registros order by id desc limit 1";
$con=conexion();
$result= mysqli_query($con,$sql);
$count=0;
while($dato = mysqli_fetch_object($result))
{
echo '||| TIEMPO='.$dato->temperatura;
echo '||| MODO='.$dato->modo;
echo '||| VELOCIDAD='.$dato->velocidad;
echo '||| DURACION='.$dato->duracion;
//echo ($dato->fecha_inicio=='0000-00-00 00:00:00')?'':'|Fi='.$dato->fecha_inicio;
//echo ($dato->fecha_fin=='0000-00-00 00:00:00')?'':'|Ff='.date("F j, g:i a");
echo "||| \n\r";
$count++;
}
if($count==0)
echo "\n\rNo hay registros";
?>