Home     Contact     Forum     Projects     Experiments     Circuits     Theory     BLOG     PIC Tutorials     Time for Science     RSS     Terms of services     Privacy policy  
   
 Home     Forum     Projects     Experiments     Circuits     Theory     BLOG     PIC Tutorials     Time for Science   

Author Topic: TUTORIAL: Project PicUSB almost ready PIC <-> RF <-> PIC <-> USB <-> PC  (Read 14210 times)

0 Members and 1 Guest are viewing this topic.

matheuslps

  • Guest
Project PicUSB: PIC<-->RF<-->PIC<-->USB<-->PC
by MatheusLPS

Hello people of the forum! How are you? So, I have good news for those who enjoy a microcontroller and do not know turn it on PC through USB. The problems are over!

OBS 1: This is a project that a made 1 year before and decided to share with you. First because I want to share and I saw a reply today on youtube from Kam on this video:

http://www.youtube.com/watch?v=cJq-PlkIb0w

I believe he is also interested in the subject.

OBS 2: I am from Brazil and english is not my mother language. Sorry for any mistake.
OBS 3: The coments on the images was writen in portuguese, that is my language. I am too lazy to recoment in english... :d
OBS 4: All the images are clickable to a large version.

Attention:

This project is not aimed at those completely new to the world of microcontrollers. You need a certain degree of knowledge to be able to go over the problems that may occur. And remember: "Uncle GOOGLE is there to remedy the most questions!"

So, I am developing a project in college where I need to use a microcontroller and connect it somehow to my computer to view information. This pre-project aims to introduce the concept of how to make the data exchange between a microcontroller and a computer via USB.

Specification of component used (USB)

Currently ports like RS232, serial, and other are no longer used, because they are considered outdated. The USB protocol takes advantage as regards the speed of information transfer and the ease of connection to the system, although this feature is quite complex as regards the control software. Much of this work is to make the PC recognizes a valid USB device.

Methodology

At first there was the idea of ​​using the computer's parallel port to communicate with the PIC, however, considering that a notebook does not have such a connection, it was decided to examine other alternatives. Faced with this limitation it employed the USB components and microcontrollers to remedy the problem.

Was used as a methodology the textbook USB Complete Third Edition, Everything You Need to Develop Custom USB Peripherals by Jan Axelson writing. It is noticed that the book is the bible for those who want to start using USB, contains many examples and source code.
Unfortunately this is not the case, even wanting to do something new, do not want to reinvent the wheel. The USB protocol already exists for a while, just wanna know how it's done something more superficial. And the book covers subject matter that we decided not to seek.

Starting from the initial proposal, it was an intense search to find material that would unite the elements PIC, USB and CCS Compiler which is already being used. Unfortunately, the material on the subject is scarce, even more of a theme so specific. Luckily it was found in an internet forum that helped in determining the type of PIC to use.

It was with great difficulty that I found a forum in Spanish, which helped me a lot:

http://www.todopic.com.ar/foros/index.php?PHPSESSID=4c610a6d668ecb0594cd26c5419195dc&topic=2260.0

This guy built a protocol in 2005 that helped me understand how a simple PIC can be connected to the PC.

He placed at the disposal of all your files with source code so that all people could benefit from. It was with this intention that I decided to post my experience so others do not have as much difficulty as I had in doing the project. Since the idea to the stage that I am, there were 2 months of research.

Block diagram of the Initial Project

The diagram can be seen in the image below:



As you can see above, the aim of the project is to control a car via the computer, built with two servo motors. This car can send various information such as: temperature, relative humidity and so on.

In this post I will give only an idea of the project, later on, I will give more detailed information about the construction of both hardware and software that was the trickiest part.

Tools Required

In this part I will quote the necessary software for the project to be executed.

Microsoft Visual C # 2010 Express: The author used the 2005 Express, however, that all the functions added work, you need the 2010 Express. It's free!

Pic C Compiler: Is the CCS. I used this because I'm used to and the bibliography found also wore it. I DO NOT KNOW USE other compilers!

Proteus ISIS: To test our project, we need a simulator. And that I recommend.

