PIC18F14K50: Modulos RF 433MHz

Page 1

Por: Omar Gurrola

3/24/13

http://www.proprojects.wordpress.com

PIC18F14K50: Modulos RF 433MHz En esta sección trabajaremos con comunicación inalámbrica por RF a una frecuencia de 433 MHz (frecuencia libre) utilizando dos módulos, uno transmisor y otro receptor únicamente. La ventaja de estos módulos es el costo, los puedes comprar en www.ebay.com por alrededor de $2.00 dólares ambos. Las características de ambos módulos son los siguientes: Caracteristic: Voltaje: Current: Modulation: Speed: Freq. Range:

Transmisor (TX): 3V-12V ≤ 40mA (12V), ≤ 9mA (3V) ASK / OOK ≤ 10Kbps 315MHz – 433.92MHz

Receptor (RX): 5V ≤ 5.5mA ASK / OOK ≤ 9.6Kbps 315MHz – 433.92MHz

Los módulos están acoplados con AC lo que evita que se pueda transmitir un pulso alto por un lapso largo, si se intenta la señal baja después de un corto tiempo, lo que evita que se puedan utilizar protocolos comunes como RS-232 y se tenga que utilizar otros tipos de protocolos que no mantengan la señal en un nivel por mucho tiempo. Para realizar la codificación y decodificación tenemos dos opciones: 1.

Realizar la codificación/decodificación por HW utilizando algún integrado para esta tarea.

2.

Realizar la codificación/decodificación por SW utilizando algún protocolo.

En mi caso no utilizare ningún integrado para codificar/decodificar la señal por que cuestan más que los módulos en sí, por lo que utilizare la codificación “Manchester - G.E. Thomas” para realizar este trabajo en SW, la cual consiste en:  

Para enviar cero “0” se transmite un “01” Para enviar uno “1” se transmite “10”

También tenemos que empaquetar la información para evitar recibir información de otros dispositivos que trabajen bajo la misma frecuencia.


Por: Omar Gurrola

3/24/13

http://www.proprojects.wordpress.com

La trama consistirá de: 1. 2. 3. 4. 5.

Header: Cabecera, sirve para inicializar la transmisión y estabilizar la señal. Device ID: ID del dispositivo, es la dirección del dispositivo y se utiliza para distinguir quien manda el paquete. Data: Datos, será el byte a transmitir. Checksum: Es la suma de todos los bytes transmitidos, se utiliza para verificar que la información recibida esta correcta. End: Final de la transmisión, no se transmite nada por un tiempo definido.

El paquete se verá así:

Para decodificar la señal se utilizara el siguiente algoritmo: 1. 2.

3. 4. 5. 6. 7. 8. 9.

Esperar el bit de inicio “0” (transición de 0 a 1). Para leer cada bit del paquete: a. Esperar 3/4Tbit. b. Leer bit. c. Esperar transición para sincronizar la señal. d. Regresar al paso a). Se deben leer 16 x “1” + “0”, si no es así hay un error en Header. Leer los siguientes 8b + “0” + “1”, si no termina en 0 y 1 hay un error en el Device ID. Si el Device ID no coincide con la del dispositivo TX, hay un error en Device ID. Leer los siguientes 8b + “0” + “1” si no termina en 0 y 1 hay un error en Data. Leer los siguientes 8b + “0” + “1”, si no termina en 0 y 1 hay un error en el Checsum. Si Data no coincide con Checksum, hay un error en Checksum. La recepción se realizó correctamente.

Para probar los módulos debemos realizar dos programas uno para el transmisor y otro para el receptor cada uno con su microcontrolador y su pantalla LCD para mostrar la información. El TX utilizara la pantalla para mostrar cuantos paquetes se han transmitido, se actualizara cada 50 paquetes y el RX la utilizara para mostrar cuantos paquetes ha recibido correctamente y cuantos con errores, actualizara la pantalla cuando presionemos un interruptor para evitar perder paquetes por actualizar cierto tiempo.


Por: Omar Gurrola

3/24/13

http://www.proprojects.wordpress.com

