Communications between devices...

I have used picaxe for some years for managed to create many successful and effective projects but so far have avoided using any serial data functions other than setting up a digital display exactly as explained in one of the manuals and managing to make this present the correct information but doing so without really understanding how it works.

I would now like to use a RTC, probably within a module, with a wish to create events that happen accurately and regularly every 30 seconds or 20 minutes or 3 hours etc. this being for an art based project. Presuming that the clock output values can be stored into variables, then I understand how to use these to give me the digital outputs required but I am really struggling to find any clear and concise explanation of the basics of what is needed to get two such devices as an RTC and Picaxe to communicate. What data is required, why and where does it need to go and how do I get it to go there? What is the difference between HSPI, i2c and 'ordinary' serial data etc and what are the pros and cons of the alternatives?
There are many available examples of programs but making any useful sense of these without understanding more of the basics is beyond my ageing brain.

There seems to be a surprising lack of information about this though I don't doubt that I may have been looking in quite the wrong place for it.

Can any of you resident geniuses (or genii if you prefer) please recommend some appropriate reading...



Many thanks...
 

J G

Active member
Hello,
I haven't used RTCs, but I have used other devices with each of these serial protocols. The main thing I would do is use the protocol available on the module or the one that there is already an example of using it with the PICAXE system. If more than one protocol are available, my personal preference would be SPI or I2C (depending on the built in hardware of the microcontroller) followed by UART.

What is the difference between HSPI, i2c and 'ordinary' serial data etc and what are the pros and cons of the alternatives?
Serial (UART)
This can need as little as one pin for single direction data transfer or 2 for bidirectional transfer. This has no form of addressing unless done in software and due to the send line of one device going into the receive line of another and vice versa, can be harder to make behave with more than 2 devices, although things could be done in software or hardware such as rs485 transceivers could be used to allow many devices to share the one bus.
The advantage of serial is that things can be directly connected to a computer for debugging or configuration if required through a serial port or the picaxe download cable. Be aware that the download cable, sertxd and serrxd have the signals inverted relative to standared UART, so either a not gate of some form or reprogramming the EEPROM of the FTDI chip inside the cable is required to get it to talk to things like Raspberry Pis, Arduinos or GPS modules (I haven't GPS modules myself though).

SPI (HSPI)
HSPI is Hardware Serial Peripheral Interface and uses hardware built into the microcontroller so that your program running on it can do other things during data transfer and not have to set pins using the software (bit banging).
This can be a very fast method of data transfer and is simple to implement on a hardware and software level, although can use a lot of pins and m2 parts and smaller can only bit bang it. For bidirectional data transfer, it needs at least 4 pins, a clock line, a data receive line, a data transmission line and a chip select. Each additional device on the bus needs its own chip select pin. The chip select pin enables and disables the device being talked to to use the bus so that other devices can use it.

This website has a bit of info comparing SPI to UART and describing how they work: https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi/all

I2C
This uses a clock line and data line with addressing performed by sending data out onto the bus and the correct device recognises the data as its address and acts on the data that is sent next. The lines are normally held high at the supply voltage level using resistors and can be pulled to 0v by any device, but cannot be pulled high. This means that if something goes wrong and multiple devices try to write to the bus at once, there can be no physical damage through one device trying to pull the line high while another pulls it low and causes a short circuit. This can be moderately fast and is supported by m2 parts.

Hope this helps.
 

neiltechspec

Senior Member
HSPI is not available on M2 chips (unless bit banged), only on X2's.

I2C for RTC's DS1307, DS3231 etc.. Plenty of examples on this forum for those.

Quick example below for DS3231 from my early attempts at I2C.

Code:
#rem

I2C DS3231 RTC test program
Note. the data to/from RTC is in BCD format

I use GMT exclusively

#endrem

#picaxe 08M2
#no_data
#terminal 4800

symbol baud = N4800
symbol oled = C.4
symbol seconds = b0
symbol mins = b1
symbol hour = b2
symbol day = b3
symbol date = b4
symbol month = b5
symbol year = b6
symbol control = b7
symbol temp = b8
symbol counter = b27

init:
    setfreq m4
    hi2csetup i2cmaster, %11010000, i2cslow, i2cbyte ;set RTC slave address
   
    pause 1000
    counter = 1
    sertxd(254,1)
    pause 50

;uncomment the line below to update the clock time
    ;goto set_clock

main:    ;read time and date, send to display
    do
   
    hi2cin $0,(seconds,mins,hour,day,date,month,year)
   
    bcdtoascii seconds,b10,b11
    bcdtoascii mins,b12,b13
    bcdtoascii hour,b14,b15
    bcdtoascii date,b16,b17
    bcdtoascii month,b18,b19
    bcdtoascii year,b20,b21

    sertxd(254,128,"GMT ",b14,b15,":",b12,b13,":",b10,b11)
       
    select case day
     case 1 sertxd(254,192,"Mon")
     case 2 sertxd(254,192,"Tue")
     case 3 sertxd(254,192,"Wed")
     case 4 sertxd(254,192,"Thu")
     case 5 sertxd(254,192,"Fri")
     case 6 sertxd(254,192,"Sat")
     case 7 sertxd(254,192,"Sun")
    end select

    sertxd(254,195," ",b16,b17,"/",b18,b19,"/20",b20,b21)
    pause 1000
   
    loop
   
set_clock:                ;write time and date e.g. 21:16:00 GMT on Fri 01/08/14
                    ;Monday is day 1, Sunday is day 7
    let seconds = $00        ;00 secs
    let mins    = $50        ;16 mins
    let hour    = $04        ;21 hours
    let day     = $01        ;05 day of week
    let date    = $01        ;01 day
    let month   = $01        ;08 month
    let year    = $01        ;14 year
     let control = %00010000 ;Enable output at 1Hz

    hi2cout 0,(seconds,mins,hour,day,date,month,year,control)
    goto main
Neil.
 
Last edited:
  • Like
Reactions: J G

AllyCat

Senior Member
Hi,
HSPI is not available on M2 chips (unless bit banged), only on X2's.
Ah yes, that's why I've never bothered to use it. :) The only time I would consider using SPI would be to interface with another chip that had no other form of interface. Its potential advantage is that it can be "fast" so is often used for "large" displays (i.e. with many independent pixels), but PICaxe cannot usefully directly handle such displays anyway. The protocol is basically very simple, so it's also used for quite basic or "dumb" peripheral components, perhaps better avoided these days.

