Sie sind auf Seite 1von 8

20/10/2016

RS485Library

RS485Library
mikroCPROforPICLibraries>HardwareLibraries>

RS485Library
RS485isamultipointcommunicationwhichallowsmultipledevicestobeconnectedtoasinglebus.ThemikroCPROforPIC
providesasetoflibraryroutinesforcomfortableworkwithRS485systemusingMaster/Slavearchitecture.MasterandSlave
devicesinterchangepacketsofinformation.Eachofthesepacketscontainssynchronizationbytes,CRCbyte,addressbyteandthe
data.EachSlavehasuniqueaddressandreceivesonlypacketsaddressedtoit.TheSlavecanneverinitiatecommunication.
Itistheusersresponsibilitytoensurethatonlyonedevicetransmitsvia485busatatime.
TheRS485routinesrequiretheUARTmodule.PinsofUARTneedtobeattachedtoRS485interfacetransceiver,suchasLTC485
orsimilar(seeschematicatthebottomofthispage).
Libraryconstants:
STARTbytevalue=150
STOPbytevalue=169
Address50isthebroadcastaddressforallSlaves(packetscontainingaddress50willbereceivedbyallSlavesexcept
theSlaveswithaddresses150and169).
Important:
ThelibraryusestheUARTmoduleforcommunication.TheusermustinitializetheappropriateUARTmodulebefore
usingtheRS485Library.
ForMCUswithmultipleUARTmodulesitispossibletoinitializethemandthenswitchbyusingtheUART_Set_Active
routine.

LibraryDependencyTree

ExternaldependenciesofRS485Library
Thefollowingvariablemustbe
definedinallprojectsusingRS
485Library:

Description:

externsfrsbitRS485_rxtx_pin

ControlRS485
Transmit/Receiveoperation
mode

externsfrsbit
RS485_rxtx_pin_direction

DirectionoftheRS485
Transmit/Receivepin

Example:

sbitRS485_rxtx_pinat
RC2_bit
sbit
RS485_rxtx_pin_direction
atTRISC2_bit

LibraryRoutines
RS485Master_Init
RS485Master_Receive
RS485Master_Send
RS485Slave_Init
RS485Slave_Receive
RS485Slave_Send

RS485Master_Init
Prototype

voidRS485Master_Init()

Returns

Nothing.

Description

InitializesMCUasaMasterforRS485communication.

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

1/8

20/10/2016

Requires

RS485Library

Globalvariables:
RS485_rxtx_pinthispinisconnectedtoRE/DEinputofRS485transceiver(seeschematicatthe

bottomofthispage).RE/DEsignalcontrolsRS485transceiveroperationmode.
RS485_rxtx_pin_directiondirectionoftheRS485Transmit/Receivepin.
mustbedefinedbeforeusingthisfunction.
UARTHWmoduleneedstobeinitialized.SeeUARTx_Init.

Example

//RS485modulepinout
sbitRS485_rxtx_pinatRC2_bit//transmit/receivecontrolsettoPORTC.B2
//Pindirection
sbitRS485_rxtx_pin_directionatTRISC2_bit//RxTxpindirectionsetasoutput
...
UART1_Init(9600)//initializeUART1module
RS485Master_Init()//intializeMCUasaMasterforRS485communication

RS485Master_Receive
Prototype

voidRS485Master_Receive(char*data_buffer)

Returns

Nothing.

Description

ReceivesmessagesfromSlaves.Messagesaremultibyte,sothisroutinemustbecalledforeachbyte
received.
Parameters:
data_buffer:7bytebufferforstoringreceiveddata,inthefollowingmanner:
data[0..2]:messagecontent
data_buffer[3]:numberofmessagebytesreceived,13
data_buffer[4]:issetto255whenmessageisreceived
data_buffer[5]:issetto255iferrorhasoccurred
data_buffer[6]:addressoftheSlavewhichsentthemessage

Thefunctionautomaticallyadjustsdata[4]anddata[5]uponeveryreceivedmessage.Theseflagsneedtobe
clearedbysoftware.
Requires

MCUmustbeinitializedasaMasterforRS485communication.SeeRS485Master_Init.

Example

charmsg[8]
...
RS485Master_Receive(msg)

RS485Master_Send
Prototype

voidRS485Master_Send(char*data_buffer,chardatalen,charSlave_address)

Returns

Nothing.

Description

SendsmessagetoSlave(s).Messageformatcanbefoundatthebottomofthispage.
Parameters:
data_buffer:datatobesent
datalen:numberofbytesfortransmition.Validvalues:0...3.
Slave_address:Slave(s)address

Requires

MCUmustbeinitializedasaMasterforRS485communication.SeeRS485Master_Init.
Itistheusersresponsibilitytoensure(byprotocol)thatonlyonedevicesendsdatavia485busatatime.

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

2/8

20/10/2016

Example

RS485Library

charmsg[8]
...
//send3bytesofdatatoSlavewithaddress0x12
RS485Master_Send(msg,3,0x12)