32bit Operating System: The Proteus USB drivers do not work on 64bit systems. And the PIC USB drivers do not. I use windows 7 64 bit and did not want to install another OS just to test the circuits. Then I used a virtual machine resource. I installed XP SP3 and Windows 7 32bit and it ran smoothly.

EDIT: Later, I was able to use 64bits operation system.....

How It Works

At first I have a PIC connected to the computer and some leds connected to the microcontroller to test.

The PIC circuit is as follows:



It is noticed that the hardware part is quiet, few components.

There is a pic of the left that is connected to PC via USB, the PIC on the right pic is on the car. Realize that they are connected only by one wire, simulating an RF connection via RS232. The LCD is just as debugger to certify that the information is coming.

We have to turn it on PC and it should be recognized as a USB device:



In the photo above, I started testing with a 18F2550. Now I have an 18F4550 and it works!

Now you must create an object-oriented software that controls our PIC. This is done in Microsoft Visual C # 2010 Express.

As a test, I made ​​a program based on the J1M, author of the original structure. This program turns on / off LED red, blue, read the temperature using an LM35 and shows in a graph. Ahhh, I left in the program a function that takes two integers, send them to the PIC and the PIC  returns the sum. Result is shown on the screen.

Screenshot of Sofware:



Pictured above is a screenshot of the system running on Windows XP installed on a virtual machine. In windows 7 worked well!

I will not post the source code of software for a while because it will overload the post.

More info is coming....
« Last Edit: May 02, 2012, 07:02:00 AM by MatheusLPS »

kam

  • Administrator
  • Hero Member
  • *****
  • Posts: 1849
Matheus, you're the man! I know a few people who will run to get this 18F4550... I've got myself some 18F chips to make similar USB connection, but i had so little time and so many things to do... Thanks ! 8) 8) 8)

Thumbs up

George

  • Jr. Member
  • **
  • Posts: 73
There is also microchip MCP2200 - which is a USB - UART chip

matheuslps

  • Guest
Thanks for the replies...

Moving on...

NOTE: This project uses the USB port in full, without emulation of a COM port.

Step 1: Download the source files, both of the two PICs, the application that controls them and the necessary files:

http://www.4shared.com/file/4GoCckEA/Trabalho_Final.html

First of all, we need a PIC with native support for USB. For this project I chose the 18F4550 because it has 40 pins, which is more than enough, good memory and USB support.

For this project, I have this block diagram:



Here we have a PIC connected to USB, the crystal of 12MHz, 15pF capacitors in the crystal, a 47uF capacitor on pin 18 (VUSB), a resistor in MCLR, a temperature sensor LM35, a red LED to indicate that the PIC is running but was not recognized as a valid device on your computer, a green LED for when we install the driver, it lights up indicating that the device was enumerated by windows.

The pic on the right I'll explain later.

In order that the PIC is recognized by windows, we must program it with the following code written in CCS. Note that I did not program all the code. I used the one that I found on www.todopic.com.ar and modified to my needs. The owner of the code did openly. So the comments are in Spanish.

Code: [Select]
/////////////////////////////////////////////////////////////////////////
////                            PicUSB.c                             ////
////                                                                 ////
//// Este ejemplo muestra como desarrollar un sencillo dispositivo   ////
//// USB con el PIC18F2550, aunque puede ser facilmente adaptado     ////
//// para la serie 18Fxx5x. Se suministra el PicUSB.exe, así como    ////
//// su código fuente para Visual C# 2005, podréis encontrar tb      ////
//// los drivers para el dispositivo. No se suministra esquema de    ////
//// conexión puesto que está pensado para ser usado en el GTP USB,  ////
//// cualquiera de las tres versiones disponibles, si aun no teneis  ////
//// el programador, podeis utilizar el esquema de esse proyecto.     ////
////                                                                 ////
//// Cuando el dispositivo sea conectado al PC, saldrá el asistente  ////
//// para la instalación del driver. Instala el suministrado junto   ////
//// a este ejemplo, lo encontrareis dentro de la carpeta Driver.    ////
//// Una vez instalado podreis usar el PicUSB.exe para encender o    ////
//// apagar el led bicolor del GTP USB, y para realizar la suma de   ////
//// dos números introducidos.                                       ////
////                                                                 ////
//// Realizado con el compilador CCS PCWH 3.227                      ////
////                                                                 ////
//// Por: Jaime Fernández-Caro Belmonte        hobbypic@hotmail.com  ////
////                                                                 ////
//// http://www.hobbypic.com                                         ////
/////////////////////////////////////////////////////////////////////////
#include <18F4550.h>
#device adc=10
#define WireTX PIN_C6 // <--------- C 6
#define WireRX PIN_C7
#fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL3,CPUDIV1,VREGEN
#use delay(clock=48000000)
#use rs232(baud=9600,xmit=WireTX , rcv=WireRX ,ERRORS , STREAM=Wireless )