Serial (UART/RS232) and I2C are really quite similar, they both transmit data bits serially using just 2 wires/pins (for bi-directional communications) and PICaxe can use both "Bit-Banging" and on-chip "Hardware" modes. An advantage of the Hardware is that it can be "faster" (often much faster), but it is limited to usually one pair of dedicated pins on the PICaxe. However, a difference is that the bit-banging Serial "RS232" is supported by the PICaxe Operating System, so is available on most I/O pins and largely "invisible" to the user/programmer. The bit-banging only becomes apparent when you try to do things "quickly". ;)

The other major difference is the "protocol": Serial/UART is basically "transmit and hope", i.e the data bits are transmitted, but it is the responsibility of the user/programmer ensure to that the "receiver software" is arranged to send a Reply (on the second wire) to confirm that the data has been received. I2C is a "Master / Slave" protocol where typically the PICaxe is the Master which initiates (and controls) all the communications and the RTC (for example) is the Slave which returns information when requested. PICaxe X2 chips can be configured as a Slave and extensions such as "Multi-Master" communications are possible, but better avoided.

Generally, I2C is the most "powerful" interface because it is a true "Data Bus", with multiple-addressing capability and high speed, etc., but it is limited to short-distance connections (typically a metre or two). As such, it's essential to use the correct I2C Slave Address, so the "Legacy" UART/RS232 interface still has its place for simple point-to-point communications.

Cheers, Alan.
 

Goeytex

Senior Member
@john green

J G gave a good summary of the most commonly used serial protocols.