TX main.c /* * Copyright (c) 2011-2013, http://www.proprojects.wordpress.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1.- Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2.- Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /********************************************************************************** * Author: Omar Gurrola * Site: http://www.proprojects.wordpress.com * Processor: PIC18 * Compiler: C18 v3.45 * File Name: main.c * Description: Main program * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Rev. Date Comment * 1.0 04/01/12 Initial version * 1.1 01/29/13 Remove ISR prototipes, they are declared in hid_bl.h *********************************************************************************/ /** INCLUDES *******************************************************/ #include <p18f14k50.h> #include "pic18f14k50_cbits.h" #include "pic18f14k50_io.h" #include "stdvars.h" #include "wait.h" #include "rfman.h" #include "HD44780.h" #include <stdio.h> /** DECLARATIONS ***************************************************/ #pragma code // Forces the code below this line to be put into the code section (Memory Adress >= 0x'REMDIR'02A) /** Interrupt Service Routines (ISR)********************************/ #pragma interrupt HighPriorityISR void HighPriorityISR (void){ //Check which interrupt flag caused the interrupt. //Service the interrupt //Clear the interrupt flag //Etc. } //This return will be a "retfie fast", since this is in a #pragma interrupt section #pragma interruptlow LowPriorityISR void LowPriorityISR (void){ //Check which interrupt flag caused the interrupt. //Service the interrupt //Clear the interrupt flag //Etc. }

//This return will be a "retfie", since this is in a #pragma interruptlow section

