PICAXE Wireless Interfacing | |
| There are three key aspects to successful
wireless communications with a PICAXE device; getting the data
transmitted, ensuring that data received is valid, and overcoming the
limitations of the PICAXE itself.
The first thing you'll need to do wireless
communications are at least two PICAXE's, one sending data through a radio
transmitter, and the other using a radio receiver to get the data and do
something with it.
This article will only deal with this simple setup, and will
concentrate on getting the data from the sender to the receiver, not what
that data means or how it is to be created or used.
The simplest transmitters convert a raw bit-stream into something which
can be understood by a matching receiver, which performs the reverse
translation and delivers that same raw bit-stream back out. There are
considerably more complex devices which will handle serial data streams
and include comprehensive error checking and packet re-transmission on
errors, but these, like transceivers which can both send and receiver, are
expensive and beyond the scope of this article.
The downside of using the simplest transmitters and receivers is that
we must handle the sending and receiving of the bit-stream and create an
'over the air' protocol which is robust and reliable while both tolerant
of, and immune to, interference. In practice, this is not as hard as it
may at first appear, if we do not have any major concerns over lost
packets, which would add a whole new dimension of difficulty.
Radio Frequencies
In the UK, Europe and almost everywhere else in the world, there are
legal restrictions on which radio frequencies can be used without having
to hold a licence or pay for using that frequency.
There are usually a number of frequencies which are allocated for the
use of Short Range Radio Devices ( SRD's ), which are
licence exempt ( meaning anyone can use them without a licence,
and without having to pay a fee ), and these are the ones which must
be used. You will usually find that the transmitters and receivers for
sale are available only for these legal frequencies anyway.
Although you can import transmitters and receivers, always check that
they use a frequency which is legal to use in your own country. Using the
wrong frequency is a criminal offence and can be heavily punished and can
often include the confiscation of the offending equipment and everything
attached to it - just hope you don't have your PC attached to a home
or school network and are downloading into your PICAXE when you have the
knock on the door !
Although it's tempting to ignore the legal aspects of radio spectrum
licensing and imagine that no one will ever find out that you are using
something illegal which has a few dozen metres of transmission capability
at best, you would be surprised at the vigour in which breaches of the
radio laws are pursued when someone 'shops you' for causing radio
interference or because they're having a 'bad day' and you've upset them.
Schools and colleges take a particularly dim view of their students who
break the law, and are quite likely to take punitive action as a warning
to others.
The legally permitted frequencies harmonised in the UK and across
Europe for licence exempt transmission are ...
The 418MHz ( MPT1340 : 417.900 to 418.100
MHz ) band was previously used extensively, but fell out of favour
because of the introduction of TETRA which
causes interference and major problems in that band. The 418MHz band has
now been allocated for mobile phone use which, with their much grater
transmission power than exempt users are allowed, means that most 418MHz
receivers will be swamped by interference.
It is strongly recommended to avoid devices which operate at 418MHz
whenever possible, and realise that the reason they may now be cheaper
than other frequency devices is because there's a good chance they won't
work very well any more.
Modulation
Radio transmitters and receivers will normally use either
Amplitude (AM) or Frequency (FM) modulation. Both are capable of
doing the job, but FM is often more immune to interference and can have a
better range than AM; it is therefore the preferred choice. FM devices are
however often more expensive than AM devices because they are more complex
to build, but are controlled in exactly the same way as AM devices are
from the PICAXE's point of view.
Interference
Because there are only a few licence exempt radio frequencies
available, many other wireless and wirefree devices will be using the same
frequency as you are, from Wireless PIR's for burglar alarms, through
Wireless Doorbells to the humble car key fob. It is almost a certainty
that you will encounter interference from other devices using the same
frequency at some time, and your own transmissions will most likely be
interfering with others.
You will also suffer interference if you have more than one of your own
devices transmitting at the same time, and of course all the problems
caused by other transmitters not necessarily on the same frequency, and
unsurpressed vehicle engines as they drive past.
The interference will usually show itself as some form of corruption on
your wireless link; data received which is not identically to what was
sent, data not being received at all, or data being received which was
sent by someone else.
It is therefore a fundamental aspect of any wireless transmission
system to have a protocol which can detect corruption, ignore invalid
data, and can authenticate that the received data came from the source it
claims to have, and that the data actually means what you think it does.
Your own radio transmissions will, as already mentioned, be
interference to others, and while commercial products are usually well
designed to reject transmissions which they don't wish to see, they can be
rendered ineffective by continuous transmissions you send out. It is
therefore courtesy that you do not develop systems which use continuous
transmission which may interfere with other systems, and you may attract
the attention of the legal authorities if you do. It is a serious
offence ( with significant penalties ) to deliberately
interfere with the operation of other systems, and you may unknowingly be
putting people's lives in danger when doing so; although 'Help Me!' alarm
and call-out systems should be using specifically allocated frequencies,
some, especially older equipment, may well be using the same frequency you
will be using,
Power Consumption Considerations
While you will probably want to keep the radio receiver and receiving
PICAXE powered-up all the time, because you don't know when data will be
sent to it, there is no reason that the sending PICAXE cannot be put into
SLEEP mode with the radio transmitter powered down when not in use. This
will extend battery life considerably if the transmitting unit is powered
that way.
It should be a very simple task to control power to the radio
transmitter by using one of the PICAXE output pins, and because each
PICAXE output pin can source 20mA ( possibly 25mA on some
PICAXE's - check the datasheets ), it could be possible to power
the radio transmitter directly from an output pin.
The full details of doing this are beyond the scope of this article
because the implementation depends on a number of factors; the voltage
required by the radio transmitter, the current drawn when it is working
and what other current load is being placed upon the PICAXE outputs.
The only issues in powering the radio transmitter under PICAXE control
are that it must be given time to stabilise before transmitting after
being powered-up, and the transmitting line should be kept low whenever
the transmitter is powered-down; not doing so can have adverse effects and
may cause damage to some radio transmitter devices.
If you have a system which uses more than one transmitter you will
almost certainly need to turn the transmitters on and off under PICAXE
control
If two transmitters are powered at the same time, the receiver may be
unable to synchronise to a single one, unexpectedly switch between the
two ( invariably in the middle of data transmission ) or
locking onto only one while permanently excluding the other.
Operating at 433MHz using AM modulation, these modules made by RF
Solutions are capable of supporting 2Kbps transmission rates with up
to 50 metre range.
The modules operate over a wide voltage range, require no
adjustment or external components other than the controllers and an
aerial. Maplins Part Code : VY 48 C
When the sender wants to send a packet of data, the first thing it does is apply power to the transmiter, delay a while to give it a chance to stabilise, ready for transmitting, and then a number of preamble bytes are sent. The preamble bytes are sent primarily to wake up the receiver and kick it into action to be ready to decode the real data which will be coming soon after. Receivers like to see continuously changing 0 and 1 bits in the transmission, ideally an equal number of 0's and 1's, but they are tolerant to reasonably long sequences which are all one or the other. While waking up the receiver, it is important that we do try and send an equal number of each bit, which means that the ideal candidates are the bytes $AA and $55 which contain alternating 0's and 1's. The receiver will undoubtedly lose some of the bits at the beginning of the preamble but should eventually synchronise up. The number of preamble bytes to send will need to be obtained by some experimentation. Start with a reasonably high number and reduce the number; it's better to start with something that works and tweak it later rather than starting with nothing working. Most receivers will require 3mS or more of preamble, which at a low baud rate equates to just one or two bytes. Following the preamble we send our Start Of Message (SOM) byte. This can have any value but should be distinct from the preamble byte. The receiver will be looking for a preamble byte followed by the SOM byte to know that it has a possible data packet arriving. After the SOM byte, we send our identification code, a count of how many data bytes there are and the data bytes themselves. After the data bytes, we send a checksum byte followed by an End Of Message (EOM) byte. This should have a differing value to the preamble bytes and the SOM byte. Having sent our EOM byte we have effectively sent our complete packet and we could finish at that point. However, we have no idea whether the packet got through to the receiving PICAXE or not. If the receiver saw the preamble and SOM byte and has started to read the packet using SERIN, but never received all bytes, it is most likely sitting there waiting for further bytes to turn up which never will, until we send another packet. At that point the PICAXE will finish reading what it thinks was the first packet, reject it because it will fail during error checking, and may then fall flat on its face again as it tries to deal with the curent packet, half of which it may already have missed. In the worse case scenario, the receiver could continual jam and not see any packets at all, even when it's receiving a perfectly good data stream. In an attempt to avoid this, we send enough postamble bytes as necessary to make sure that SERIN has received as many bytes as it needs to think a full packet has been received. The mechanism is not perfect because a poor quality link may see some of the postamble bytes lost as well. Although we could send even more postamble bytes than are really necessary, there is still a chance that it won't be enough. A good compromise is to send as many postamble bytes as there could be maximum data bytes. Even though we will lose one packet, the receiver should be forced to perceive the next packet as being one in its own right, and not the tail-end of an earlier one. This postamble also has the advantage that we can send variable length data packets which will always be padded out with postamble bytes to the size of packet which the receiver expects. If you need the shortest possible packet length, it would be possible to send just the right number of postamble bytes to pad out a packet to the right size, and then just one more to handle single byte data loss. Having sent the postamble bytes, the complete packet is gone, and the sender can power-down the transmitter, sleep for a while, before waking up, obtaining a new set of data to send and sending that packet. The Checksum Because we can have all sorts of corruption of the data stream from single bits in one byte sent to completely missing bytes, and even inserted bytes caused by interference, it is necessary to have a fairly reliable checksum which does not give the false impression that a legitimate packet has arrived when it is in fact corrupted. Standard 'XOR checksums' where the checksum is simply XOR'd with every byte that is sent is a particularly poor choice because just two inverted bits in the same bit positions of different bytes can make the packet look legitimate. Similar problems exist where the checksum is the eight bit truncated value of all bytes sent added together. Cyclic Redundancy Checks ( CRC's ) are much less prone to such errors, but even they are not infallible, and with any single byte checksum, there's always the 1 in 256 chance that whatever the byte is, it will match with what the checksum would have been. The real problem with CRC's as opposed to the simpler methods of checksumming is that calculating a CRC takes a lot longer to do. While there are numerous tricks which can be applied to speed up the calculation of CRC's, the PICAXE does not have the capability to apply them, meaning that a CRC has to be calculated using a brute force approach which is easy to do, but is also time consuming, especially as the PICAXE is not phenomenally fast. Where speed is of great importance it is entirely possible to drop back to a simpler form of checksum, or not use one at all, with the risks that involves. If greater reliability is required, it is also possible to go to 16 and even 32 bit CRC checksums, but there will be an increasing time penalty in both calculating the checksums and in transmitting the additional bytes. This time penalty will also apply to the receiver which has to perform exactly the same calculation to see if the checksum sent matches what it thinks it should be. It is also important to note that calculating a CRC on-the-fly during packet transmission extends the time when the transmitter which can cause the receiver to lose synchronisation with he the data stream. To avoid such a problem, the CRC of the packet should be calculated before the packet is transmitted.
Transmitter SoftwareThe following transmitter example will send a packet of data that can be between one and four bytes long to a second PICAXE running the receiving software described later.You will need to provide details of the Output Pin to which the radio transmitter data line is connected, an Output Pin number which is used to control the powering up of the radio transmitter ( any pin number except that used as the radio transmitter data line will do if the transmitter is always on ), and you will need to select a baud rate suitable for your design ( start low and work up ), and a powering-up delay for the radio transmitter. You should alter 'RECEIVER_CODE' to a number between 0 and 15 to give yourself a unique identification of which receiver will be able to receive the data sent from the PICAXE and alter 'SENDER_CODE' to a number between 0 and 15 to indicate which sending device this PICAXE is. The design here allows for up to 16 unique receiving systems, each of which can receive from up to 16 individual sending devices. You can change the data sent in the packets by altering the 'CreatePacket:' routine. At present it sends a four byte data packet containing the text "Okay". The software can be tested by removing the radio transmitter and receiver and fitting a wire link between the Output Pin of the sending PICAXE and the Input Pin of the receiving PICAXE and by joining each PICAXE's 0V lines together. SYMBOL RECEIVER_CODE = 0 ' 0 .. 15 SYMBOL SENDER_CODE = 0 ' 0 .. 15 SYMBOL TX_PIN = ? SYMBOL TX_BAUD = ? SYMBOL POWER_ON_PIN = ? SYMBOL POWER_UP_DELAY = ? SYMBOL PREAMBLE_LENGTH = 5 SYMBOL MAX_DATA_LENGTH = 4 SYMBOL PREAMBLE_BYTE = $AA SYMBOL SOM_BYTE = $C5 SYMBOL EOM_BYTE = $5C SYMBOL POSTAMBLE_BYTE = $3A SYMBOL dataLength = b0 SYMBOL byteNumber = b1 SYMBOL bytePtr = b2 SYMBOL byte = b3 SYMBOL bit = b4 SYMBOL k = b5 SYMBOL crc = b6 SYMBOL POLYNOMIAL = $8C PowerOnReset: Loop: GOSUB CreatePacket GOSUB SendPacket PAUSE 5000 GOTO Loop CreatePacket: dataLength = 4 POKE $50,"O" POKE $51,"k" POKE $52,"a" POKE $53,"y" RETURN Sendpacket: ' On entry, 'dataLength' contains the number of bytes ' of data to send. The bytes of data are stored in SFR ' RAM from location $50 upwards. CalculateCrc: crc = 0 byte = SENDER_CODE * $10 | RECEIVER_CODE GOSUB CrcAdd bytePtr = $50 FOR byteNumber = 1 TO dataLength PEEK bytePtr,byte bytePtr = bytePtr+1 GOSUB CrcAdd NEXT PowerUpTransmitter: HIGH POWER_ON_PIN PAUSE POWER_UP_DELAY SendPreamble: FOR byteNumber = 1 TO PREAMBLE_LENGTH SEROUT TX_PIN,TX_BAUD,(PREAMBLE_BYTE) NEXT SendStartOfMessage: SEROUT TX_PIN,TX_BAUD,(SOM_BYTE) SendReceiverAndSenderCode: byte = SENDER_CODE * $10 | RECEIVER_CODE SEROUT TX_PIN,TX_BAUD,(byte) SendDataLength: SEROUT TX_PIN,TX_BAUD,(dataLength) SendData: bytePtr = $50 FOR byteNumber = 1 TO dataLength PEEK bytePtr,byte bytePtr = bytePtr+1 SEROUT TX_PIN,TX_BAUD,(byte) NEXT SendChecksum: SEROUT TX_PIN,TX_BAUD,(crc) SendEndOfMessage: SEROUT TX_PIN,TX_BAUD,(EOM_BYTE) SendPostamble: FOR byteNumber = 1 TO MAX_DATA_LENGTH SEROUT TX_PIN,TX_BAUD,(POSTAMBLE_BYTE) NEXT SentPacket: LOW TX_PIN LOW POWER_ON_PIN RETURN CrcAdd: FOR bit = 0 TO 7 k = byte ^ crc & 1 IF k = 0 THEN CrcAdd1 k = POLYNOMIAL CrcAdd1: crc = crc / 2 ^ k byte = byte / 2 NEXT RETURN
Receiver SoftwareThe following receiver example will receive a packet of data that can be up to four bytes long from another PICAXE running the transmitting software described above.The SERIN command after the 'ReceivePacket:' label has been split into two lines so it displays better in this listing, and you'll need to delete the '_' character and concatenate the second line on to the first to get the code to compile. You will also need to provide details of the Input Pin to which the radio receiver data line is connected, and you will need to select a baud which matches that of the sender, and suits the polarity of the radio receiver data stream. You should change the 'RECEIVER_CODE' to a number between 0 and 15 to match the 'RECEIVER_CODE' used in the sending PICAXE's you wish to receive packets from. The program is designed to work with a PICAXE which supports the SERTXD command. IF your target device does not support SERTXD, you will need to modify it to use SEROUT to a PC or other device, or use some other mechanisms such as an LCD to display the received data packets and status information. The software can be tested by removing the radio transmitter and receiver and fitting a wire link between the Output Pin of the sending PICAXE and the Input Pin of the receiving PICAXE and by joining each PICAXE's 0V lines together. SYMBOL RECEIVER_CODE = 0 ' 0 .. 15 SYMBOL RX_PIN = ? SYMBOL RX_BAUD = ? SYMBOL MAX_DATA_LENGTH = 4 SYMBOL PREAMBLE_BYTE = $AA SYMBOL SOM_BYTE = $C5 SYMBOL EOM_BYTE = $5C SYMBOL POSTAMBLE_BYTE = $3A SYMBOL dataLength = b0 SYMBOL data1 = b1 SYMBOL data2 = b2 SYMBOL data3 = b3 SYMBOL data4 = b4 SYMBOL data5 = b5 SYMBOL data6 = b6 SYMBOL byteNumber = b7 SYMBOL bytePtr = b8 SYMBOL byte = b9 SYMBOL bit = b10 SYMBOL k = b11 SYMBOL crc = b12 SYMBOL code = b13 SYMBOL POLYNOMIAL = $8C PowerOnReset: GOSUB ClearErrorLed Loop: GOSUB ReceivePacket GOSUB ShowPacket GOTO Loop ReceivePacket: SERIN RX_PIN,RX_BAUD,(PREAMBLE_BYTE,SOM_BYTE),code _ dataLength,data1,data2,data3,data4,data5,data6 CheckDataLength: IF dataLength < 1 THEN Failed IF dataLength > MAX_DATA_LENGTH THEN Failed CheckReceiverCode: byte = code & $0F IF byte <> RECEIVER_CODE THEN Failed SaveDataForUseLater: POKE $50,data1 POKE $51,data2 POKE $52,data3 POKE $53,data4 POKE $54,data5 POKE $55,data6 CheckEomByte: bytePtr = $50 + dataLength + 1 PEEK bytePtr,byte IF byte <> EOM_BYTE THEN Failed CheckChecksum: crc = 0 byte = code GOSUB CrcAdd bytePtr = $50 FOR byteNumber = 1 TO dataLength PEEK bytePtr,byte bytePtr = bytePtr+1 GOSUB CrcAdd NEXT bytePtr = $50 + dataLength PEEK bytePtr,byte IF byte = crc THEN ReceivedPacket Failed: GOSUB SetErrorLed GOTO ReceivePacket ReceivedPacket: GOSUB ClearErrorLed RETURN CrcAdd: FOR bit = 0 TO 7 k = byte ^ crc & 1 IF k = 0 THEN CrcAdd1 k = POLYNOMIAL CrcAdd1: crc = crc / 2 ^ k byte = byte / 2 NEXT RETURN ShowPacket: byte = code / $10 SERTXD("FROM ",#byte,":") bytePtr = $50 FOR byteNumber = 1 TO dataLength PEEK bytePtr,byte bytePtr = bytePtr+1 SERTXD(byte) NEXT SERTXD($0D,$0A) RETURN SetErrorLed: SERTXD("BAD PACKET",$0D,$0A) RETURN ClearErrorLed: RETURN
Thanks and AcknowledgementsThanks go to Dan ( aka "Tarzan" on the PICAXE User Forum ) for being prepared to take the transmitter and receiver code on this page in good faith and being willing to see if it would work, successfully identifying a small bug in the receiver software in the processThanks also go to Peter H Anderson of www.phanderson.com for the original code upon which the CRC calculating routine used here is based. Finally, many thanks go to Greg Newton for practical advice and for sharing his experiences of actually using wireless communications, identifying the need to power-off transmitters when more than one is used, providing further information on packet timing and packet formating, and for helping unravel the mysteries of CRC checksumming. And not least for, getting the code to work with physical wireless transmitters and receivers, identifying the timing errors in the transmitter code, and the need to calculate the checksum befor the packet is sent, rather than while the packet is being transmitted. Thanks to Greg and Dan, the code presented above has now been tested using both hard-wired links between two PICAXE's and demonstrated to work over an actual wireless link.
PICAXE is a trademark of Revolution Education Ltd. PICmicro is a registered trademark of Microchip Inc. | ||||||||
First
published on Monday the 22nd of March, 2004 at 20:02:18 Last upload was on Monday the 23rd of August, 2004 at 00:20:47 |