View previous topic :: View next topic |
Author |
Message |
janet
Joined: 17 Feb 2004 Posts: 23
|
How to connect 2 PIC using RS232? |
Posted: Thu Mar 11, 2004 11:50 pm |
|
|
Hi,
I wish to connect to PIC using RS232. One of the PIC is used to connect to sensor, the other one is receiver. The PIC may connect to several sensor, and send it to receiver.
serveral sensor(s) -> PIC ->(RS232) -> Receiver (PIC)
the sensor-PIC will send 3 bytes to receiver PIC for each reading
Sync_byte + sensor_id + sensor_value
after the receiver PIC receive the Sync_byte, it will start to store the sensor value according to sensor_id.
. both sensor and receiver are using XTAL 20 Mhz. The baud rate for the rs232 is 9600.
I have made a loop to check the incoming byte continuosly. However, if the loop is rather slow, some data will be missed.
How to ensure the loop is fast enough to catch all the incoming byte? or perhaps we could make sensor send data in slower rate?
/* sensor */
void main() {
SENSOR sensor[SENSOR_SIZE];
BYTE i;
while (TRUE) {
sensor[TEMPERATURE].value = 45;
sensor[DIP_SWITCH].value = input_d();
sensor[RANDOM].value = 34;
sensor[SINE_WAVE].value = 33;
for (i = 0; i < SENSOR_SIZE; i++) {
putc(SYNC_BYTE);
putc(sensor[i].id);
putc(sensor[i].value);
}
}
}
/* Receiver */
void main() {
BYTE i;
RECV recv;
DATA_BUFFER data_buffer;
recv.sm_recv = SM_RECV_LISTEN;
recv.byte_count = sizeof(SENSOR);
data_buffer.data_count = 0;
while (TRUE) {
while (kbhit()) {
switch(recv.sm_recv) {
case SM_RECV_LISTEN:
if (getc() == SYNC_BYTE) {
recv.sm_recv = SM_RECV_ID;
}
break;
case SM_RECV_ID:
data_buffer.sensor[data_buffer.data_count].id = getc();
recv.sm_recv = SM_RECV_ID;
break;
case SM_RECV_VALUE:
data_buffer.sensor[data_buffer.data_count].value = getc();
data_buffer.data_count++;
recv.sm_recv = SM_RECV_LISTEN;
break;
}
}
}
} |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Mar 12, 2004 12:29 am |
|
|
Look at the CCS example file, EX_SISR.C, to see how to create
an interrupt driven receive fifo. Use as large a buffer as possible
(80 bytes or more, on a 16F877).
By using this buffer, you don't have to watch kbhit() so closely.
You can afford the time to do other things for awhile in your program.
However, you still have to pull bytes out of the buffer at the same
average rate at which they are coming in, or you will get a buffer
overflow. |
|
|
janet
Joined: 17 Feb 2004 Posts: 23
|
|
Posted: Fri Mar 12, 2004 2:33 am |
|
|
i have read the example, but, which is pin RDA?
i m using pic16f877 and pic18f452 |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Mar 12, 2004 2:43 am |
|
|
Quote: | i have read the example, but, which is pin RDA?
i m using pic16f877 and pic18f452 |
#int_rda is used with the hardware RS232 Rx pin, which
is on Pin C7 for both the 16F877 and the 18F452.
Use the following line to setup the USART.
This will work for both of the above PICs.
#use rs232(baud = 9600, xmit=PIN_C6, rcv = PIN_C7, ERRORS) |
|
|
|