Nowadays most of Micro Controllers have a built in USART hardware. It can be used for communication between PC and micro controller. Since PIC is widely used general purpose µController, here after µC refers to PIC µControllers. But the concept can be adapted to any µControllers.
USART/RS232 communication needs minimum of at least 3 wires for full duplex communication. They are
- Transmition Line (Tx)
- Receiving Line (Rx)
- Common Ground (GND)
First consider the µController side.
Sample code given in MikroC will be a good start. But remember these things:
µController can send only a single Byte (1 register values/ 8 bits) at a time. So, to send a stream of text/numbers use this code.
Usart_Write('P');
For text:
Usart_Write('I');
Usart_Write('C');
// this will send a word 'PIC' through USART
There are some string functions in C, which you can use to send words easily. These functions will ultimately call Usart_Write(char c) repeatedly to transmit the string data.
For Numbers:
Usart_Write(255);
Usart_Write(2);
// this will send the number in binary format.
Max. limit is 255 or 0xFF
If only 3 wires are being used, maximum safe rate is 9600 baud. If more speed is needed, go for a hardware or software transmission flow control mechanism. If this rule is not followed, there is more chance of error in the transmission.
So the most latest data received will be read by i = Usart_Read(); So, the good practice is to store the value in a variable for the later use. To receive a set of characters use a while loop
unsigned char arr_data[5];
unsigned short i;
i = 0;
do {
if (Usart_Data_Ready()) {
arr_data(i) = Usart_Read();
i += 1; // increase i for the next step
}
} while (i<5);
PIC earlier than PIC18F series have limitation in array size. For example maximum size of an array will be limited to 96 for popular PIC16F877A because of its bank structure.
Reading the array located in other then Bank0 is difficult to use with USART (My personal experience). If larger size array is required use a PIC18F device. This will solve the size limitation problem. In PIC18F4550, it has 2kB data memory (RAM) allowing reasonable memory left for other variables.
Now let's have a quick look at PC side.
- MikroC include a USART terminal (short cut ctrl+T). First use this tool to visualize the data sent by PIC.
- If this is success only, move to the next step.
- See my blog on USART communication with Visual Basic 6.0 to create your custom user interface.
No comments:
Post a Comment
Please give your valuable comments