As for your Picaxe/RTC project you will find that I2C is the most common way that RTC devices communicate with a microcontroller.

A good example might be inexpensive but full featured MCP7940N by Microchip. However there are many others to chose from depending upon your budget.
 

AllyCat

Senior Member
Hi,

Yes, the vast majority of RTCs use the I2C bus, so you might struggle to find anything else. :) In principle you just need to connect the two bus pins (SCL and SDA), connect two pullup resistors (which often can be those available within most PICaxes) and run the "correct" program/instructions.

Personally, I did choose the MCP7940 because I wanted to (also) use its internal RAM (not EEPROM). But I have to confess that it wasn't as "easy" as I'd expected. First of course, it needed a battery and a 32kHz resonator with the two tiny (6-9pF) capacitors, but then the software was required to change some of its "default" settings, before it ran successfully. So, to be honest, if you are just looking for a "convenient" and accurate RTC, I suggest looking for a DS3231-based breakout module, which includes the resonator circuit, probably the pullup resistors and a coin-cell battery-holder. Some also carry a serial EEPROM chip which may be useful, or there is the tiny little "RTC for Pi" module, (but check whether the rechargeable button cell is supplied). In either case there are several good examples of software and hardware for this chip on the forum, particularly by user marks.

Cheers, Alan.
 
Last edited:
Many thanks to you all for those very instructive responses.

It was finding a couple of DS1302 modules in my possession that inspired the ideas that are now developing far faster than is my understanding of the required coding but it certainly seems very clear that using this particular device is far more of a challenge than wil be sensible for a first (or maybe hundred!) time attempt. I have ordered myself a couple of DS3231 modules as an alternative.

The Sparkfun tutorial suggested by JG is very helpful as are others on SPI and I2C from the same web site these being very much the sort of reading I was looking for and I am now somewhat wiser about the basics.
Now I am seeking explanations on a similar level of detail that might clarify the required information and sequence in which this need to be used to initiate the RTC and then to extract the information from it. I can see this in the program examples but I would like to understand better the whys of this.

I don't actually want or need an ongoing readout of resulting outputs for my imagined projects but it seems it might be a good idea to incorporate an LCD screen to display this information while learning what is going on. Can I presume that this relatively easy using a PIC16C620A and LCD display?
 

AllyCat

Senior Member
Hi,
Can I presume that this relatively easy using a PIC16C620A and LCD display?
Why do you suggest the PIC620A which isn't a PICaxe and doesn't appear remotely suitable for devising your own display. Have you "found" a ready-made module? But you don't need an LCD for development, you can just use the Program Editor's features such as the Terminal Emulator and/or the Debug window.

Cheers, Alan.
 

westaust55

Moderator
John Green,
You can have a read of my “tutorial” on the DS3232 RTC here:

Without checking data sheets I recall the difference between the DS3232 and DS3231 is that the DS3232 has internal battery backed memory (about 256 bytes?).

you do not have to keep reading the time with these RTC. As my tutorial indicates, you can set up to two alarm times/dates and the RTC can generate an interrupt to the PICAXE when the set time occurs.
 
"Why do you suggest the PIC620A which isn't a PICaxe and doesn't appear remotely suitable for devising your own display?"

I beg to differ :) I only suggest that as it's what I have from previous projects (though it is PIC16C620A with the added 16!) and was most certainly purchased from the picaxe store!!
See here... https://picaxe.com/docs/frm010.pdf

But thank you for the suggestion of using debug. I had overlooked that possibility. Much easier.
 

AllyCat

Senior Member
Hi,

Ah, I only searched for "PIC620A" in the PICaxe Store (which found nothing), the forum (which found only this thread) and Google, which said it is a 750 byte "OTP" (One Time Programmable) chip, with no PICaxe (interpreter) programming capability. I had no way of knowing what code might have been pre-programmed into it, which is why I asked if it was a "ready-made" module.

Cheers, Alan.
 
AllyCat, I promise I am not in anyway gloating at your misunderstanding given that in respect of this subject, you are unquestionably one of the experts and I, in reality fast approaching the biblical three score and ten, have pangs of childlike anxiety in the face of my own ignorance. The opportunity to gain from your knowledge is much appreciated...