/////////////////////////////////////////////////////////////////////////////
//
// CCS Library dynamic defines.  For dynamic configuration of the CCS Library
// for your application several defines need to be made.  See the comments
// at usb.h for more information
//
/////////////////////////////////////////////////////////////////////////////
#define USB_HID_DEVICE     FALSE             //deshabilitamos el uso de las directivas HID
#define USB_EP1_TX_ENABLE  USB_ENABLE_BULK   //turn on EP1(EndPoint1) for IN bulk/interrupt transfers
#define USB_EP1_RX_ENABLE  USB_ENABLE_BULK   //turn on EP1(EndPoint1) for OUT bulk/interrupt transfers
#define USB_EP1_TX_SIZE    4                 //size to allocate for the tx endpoint 1 buffer
#define USB_EP1_RX_SIZE    8                 //size to allocate for the rx endpoint 1 buffer


/////////////////////////////////////////////////////////////////////////////
//
// If you are using a USB connection sense pin, define it here.  If you are
// not using connection sense, comment out this line.  Without connection
// sense you will not know if the device gets disconnected.
//       (connection sense should look like this:
//                             100k
//            VBUS-----+----/\/\/\/\/\----- (I/O PIN ON PIC)
//                     |
//                     +----/\/\/\/\/\-----GND
//                             100k
//        (where VBUS is pin1 of the USB connector)
//
/////////////////////////////////////////////////////////////////////////////
//#define USB_CON_SENSE_PIN PIN_B2  //CCS 18F4550 development kit has optional conection sense pin

/////////////////////////////////////////////////////////////////////////////
//
// Include the CCS USB Libraries.  See the comments at the top of these
// files for more information
//
/////////////////////////////////////////////////////////////////////////////
#include <pic18_usb.h>     //Microchip PIC18Fxx5x Hardware layer for CCS's PIC USB driver
#include <PicUSB.h>         //Configuración del USB y los descriptores para este dispositivo
#include <usb.c>           //handles usb setup tokens and get descriptor reports


/////////////////////////////////////////////////////////////////////////////
//
// Al conectar el PicUSB al PC encendemos el Led Rojo hasta que el dispositivo
// halla sido configurado por el PC, en esse momento encederemos el Led Verde.
// Esperaremos hasta que se reciba un paquete proveniente del PC. Comprobaremos
// el primer byte del paquete recibido para comprobar si queremos entrar en el
// modo Suma, donde se realizará una suma de dos operandos, que corresponderan
// con los dos bytes restantes del paquete recibido; una vez realizada la suma
// enviaremos el paquete con el resultado de vuelta al PC. Si entramos en el
// modo Led comprobaremos el segundo byte del paquete recibido para comprobar
// si deberemos apagar los leds, encender el verder o el rojo.
//
/////////////////////////////////////////////////////////////////////////////

#define LED_OK           PIN_B6
#define LED_FAIL         PIN_B7
#define LED_ON           output_high
#define LED_OFF          output_low

int periodo;
int ciclo1=0;
int ciclo2=0;
int ciclo3=0;

#define modo      recibe[0]
#define param1    recibe[1]
#define param2    recibe[2]
#define param3    recibe[3]       
#define param4    recibe[4]
#define resultado envia[0]
#define barra     send[0]
#define status    send2[0]

/*=====================
A interrupção:
=======================*/