RS485Slave_Init
Prototype

voidRS485Slave_Init(charSlave_address)

Returns

Nothing.

Description

InitializesMCUasaSlaveforRS485communication.
Parameters:
Slave_address:Slaveaddress

Requires

Globalvariables:
RS485_rxtx_pinthispinisconnectedtoRE/DEinputofRS485transceiver(seeschematicatthe
bottomofthispage).RE/DEsignalcontrolsRS485transceiveroperationmode.Validvalues:1(for
transmitting)and0(forreceiving
RS485_rxtx_pin_directiondirectionoftheRS485Transmit/Receivepin.

mustbedefinedbeforeusingthisfunction.
UARTHWmoduleneedstobeinitialized.SeeUARTx_Init.
Example

InitializeMCUasaSlavewithaddress160:
//RS485modulepinout
sbitRS485_rxtx_pinatRC2_bit//transmit/receivecontrolsettoPORTC.B2
//Pindirection
sbitRS485_rxtx_pin_directionatTRISC2_bit//RxTxpindirectionsetasoutput
...
UART1_Init(9600)//initializeUART1module
RS485Slave_Init(160)//intializeMCUasaSlaveforRS485communicationwithaddress160

RS485Slave_Receive
Prototype

voidRS485Slave_Receive(char*data_buffer)

Returns

Nothing.

Description

ReceivesmessagesfromMaster.IfSlaveaddressandMessageaddressfielddon'tmatchthenthemessage
willbediscarded.Messagesaremultibyte,sothisroutinemustbecalledforeachbytereceived.
Parameters:
data_buffer:6bytebufferforstoringreceiveddata,inthefollowingmanner:
data[0..2]:messagecontent
data[3]:numberofmessagebytesreceived,13
data[4]:issetto255whenmessageisreceived
data[5]:issetto255iferrorhasoccurred

Thefunctionautomaticallyadjustsdata[4]anddata[5]uponeveryreceivedmessage.Theseflagsneedtobe
clearedbysoftware.
Requires

MCUmustbeinitializedasaSlaveforRS485communication.SeeRS485Slave_Init.

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

3/8

20/10/2016

Example

RS485Library
charmsg[8]
...
RS485Slave_Read(msg)

RS485Slave_Send
Prototype

voidRS485Slave_Send(char*data_buffer,chardatalen)

Returns

Nothing.

Description

SendsmessagetoMaster.Messageformatcanbefoundatthebottomofthispage.
Parameters:
data_buffer:datatobesent
datalen:numberofbytesfortransmition.Validvalues:0...3.

Requires

MCUmustbeinitializedasaSlaveforRS485communication.SeeRS485Slave_Init.Itistheusers
responsibilitytoensure(byprotocol)thatonlyonedevicesendsdatavia485busatatime.

Example

charmsg[8]
...
//send2bytesofdatatotheMaster
RS485Slave_Send(msg,2)

LibraryExample
ThisisasimpledemonstrationofRS485Libraryroutinesusage.
MastersendsmessagetoSlavewithaddress160andwaitsforaresponse.TheSlaveacceptsdata,incrementsitandsendsit
backtotheMaster.MasterthendoesthesameandsendsincrementeddatabacktoSlave,etc.
MasterdisplaysreceiveddataonPORTB,whileerroronreceive(0xAA)andnumberofconsecutiveunsuccessfulretriesare
displayedonPORTD.SlavedisplaysreceiveddataonPORTB,whileerroronreceive(0xAA)isdisplayedonPORTD.Hardware
configurationsinthisexamplearemadefortheEasyPIC6boardand16F887.
RS485Mastercode:
CopyCodeToClipboard

chardat[10]//bufferforreceving/sendingmessages
chari,j
sbitrs485_rxtx_pinatRC2_bit//settranscievepin
sbitrs485_rxtx_pin_directionatTRISC2_bit//settranscievepindirection
//Interruptroutine
voidinterrupt(){
RS485Master_Receive(dat)
}
voidmain(){
longcnt=0
ANSEL=0//ConfigureANpinsasdigitalI/O
ANSELH=0
C1ON_bit=0//Disablecomparators
C2ON_bit=0

PORTB=0
PORTD=0
TRISB=0
TRISD=0

UART1_Init(9600)//initializeUART1module
Delay_ms(100)

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

4/8

20/10/2016

RS485Library

RS485Master_Init()//initializeMCUasMaster
dat[0]=0xAA
dat[1]=0xF0
dat[2]=0x0F
dat[4]=0//ensurethatmessagereceivedflagis0
dat[5]=0//ensurethaterrorflagis0
dat[6]=0
RS485Master_Send(dat,1,160)

RCIE_bit=1//enableinterruptonUART1receive
TXIE_bit=0//disableinterruptonUART1transmit
PEIE_bit=1//enableperipheralinterrupts
GIE_bit=1//enableallinterrupts
while(1){
//uponcompletedvalidmessagereceiving
//data[4]issetto255
cnt++
if(dat[5]){//ifanerrordetected,signalit
PORTD=0xAA//bysettingportdto0xAA
}
if(dat[4]){//ifmessagereceivedsuccessfully
cnt=0
dat[4]=0//clearmessagereceivedflag
j=dat[3]
for(i=1i<=dat[3]i++){//showdataonPORTB
PORTB=dat[i1]
}//incrementreceiveddat[0]
dat[0]=dat[0]+1//sendbacktomaster
Delay_ms(1)
RS485Master_Send(dat,1,160)
}
if(cnt>100000){
PORTD++
cnt=0
RS485Master_Send(dat,1,160)
if(PORTD>10)//ifsendingfailed10times
RS485Master_Send(dat,1,50)//sendmessageonbroadcastaddress
}
}
}

RS485Slavecode:
CopyCodeToClipboard

chardat[9]//bufferforreceving/sendingmessages
chari,j
sbitrs485_rxtx_pinatRC2_bit//settranscievepin
sbitrs485_rxtx_pin_directionatTRISC2_bit//settranscievepindirection
//Interruptroutine
voidinterrupt(){
RS485Slave_Receive(dat)
}
voidmain(){
ANSEL=0//ConfigureANpinsasdigitalI/O
ANSELH=0
C1ON_bit=0//Disablecomparators
C2ON_bit=0

PORTB=0
PORTD=0
TRISB=0

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

5/8

20/10/2016

RS485Library

TRISD=0

UART1_Init(9600)//initializeUART1module
Delay_ms(100)
RS485Slave_Init(160)//IntializeMCUasslave,address160
dat[4]=0//ensurethatmessagereceivedflagis0
dat[5]=0//ensurethatmessagereceivedflagis0
dat[6]=0//ensurethaterrorflagis0
RCIE_bit=1//enableinterruptonUART1receive
TXIE_bit=0//disableinterruptonUART1transmit
PEIE_bit=1//enableperipheralinterrupts
GIE_bit=1//enableallinterrupts
while(1){
if(dat[5]){//ifanerrordetected,signalitby
PORTD=0xAA//settingportdto0xAA
dat[5]=0
}
if(dat[4]){//uponcompletedvalidmessagereceive
dat[4]=0//data[4]issetto0xFF
j=dat[3]
for(i=1i<=dat[3]i++){
PORTB=dat[i1]
}
dat[0]=dat[0]+1//incrementreceiveddat[0]
Delay_ms(1)
RS485Slave_Send(dat,1)//andsenditbacktomaster
}
}
}

HWConnection

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

6/8

20/10/2016

RS485Library

ExampleofinterfacingPIC16F887MCUtoPIC16F887MCUMCUviaRS485buswithLTC485asRS485transceiver

MessageformatandCRCcalculations
Q:HowisCRCchecksumcalculatedonRS485Masterside?
CopyCodeToClipboard

START_BYTE=0x96//10010110
STOP_BYTE=0xA9//10101001

PACKAGE:

START_BYTE0x96
ADDRESS
DATALEN
[DATA1]//ifexists
[DATA2]//ifexists
[DATA3]//ifexists
CRC
STOP_BYTE0xA9

DATALENbits

bit7=1MASTERSENDS
0SLAVESENDS
bit6=1ADDRESSWASXORedwith1,ITWASEQUALTOSTART_BYTEorSTOP_BYTE
0ADDRESSUNCHANGED
bit5=0FIXED
bit4=1DATA3(ifexists)WASXORedwith1,ITWASEQUALTOSTART_BYTEorSTOP_BYTE
0DATA3(ifexists)UNCHANGED

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

7/8

20/10/2016

RS485Library

bit3=1DATA2(ifexists)WASXORedwith1,ITWASEQUALTOSTART_BYTEorSTOP_BYTE
0DATA2(ifexists)UNCHANGED
bit2=1DATA1(ifexists)WASXORedwith1,ITWASEQUALTOSTART_BYTEorSTOP_BYTE
0DATA1(ifexists)UNCHANGED
bit1bit0=0to3NUMBEROFDATABYTESSEND

CRCgeneration:

crc_send=datalen^address
crc_send^=data[0]//ifexists
crc_send^=data[1]//ifexists
crc_send^=data[2]//ifexists
crc_send=~crc_send
if((crc_send==START_BYTE)||(crc_send==STOP_BYTE))
crc_send++

NOTE:DATALEN<4..0>cannottaketheSTART_BYTE<4..0>orSTOP_BYTE<4..0>values.

Copyright(c)20022012mikroElektronika.Allrightsreserved.
Whatdoyouthinkaboutthistopic?Sendusfeedback!

https://download.mikroe.com/documents/compilers/mikroc/pic/help/rs485_library.htm

Wantmoreexamplesandlibraries?
Findthemon

8/8

Das könnte Ihnen auch gefallen