mercredi 25 janvier 2012

UART and RS232 communication

Hello,
today I'm going to show you how to communicate through uart with the RS232 protocol.
how to send and extract data.
let's start with the sending.
with Mikroc you can send to types of data (character and text).
A character can have a value from 0 to 255 but a text is a string of characters.
To do so we need to call the "UART library" from Mikroc

This program sends a character (or a number less then 256) if a request was demanded;

unsigned char read=0
Void main(){
     uart1_init(9600);
while(1){
   if (uart1_data_ready()==1){
       read=uart1_read();
      uart1_write(read);
 }
}
}

this program read a string of characters then resend this string
char txt[120];
void main(){
   uart1_init(9600);
while(1){
    uart1_read_text(txt,"#" ,255);
uart1_write(10);
uart1_write(13);
uart1_write_text(txt);
}
}

What about the electronics:

The UART protocol is amazing but we can't communicate with a PC using it so we have to convert this protocol to an other one that is adopted by PC, the great one is the famous RS232 protocol.
RS232 is very close to the UART protocol the only difference is the logic level:
RS232: 1-->+12V 0-->-12V
UART: 1-->5V 0-->0V
So all we have to do is to find a way to convert the logic level from PC to PIC and From PIC to PC
The best solution is the one provided by Maxim the MAX232 circuit:
This little circuit does the job quite well.
The RS232 protocol use the DB9 port on PC but we can't find this port a new PCs that's why we need a converter from the RS232 to USB we use (just like its function) a converter cable from RS232 to USB just like this one:

Some cables requires a driver to be installed so you need to find the right one.
Linking....
The best circuit that I personally tried it is this one and it works amazingly:
 

2 commentaires:

  1. salem! ya 5ouya barak Allahou fik vraiment explication très simple et efficace,amma elpartie hedhi mafhemthech :\
    char txt[120];
    void main(){
    uart1_init(9600);
    while(1){
    uart1_read_text(txt,"#" ,255);
    uart1_write(10);
    uart1_write(13);
    uart1_write_text(txt);
    }
    }

    RépondreSupprimer
  2. char txt[120];
    void main(){
    uart1_init(9600);
    while(1){
    uart1_read_text(txt,"#" ,255);//read data till you find #
    uart1_write(10);
    uart1_write(13);//new Line
    uart1_write_text(txt);//write the data we read
    }
    }

    RépondreSupprimer