Thank you also westaust55. I have learnt much from some of your other tutorials so will look forward to working my way through this one you have now suggested.
 

tmfkam

Senior Member
I have never used "Debug" or the serial terminal. It may be easier when using the PicAxe editor on Windows, but it doesn't seem easy on the under supported macOS.

I find that an LCD is so much more useful. For any project that doesn't include an LCD display, a serial LCD module can make all the difference when wondering why things are not doing what I expected. Usually because I've tried to put a Word value into a Byte variable. Yet again...
 

AllyCat

Senior Member
Hi,

@john: Thanks, I was actually quite interested to be "shown" the FRM010; I still have plans to try to "Improve" the AXE13x LCD/OLED software (perhaps skip to post #9 after the "intro"), but I can't decide what additional instruction codes or features might be useful. I had already "found" the AXE033 which also uses a pre-programmed chip, so I would like to make my code "compatible" with some of their instruction/commands. But one problem is that the features of those chips are not even compatible with each other (for example in the method of sending pre-defined text strings) ! :(

@tmfkam: Yes, I've never "used" the Debug feature myself either (I have tested it on occasions) because it potentially "slows down" the program so much. Personally, I prefer to use customised SERTXD commands to the Terminal Emulator, but I was surprised to discover that DEBUG really is quite a decent feature, particularly for novices. ;)

And yes, it is unfortunate that PICaxe is (and probably needs to be) so oriented towards Windows. I would like to "introduce" the grand-children to PICaxe, but they are in a totally "Apple" (mainly iPhone/Pad) -oriented household. :( Therefore, I do try to make nearly all the program code that I contribute to the forum, compatible with AxePad and PE5. But I can only test with WinAxePad, I don't know how compatible that is with Mac and Linux. However, WinAxePad does appear to support both DEBUG and SERTXT commands to a Terminal Emulator (but the missing Simulator is an annoyance), which is basically the way that I've been developing microcontroller software for around 40 years now. :)

Cheers, Alan.
 

WhiteSpace

Well-known member
Interesting discussion. May I butt in and ask what bit-banging is, please, or rather how it’s done? I have seen numerous references to it in various threads - usually just suggesting that it is an option - but despite searching haven’t found an explanation of how to do it. I have recently managed to get two i2c devices communicating with the same Picaxe (more on that project shortly) but it would be useful to understand the alternatives. Thanks
 

J G

Active member
Interesting discussion. May I butt in and ask what bit-banging is, please, or rather how it’s done? I have seen numerous references to it in various threads - usually just suggesting that it is an option - but despite searching haven’t found an explanation of how to do it. I have recently managed to get two i2c devices communicating with the same Picaxe (more on that project shortly) but it would be useful to understand the alternatives. Thanks
Bit banging is when things like serial protocols are implemented using software only, manually setting pins high and low with required pauses and knowledge of the protocol being used. This is without using dedicated hardware built into the microcontroller that would automatically do all communication once set up properly. This might be done because the hardware to use a specific protocol is missing, such as SPI in m2 parts or because of limitations of pins that can be used or inflexibility in the existing hardware, such as most forms of UART serial and program download except for hserout and hserin being bit banged and implemented in software in the picaxe bootstrap.

If you want an example in BASIC of bit banging a protocol such as SPI, have a look at the examples in manual 2 for shiftin and shiftout to implement spi for all parts regardless of the internal silicon. I have used something similar down the bottom of this file to talk to an spi based module.

I haven't studied the exact workings of i2c that much, however I would probably prefer to use the built in hardware if possible as it is generally faster, more reliable, takes up less program space and allows the program to do something else while transmitting data as it does not have to worry about timings or toggling pins correctly.
 

AllyCat

Senior Member
Hi,
... I would probably prefer to use the built in hardware if possible as it is generally faster, more reliable, takes up less program space and allows the program to do something else while transmitting data as it does not have to worry about timings or toggling pins correctly.
Well, Yes and No; I measured the hardware HI2C instructions to be three hundred times faster than bit-banging. :eek:

However, (like HSEROUT) I don't believe that HI2COUT operates (entirely) as a "background" task, (until the last data byte has been encountered). I didn't make comprehensive measurements but my spreadsheet shows the execution time of HI2COUT ... to be about 1150 + 330 * N PIC Instruction cycles (i.e. ~2ms for 3 bytes) , where the (M2) instruction cycles are 1 microsecond each at the default SETFREQ M4 , and N is the number of bytes to be transmitted. HI2CIN was rather faster at around 200 * N ICs , and both were significantly faster than some internal data transfers. A measurement of PEEK b1 , WORD w1 might give you quite a fright. ;)

