لاستعراض هذا النوع من شبكات الاتصال سوف نقوم فى هذا الفصل بعمل اتصال نصف مزدوج بين اثنين من الميكروكونترولر , وسوف نستخدم لهذا الغرض الموديولات USART مع مزيد من التحكم لطرف التمكين .
لإدراك استخدام RS485 يمكنك مراقبة وتحليل كود المصدر للبرنامج التالى الذى يقوم بإرسال حالة مقاومة متغيرة للتحكم فى شدة الإضاءة لمصباح بالجهة المقابلة :
كود:
void main( void )
{
//Declaration of variables.
unsigned short DATA;
//Port settings.
TRISB = 0b11111110;
PORTB = 0; //MAX485 is configured as a receiver.
//Activated pull-up resistors.
OPTION_REG = 0;
//USART module is configured to 250000 bps.
UART1_Init(250000);
//PWM module is configured with a frequency of 1K Hz
PWM1_Init(1000);
//PWM module starts with 0%.
PWM1_Start();
PWM1_Set_Duty(0);
while(1) //Infinite Loop.
{
//Evaluates if a data has arrived.
if( UART1_Data_Ready() )
{
DATA = UART1_Read();
//Evaluates whether the data arrival equals the flag 170.
if( DATA==170 )
{
//waits for the next data.
while( !UART1_Data_Ready() );
DATA = UART1_Read();
//Updates the duty cycle of the PWM.
PWM1_Set_Duty(DATA);
}
}
//Evaluates whether the button was pressed.
if( Button(&PORTB, 1, 50, 0) )
{
PORTB = 1; //MAX485 is configured as a transmitter.
//Reads the analog channel with voltage
//potentiometer, and saved the 8 most significant bits
// in the variable DATA.
DATA = (ADC_Read(0)>>2)&0xFF;
//Transmits the flag 170, to synchronize communication.
UART1_Write(170);
//Pauses for 1 m seconds between data.
delay_ms(1);
//Transmitting the value of the variable DATA.
UART1_Write(DATA);
//Wait until the button is released.
while( Button(&PORTB, 1, 50, 0) );
PORTB = 0; //Set MAX485 as receiver .
}
}
}