#int_timer1
void TIMER1_isr (void)
{     
   set_timer1(65480);                             //Preload do timer1
   
/*=====================
Testes para ciclo = 0:
=======================*/
   
   if (ciclo1 == 0)
   {
      output_low (PIN_B0);
   }
   if (ciclo2 == 0)
   {
      output_low (PIN_B1);
   }
   if (ciclo3 == 0)
   {
   output_low (PIN_B2);
   }

/*==============================
Já que o ciclo é diferente de 0:
================================*/
   if (periodo <255)
   {
      If (periodo < ciclo1)
      {
         output_high (PIN_B0);
      }
      else
      {
         output_low (PIN_B0);
      }
     
         
       If (periodo < ciclo2)
      {
         output_high (PIN_B1);
      }
      else
      {
         output_low (PIN_B1);
      }
     
       If (periodo < ciclo3)
      {
         output_high (PIN_B2);
      }
      else
      {
         output_low (PIN_B2);
      }
     
   }
   else if (periodo == 255)
   {
      output_high (PIN_B0);
      output_high (PIN_B1);
      output_high (PIN_B2);
      periodo=0;
   }   
   periodo++;   
}

void main(void) {
   
   int8 recibe[5];                  //declaramos variables
   int8 envia[2];
   int8 send[1]; 
   int8 send2[1];
   int16 adc=0;

   LED_OFF(LED_OK);                   //encendemos led rojo
   LED_ON(LED_FAIL);

   usb_init();                      //inicializamos el USB 
   
   setup_adc_ports(AN0);         //Configura canais analógico
   setup_adc(ADC_CLOCK_INTERNAL);    //De acordo com relógio interno.
   
   /*SETUP_TIMER_1 (T1_INTERNAL|T1_DIV_BY_2);       //Configurar timer1 para clock iterno/8
   enable_interrupts (INT_TIMER1);                //Habilitar Interrupções
   enable_interrupts (global);*/

   usb_task();                      //habilita periferico usb e interrupciones
   usb_wait_for_enumeration();      //esperamos hasta que el PicUSB sea configurado por el host
   
   /*SETUP_TIMER_1 (T1_INTERNAL|T1_DIV_BY_2);       //Configurar timer1 para clock iterno/8
   enable_interrupts (INT_TIMER1);                //Habilitar Interrupções
   enable_interrupts (global);*/

   LED_OFF(LED_FAIL);
   LED_ON(LED_OK);                    //encendemos led verde

   while (TRUE)
   {
      if(usb_enumerated())          //si el PicUSB está configurado
      {
         if (usb_kbhit(1))          //si el endpoint de salida contiene datos del host
         {
           
            usb_get_packet(1, recibe, 5); //cojemos el paquete de tamaño 3bytes del EP1 y almacenamos en recibe           
           
            if (modo == 0) // Modo_Suma
            {
               resultado = param1 + param2;  //hacemos la suma               
               usb_put_packet(1, envia, 2, USB_DTS_TOGGLE); //enviamos el paquete de tamaño 1byte del EP1 al PC
            }

            if (modo == 1) // Modo_Carro
            {
               if (param1 == 0)
               {                   
                  fputc('U',Wireless);
                  delay_ms(20);
                 
               }
               
               if (param1 == 1)
               {
                  fputc('R',Wireless);
                  delay_ms(20);
               
               }
               
               if (param1 == 2)
               {
                  fputc('D',Wireless);
                  delay_ms(20);
               
               }
               
               if (param1 == 3)
               {
                  fputc('L',Wireless);
                  delay_ms(20);
               }
               
               if (param1 == 4)
               {
                  fputc ('S',Wireless);
               }
            }
           
            if (modo == 2) // Envio da Temperatura
            {
               set_adc_channel(0);           //Habilitación canal0
               delay_us(20);                 
               adc = read_adc();
               barra=((5*adc*100)/1024);
               usb_put_packet(1, send, 1, USB_DTS_TOGGLE); //enviamos el paquete de tamaño 1byte del EP1 al PC
            }
            if (modo == 3) //Modo PWM
            { 
               if (param1 == 1)  //pwm ativado
               {                 
                  ciclo1=param2;
                  ciclo2=param3;
                  ciclo3=param4;
               }
            }
           
            if (modo == 4)
            {
               status=1;
               usb_put_packet(1, send2, 1, USB_DTS_TOGGLE); //enviamos el paquete de tamaño 1byte del EP1 al PC
            }
           
         }
      }
   }
}