Cheers, Alan.
 
  • Like
Reactions: J G

J G

Active member
Hi,

Well, Yes and No; I measured the hardware HI2C instructions to be three hundred times faster than bit-banging. :eek:

However, (like HSEROUT) I don't believe that HI2COUT operates (entirely) as a "background" task, (until the last data byte has been encountered). I didn't make comprehensive measurements but my spreadsheet shows the execution time of HI2COUT ... to be about 1150 + 330 * N PIC Instruction cycles (i.e. ~2ms for 3 bytes) , where the (M2) instruction cycles are 1 microsecond each at the default SETFREQ M4 , and N is the number of bytes to be transmitted. HI2CIN was rather faster at around 200 * N ICs , and both were significantly faster than some internal data transfers. A measurement of PEEK b1 , WORD w1 might give you quite a fright. ;)

Cheers, Alan.
Glad someone knows what is going on :).

I have to admit that I assumed the PICAXE serial hardware and firmware behaved in a similar way to the Arduino 328p hardware serial in that I think they add the bytes to send to a buffer and a combination of hardware and interrupts all hidden away does the rest of loading and sending the next byte as required, while your program is free to do whatever it needs to do. This would probably be a little more complex to understand and implement on a picaxe than blocking program execution until all data is sent, especially in the case of the next few instructions relying on all data being sent or interrupts stuffing up the timing of other time sensitive instructions later on. In the case of an Arduino, would calling Serial.flush(); after any Serial.write(); cause it to behave the same way as PICAXE microcontrollers?

As an aside, do you have a link to this magic thread / spreadsheet or can you give any hints about measuring short time intervals? Thanks.
 

AllyCat

Senior Member
Hi,

I'm not "publishing" my spreadsheet because it contains too many inconsistencies. The problem is that many factors affect the speed of execution of PICaxe chips. For example the 08M2 appears to be about 10% faster than the 20M2 and perhaps the X2s about 20% slower (but I never use X2s). The PICaxe Basic interpreter also has some quite "unexpected" characteristics, originally because it was devised to compress the code into a very small program memory space. These characteristics are still retained for "Legacy" reasons and also to protect the Intellectual Property Rights of the Interpreter code.

The "definitive" document on the functionality of the original chips was described by Westaust55 in this thread in 2011 which indicates some of the factors that determine the speed of execution. But that (just) preceded the introduction of the M2 chips which incorporated considerable architectural changes that lead to additional complexity in the coding. These caused a significant reduction in the typical execution speeds (for a given clock speed), but much higher clock frequencies were introduced at the same time.

I contributed to that thread from post #12 onwards, but years later could never remember where it was located in the forum. :( So eventually, I added my own dedicated code snippet thread HERE, which refines my original program. That allows a user to measure the execution time of most PICaxe instructions, or complete code modules, on any (M2) PICaxe target hardware (but not in the simulator) without the need for any other "tools". However, the problem remains in which instructions should be measured (and on what hardware), because there is an enormous number of variants. :(

Cheers, Alan.
 
  • Like
Reactions: J G

inglewoodpete