void main(void){ u16 c; u16 t = 0; s8 String[17]; u16 Update = 1; OSCCONbits.IRCF = 0b110; OSCTUNEbits.SPLLEN = 1; OpenInRA5(); lcd_initialize(); RFInit(); #define DID #define DATA

0xAA 0xAA

// Poscaler selected to 8 MHz // PLLx4 Enable System FQ = 32 MHz


Por: Omar Gurrola #define PKGS

3/24/13

http://www.proprojects.wordpress.com

1000

while(true){ lcd_goto(1,1); lcd_write_pgm("Waiting Start..."); if(ReadRA5() == 1){ Waitmsx(50); if(ReadRA5() == 1){ lcd_goto(1,1); lcd_write_pgm("Sending Data...."); for(c = 0; c < PKGS; c++){ RFStartTX(DID); RFSend(DATA); RFEndTX(); // Update screen Total/Sended t++; if(Update == 50){ Update = 0; sprintf(String,"%6hu -- %6hu",PKGS,t); lcd_goto(2,1); lcd_write(String); } Update++; } } } } // end while } // end main() RX main.c /* * Copyright (c) 2011-2013, http://www.proprojects.wordpress.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1.- Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2.- Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /********************************************************************************** * Author: Omar Gurrola * Site: http://www.proprojects.wordpress.com * Processor: PIC18 * Compiler: C18 v3.45 * File Name: main.c * Description: Main program * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Rev. Date Comment * 1.0 04/01/12 Initial version * 1.1 01/29/13 Remove ISR prototipes, they are declared in hid_bl.h *********************************************************************************/ /** INCLUDES *******************************************************/ #include <p18f14k50.h> #include "pic18f14k50_cbits.h" #include "pic18f14k50_io.h" #include "stdvars.h" #include "wait.h" #include "rfman.h" #include "HD44780.h" #include <stdio.h> /** PROTOTYPES *****************************************************/ void ResetStadistics(void); void UpdateStadistics(void); /** VARIABLES ******************************************************/ /** DECLARATIONS ***************************************************/


Por: Omar Gurrola #pragma code

3/24/13

http://www.proprojects.wordpress.com

// Forces the code below this line to be put into the code section (Memory Adress >= 0x'REMDIR'02A)

/** Interrupt Service Routines (ISR)********************************/ #pragma interrupt HighPriorityISR void HighPriorityISR (void){ //Check which interrupt flag caused the interrupt. //Service the interrupt //Clear the interrupt flag //Etc. } //This return will be a "retfie fast", since this is in a #pragma interrupt section #pragma interruptlow LowPriorityISR void LowPriorityISR (void){ //Check which interrupt flag caused the interrupt. //Service the interrupt //Clear the interrupt flag //Etc. }

//This return will be a "retfie", since this is in a #pragma interruptlow section

u16 noe,hdre,dide,datae,cse,toe; s8 String[21]; void main(void){ u8 devid, data, result; OSCCONbits.IRCF = 0b110; OSCTUNEbits.SPLLEN = 1;

// Poscaler selected to 8 MHz // PLLx4 Enable System FQ = 32 MHz

OpenInRA4(); OpenInRB4(); lcd_initialize(); RFInit(); #define SW1() #define SW2()

PORTAbits.RA4 PORTBbits.RB4

#define DID #define DATA

0xAA 0xAA

ResetStadistics(); while(true){ result = RFReceive(&devid,&data); if(result == RF_OK){ if(devid != DID) result = RF_DID_ERROR; if(data != DATA) result = RF_DATA_ERROR; } switch(result){ case RF_OK: noe++; break; case RF_HDR_ERROR: hdre++; break; case RF_DID_ERROR: dide++; break; case RF_DATA_ERROR: datae++; break; case RF_CS_ERROR: cse++; break; } if(SW1() == 1){ Waitmsx(30); if(SW1() == 1){ ResetStadistics(); } } if(SW2() == 1){ UpdateStadistics(); } } // end while } // end main() void ResetStadistics(void){ noe = hdre = dide = datae = cse = toe = 0; UpdateStadistics(); } void UpdateStadistics(void){


Por: Omar Gurrola

3/24/13

lcd_goto(1,1); lcd_write_pgm(" Estadisticas de RX "); lcd_goto(2,1); sprintf(String,"OK: %.5hu HD: %.5hu",noe,hdre); lcd_write(String); lcd_goto(3,1); sprintf(String,"ID: %.5hu DT: %.5hu",dide,datae); lcd_write(String); lcd_goto(4,1); sprintf(String,"CS: %.5hu TO: %.5hu",cse,toe); lcd_write(String); }

Diagrama esquemรกtico del TX:

Diagrama esquemรกtico del RX:

http://www.proprojects.wordpress.com


Por: Omar Gurrola Circuito armado:

3/24/13

http://www.proprojects.wordpress.com


Por: Omar Gurrola

3/24/13

http://www.proprojects.wordpress.com

Pruebas: Las pruebas consisten en enviar 1000 paquetes a las siguientes distancias: 1m, 5m, 10m, 50m y 100m, utilizando 12v en el transmisor y ambos módulos con antenas de espiral para máxima potencia. El objetivo consiste en determinar el % de perdida en cada distancia y graficarla en Excel. 1.

En la primera prueba se utilizaron antenas de 37cm de largo en forma de espiral tanto para el TX como el RX. Como se puede observar en la gráfica la distancia máxima sin tanta perdida fue de 5m.

2.

En la segunda prueba se utilizaron antenas de 32cm para el TX y 25cm en el RX en forma de espiral ambas. Como se puede observar en la gráfica la distancia máxima sin tanta perdida aumento a 10m.


Por: Omar Gurrola 3.

3/24/13

http://www.proprojects.wordpress.com

En la última prueba se utilizaron antenas de 32cm para el TX y 25cm en el RX en forma de espiral ambas, con la diferencia de que el TX fue estirado 15cm y el RX 11cm. Como se puede observar en la gráfica la distancia máxima sin tanta perdida aumento a 50m.

Estoy seguro que se puede mejorar la señal con otros tipos de antenas, pero por cuestión de tiempo fue lo único que pude probar.


Por: Omar Gurrola

3/24/13

http://www.proprojects.wordpress.com

Referencias 

Microchip, “PIC18F/LF1XK50 Data Sheet”, 2010, http://ww1.microchip.com/downloads/en/DeviceDoc/41350E.pdf

Peter JAKAB, “Infra/radio remote control transmitter/receiver with PIC”, 1999 http://jap.hu/electronic/codec-v4.0.html

Winpicprog, “PIC Tutorial Twelve - RF remote control”, 2013 http://www.winpicprog.co.uk/pic_tutorial12.htm

great-digital, “New 433Mhz RF Transmitter Module And Receiver Link Kit For Arduino/ARM/MCU WL”, 2013 http://www.ebay.com/itm/New-433Mhz-RF-Transmitter-Module-And-Receiver-Link-Kit-For-Arduino-ARM-MCUWL-/380584441506?pt=LH_DefaultDomain_0&hash=item589c99b6a2

Philippe Larcher, “AN2358 – Manchester Decoder Using PSoC”, 2007 http://www.eetasia.com/STATIC/PDF/200805/EEOL_2008MAY23_EMS_AN_03.pdf?SOURCES=DOWNLOAD

Wikipedia, “Manchester code”, 2013 http://en.wikipedia.org/wiki/Manchester_code


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.