For those who already program in CCS, it will be easier to understand the code as simple.

But I'll explain a bit:

First is declared all information in the USB connection, the variables and finally the code begins.

In my code that was adapted, the goal is to receive commands from the computer and transmit them to the other PIC by RS232 to control the L293 which is a dual H-bridge. I know the second pic is oversized for this task, but since he had one left here, I used it.

In the topic title says I use RF modules, yes, I tried but gave me some problems and I left to do with the RF next semester, since it was only an extra. With just a wire between pins TX and RX, run nice.

In addition to this main task, the 1st pic is USB, receives a request every 1s from PC and returns the value of temperature that is acquired through the LM35.

There is also a routine three PWM channels by software, however when it is activated, the PIC loses the USB connection. This part was to be developed in the next semester in college too. The three channels work, but the USB goes away.

Once you program the PIC and connect the USB window is displayed to install the driver. Note that the windows 64bit driver does not work. In windows 7 32 bit, the project worked for a while, then stopped and have not figured out why. Only fully worked on windows XP.

Driver installed, the PIC is recognized and listed as a valid USB device.

To send information and receive data, we need an application. Mine was written in Microsoft Visual Studio C #. You find the necessary files in the link up there. See a SS application:



To make it work, you need to install Net Framework 4.0. Can be found on the microsoft site.

You can check out the video of the project in operation (Audio in portuguese). You can just jump to 2:10.

EDIT:

I added subtitle to the video now.... enjoy....

http://www.youtube.com/watch?v=GjACB0RiuBQ

For now it is. This is not really a tutorial step by step. Only the information that you need and are not easily to find.

EDITÇ

How I made the ugly car

http://img84.imageshack.us/img84/4582/foto1kf.jpg
http://img146.imageshack.us/img146/6056/foto2we.jpg
http://img196.imageshack.us/img196/9327/foto3dt.jpg
http://img225.imageshack.us/img225/1781/foto4uta.jpg
http://img109.imageshack.us/img109/7808/foto5xpy.jpg
http://img713.imageshack.us/img713/7978/foto6o.jpg
http://img232.imageshack.us/img232/9986/foto7x.jpg
http://img233.imageshack.us/img233/7356/foto8h.jpg
http://img718.imageshack.us/img718/9939/foto9b.jpg
http://img339.imageshack.us/img339/2076/foto10aa.jpg
http://img90.imageshack.us/img90/4104/foto11m.jpg
http://img155.imageshack.us/img155/1633/foto12cy.jpg
http://img818.imageshack.us/img818/723/foto13j.jpg
http://img524.imageshack.us/img524/967/foto14s.jpg
http://img814.imageshack.us/img814/9638/foto15jf.jpg
http://img560.imageshack.us/img560/9261/foto16u.jpg
http://img406.imageshack.us/img406/6263/foto17c.jpg
http://img80.imageshack.us/img80/1184/foto18wl.jpg
http://img339.imageshack.us/img339/3703/foto19i.jpg
http://img98.imageshack.us/img98/4315/foto20r.jpg
http://img98.imageshack.us/img98/9053/foto21a.jpg
http://img339.imageshack.us/img339/8643/foto22aw.jpg
http://img192.imageshack.us/img192/8457/foto23a.jpg
http://img840.imageshack.us/img840/5983/foto24.jpg
http://img204.imageshack.us/img204/5817/foto25b.jpg
http://img233.imageshack.us/img233/4420/foto26q.jpg

Add more stuff later on.

EDIT

Fixing english mistakes....
« Last Edit: May 03, 2012, 05:03:48 AM by MatheusLPS »

kam

  • Administrator
  • Hero Member
  • *****
  • Posts: 1849
heh! i didn't noticed before that the car has tracks! its not a car, its a TANK! T34 !!!

matheuslps

  • Guest
Well I am planning to build the second version of the car (tank) with better motors and better structure.... add the RF link that is know workin like a charm....

I have 8 (eight) stepper motors here.

Before that i will remake the circuits to put on the article that I am wiriting for the site.

Look that the circuit I use here are capped because I use the simulator and they do not need to be complete...

wait.......