Senior Member
For example the 08M2 appears to be about 10% faster than the 20M2 and perhaps the X2s about 20% slower (but I never use X2s). The PICaxe Basic interpreter also has some quite "unexpected" characteristics, originally because it was devised to compress the code into a very small program memory space. These characteristics are still retained for "Legacy" reasons and also to protect the Intellectual Property Rights of the Interpreter code.
One of the reasons for the speed difference is that the M2s use a smaller token when compared with the X2s and are therefore slightly quicker to determine what they have to do next.. (The tokens are what the "compiler" creates for the PICAXE chip's internal firmware to interpret). You'll notice that the M2s are limited to just less than 32 registers implying 5-bit tokens, while the X2s have slightly less than 64 registers (6-bit tokens).
 
  • Like
Reactions: J G

J G

Active member
Without meaning to hijack the thread too much, thanks all for the insight and pointers into how PICAXE micros actually behave, are internally set up and the code and results to test them. In the past I have had to calibrate picaxe timings using an arduino as a timer and adjusting pause values to generate acceptable IR signals for a camera, but didn't realise that the instruction time can vary so much based on what is around it.
 

Flenser

Senior Member
I have to admit that I assumed the PICAXE serial hardware and firmware behaved in a similar way to the Arduino 328p hardware serial
JG,

Your assumption about the serial hardware and firmware was correct.

The serial hardware on the PIC chips used for PICAXEs is very similar, although not exactly the same, as the serial hardware on the Atmel 328P chip used for Arduino.

I've not used Arduino yet but I have coded in C and looking at the Arduino serial library it appears that the commands Serial.begin(), Serial.end(), Serial.read() and Serial.write(). provided by the Arduino serial library operate in a very similar way to the HSERSETUP, HSERIN and HSEROUT commands provided by the PICAXE firmware on the M2 chips and for the HSERIN only mode on the X2 chips.

I can't see a function in the Arduino serial library that is equivalent to the PICAXE background serial mode available on the X2 chips.
Similarly there are other functions in the Arduino serial library that don't have an equivalent on the PICAXE.
 
  • Like
Reactions: J G

popchops

Well-known member
Great thread. My problem is that I'm currently using HSPI pins to communicate between a 28X2 and a Texas Instruments digital attenuator PGA3211. (PGA only supports SPI). I really would like to read and write to another smaller 08M2 PICAXE but that only supports I2C, and HI2C uses the same pins as HSPI. :mad:

So looks like I must upgrade the 08M2 to a 20X2 and use HSPI between all three devices with 28X2 as master.
 

popchops

Well-known member
If I want to transmit only via HSPI, what do I need to do with the unused input pin (hspi sdi) on the Picaxe?

The command description for hspiout says:
"Due to the internal operation of the microcontrollers SPI port, a hspiout command will only function when the hspiin 'input pin' is in the expected default state. If this pin is incorrect (e.g. high when it should be low), the hspiout byte cannot be sent (as the microcontroller automatically detects an SPI error condition). After 2.3 seconds of fault condition the PICAXE microcontroller will automatically reset."

What is the 'expected default state'? I'm sure my prototype works with this SDI pin floating, but I'm designing a PCB now and I could use some advice. Thanks in advance.
 

inglewoodpete

Senior Member
Great thread. My problem is that I'm currently using HSPI pins to communicate between a 28X2 and a Texas Instruments digital attenuator PGA3211. (PGA only supports SPI). I really would like to read and write to another smaller 08M2 PICAXE but that only supports I2C, and HI2C uses the same pins as HSPI. :mad:

So looks like I must upgrade the 08M2 to a 20X2 and use HSPI between all three devices with 28X2 as master.
Unfortunately, the Microchip PIC12F1840 chip that is used for the 08M2 only has one Master Synchronous Serial Port (MSSP) peripheral in its silicon. It can only be configured for i2c or SPI and not both at the same time.

SPI is a fairly simple protocol to implement. My suggestion is for you to use the PICAXE 08M2's hardware i2c port for i2c and implement bit-banged SPI on the other available pins. Of course, the 08M2 is a little short on pins! Still, for your application, you only need 2 pins for i2c and 2 pins for SPI. If the 08M does not have enough pins, you could do this on a 14M2.
 
Top