Low Freq PWM and Interrupts

piclt

Member
I was trying to generate a low freq. square wave about 100 Hz with 18M2+ running at 16MHz but PWM only goes down to 244 Hz. So tried to use Interrupts to trigger on rising edge of the PWM and toggle output B.0. This works quite well providing very little code or delay in the main loop. Even small counting and switching procedures seems to upset it. and Touch16 slows it down completely. attached is a test bit of code I was trying. would welcome any ideas. ??

Code:
init:
#picaxe 18m2
pullup off
setfreq m16

'pwmout pwmdiv64, B.6, 255, 511  '200 hz
pwmout pwmdiv64, B.6, 141, 283   ' 441 Hz
' Link B.6 to C.6 (with 220 ohm resistor) - use interrupt on C.6
setint %01000000,%01000000

w2=0
b2=0

main:   
w2=0
'pause 1
pause 100
'gosub docount
'touch16 C.0, w6
'touch16 C.1, w7
'gosub dotouch   
goto main   

interrupt:
' toggle B.0 on count of C.6 rising edges
if b2=0 then toggle B.0
b2=2    'set count of rising edges here
endif
interloop:
    if pinC.6 = 1 then interloop
b2=b2-1       
pause 1
setint %01000000,%01000000
return

dotouch:
touch16 C.0, w6
pause 10
touch16 C.1, w7
pause 10
return

docount:
w2=w2+1
if w2 < 50 then docount
    w2=0
return
 

inglewoodpete

Senior Member
You have struck one of the limitations of the PICAXE, with its tokenised, interpretted code. You have to find a compromise: how fast do you need to process your foreground task versus how slow do you want your background task (PWM in this case)?

As you have found, the polled interrupts that the PICAXE uses will struggle to provide regular 10mS interrupts.

If your need for PWM to run at that unusually slow rate is real (rather than a wish), I suggest you use a second PICAXE, like an 08M2. Even if you were to upgrade to a 28X2 or 40X2, you have an additional impediment in that they cannot use the pwmdiv64 option due to a limitation in the underlying silicon capability.
 
Last edited:

tmfkam

Senior Member
You could use one of the AD9835 frequency generator units purposely designed for this task? Programmable from 1Hz to 25MHz. Once set to the programmed frequency they would then generate the 244Hz without further intervention.
 

piclt

Member
Thanks for replies. I thought the interrupts would be have been working away in the background. The interrupt routine has to wait till the interrupt clears which I assume is the pwm pulse on C.6 going to zero before setting the setint again. Is that the main problem. If back running in main loop should the next interrupt not be caught no matter what it is doing. It seems as though that during touch16 the interrupt is not detected until the touch16 statement is completed...??. The 18M2+ has SRLATCH, I can set this with the pwm pulse but cannot see a way to reset it on time to give 50%duty pulses from SRQ. or get it to work like a toggle flipflop divide by 2. ?? Also seems it can work as 555 timer....didnt figure out how that works yet ??
 

AllyCat

Senior Member
Hi,
It seems as though that during touch16 the interrupt is not detected until the touch16 statement is completed.
Yes, that is correct, all the M2 interrupts are polled , so tested and executed only between individual Basic instructions, during PAUSEs, and maybe a few of the more complex (internal Macro) instructions. Note also that the "Touch" system uses two internal Timers (I believe T0 and T1) so there may well be "interactions" with the PWM outputs, and perhaps other timed functions.
..... cannot see a way to reset it on time to give 50%duty pulses from SRQ. or get it to work like a toggle flipflop divide by 2. ?? Also seems it can work as 555 timer....didnt figure out how that works yet ??
No, the S-R Latch is a hardware feature of the "base PIC" and IMHO is of almost no use in PICaxe applications. It has only one "trigger" input so is more intended as a "Monostable" Latch, but the (clocked) delay intervals are so short that even the longest is much less than the execution time of a single PICaxe instruction. There is also no formal way to read its state, so I find the Timer 1 Gate Hardware and the "Interrupt on Change" Flags to be of more value.

Back to the original post: Yes, low frequency PWM capabilities are quite limited, particularly at higher clock rates (and with the X2s). But it is easy to generate 50 Hz pulses by using the SERVO command (including at 4x the default clock frequency, i.e. 16 MHz), or 100 Hz at 32 MHz. The (up to 8) servo pulses are generated sequentially (by internal firmware) so if you were desperate for 100 Hz (interrupts) at M16, you might cascade 4 - 6 Servo channels, set to about 2.5 ms each. ;)

Cheers, Alan.
 

oracacle

Senior Member
funny you memntion the 555, not really related but still interseting and you maybe able to take something away and apply it here (came across while randomly consuming random internet videos)
I2C Enabled 555 Noise Maker Controlled by Arduino Uno - YouTube
Using a digital potentiometer to vary the freqency output of a 555, that pot can be controlled by which ever micro controller you choose. I supose you could even fly back from the output of the 555 to the picaxe and adjust to the frequency you want. A kind of closed loop PWM.
The downside is that amount of extra components, and possibly pins on the picaxe depending on how you coose to control it.
 

piclt

Member
yes, Noise Maker is interesting and seems to work very well, but too many bits for what I am doing now. I was wanting a one chip project with very little else connected.
I have tried out inglewoodpete post #2 suggesting adding a 08m2 and there is not much simpler than that. Just one prog statement to start the PWM.
I have the 18M2 at setfrq m16 running some touch pads and the higher freq. PWM output with the 08M2 at setfreq m4 doing the low freq. PWM output only.
 

oracacle

Senior Member
I was thinking you could take the section where the astable 555 could be adjusted using a digital pot. Dispence with the rest of it and you have a PWM signal that can adjusted down as low as you like. But I must agree using a 08m is a good solution too, and will be alot flexible, you could use it as a clock divider if needed, or have it on a serial bus to update its PWM ouput.
 

piclt

Member
I thought I would have another try at getting the 18m2+ internal 555 timer to run....but no joy..???
I can set and reset it with SRSET and SRRESET. and trigger it to set/reset with PWM signal linked into SRI.
But cannot get is to run as an oscillator being pulsed from the internal clock that it is supposed to have or else the clock for it needs enabled somewhere..?? I have read the manuals and the Microchip datasheet and tried what I thing is every option in the SRlatch config command but no joy.....????
 

piclt

Member
I have now got the internal 555 timer of the 18M2+ working. It needs config set to..... srlatch %10101000, %01001000. In config1 the divider bits does not seem to matter and in config2 it needs clock to set the srlatch and SRI high to reset it. And a Res + Cap on SRQ to give the time constant with the Cap voltage fed into the SRI. It works free running from the Picaxe code freq is set by the RC circuit. So as above in post#8 a digital pot should work. It is interesting I could not find any help anywhere on the datasheets or manual about this aspect of the config.
The Picaxe manual says " The SR latch also contains an internal clock source. This means the SR latch can be optionally configured to act like a ‘555 timer’. " No mention of RC circuit and it reads as though the 555 was controlled from the internal clock only ....????......
Wondering has anybody any ideas how better to set it up.
It now means I can generate a low freq pulse out and at same time a high freq PWMout and not affect the running or timing of the main prog loop.
The 555 and the PWM are not slowed down by the long touch16 commands either and the touch16 is still "fast"
 

AllyCat

Senior Member
Hi,

Is the frequency stable and "predictable" (i.e. capable of calculation from knowledge of the capacitor value, and stable if the supply voltage varies)?

I don't think that using an external capacitor and resistor(s) was the "intended" function of the S-R Latch. But in principle it's possible to build an oscillator by using an "external" capacitor, a resistance and a few CMOS gates (regardless of their "intended" purpose). Basically you just need a "Threshold Detector" (e.g. the input of a CMOS gate) and some "Hysteresis", which can use a "Schmitt Trigger" Input Gate, or some form of positive feedback (e.g. two inverting gates in series).

In addition to the Gates which form the S-R Latch, you could probably use the PICaxe's "Data Signal Modulator" (DSM), or certainly the internal Comparator(s) which can be also modulated in amplitude and/or frequency by the "DAC" resistor chain. Or you could even put a "large" capacitor onto one of the "Touch" pins and use that as a low frequency oscillator. One advantage of microcontrollers (as opposed to microcomputers) is that their application is limited mainly by the imagination (and knowledge) of the user. ;)

Cheers, Alan.
 

piclt

Member
"Is the frequency stable and "predictable" " .....Yes, as stable as my setup is ??...I am on a breadboard powered with a battery box.
I only looked at low freq tones which I can hear on a speaker or watch in Audacity .... not high speed stuff driving motors.
As a sort of test I set freqs say 200 hz or 400 hz on pwmout and set the 555 timer to 100 hz (I had a 0.1uf and a 220k res for 100Hz outroughly) and listened on speaker, both stayed in tune and looking at it in Audacity waveforms were good and played back ok. The mark space ratio of the 555 was about maybe 40%. I couldn't see how I could adjust that a real 555 has threshold and trigger. I didn't think the comparators were available on the 18M2 and didn't try anything with the DAC.??? maybe need to look at that. manuals are not very descriptive??....need some pointers
I tried a few combinations of resistors with the 0.1 uf Cap....figures as below.
220k .........104 Hz
100 k ....... 230Hz
69k ........335 Hz
320k ....... 72Hz
175k ......128Hz
267k ...... 86Hz
289k ...... 79Hz
314k ..... 74 Hz
Not maybe linear but not bad??

This is my simple test code

Code:
'Minimal code to get internal 555 timer working
' on Picaxe 18M2+
'Required.... R-C circuit between SRQ output pin and Ground with SRI input pin connected to junction of R and C.
' ... 0.1 uf and 220 Kohm give about 100 Hz

#picaxe 18m2
setfreq m16

srlatch %10101000, %01001000 ' clock sets srlatch, SRI high resets it.

main:
'do what you want here
goto main
 

AllyCat

Senior Member
Hi,
I didn't think the comparators were available on the 18M2 and didn't try anything with the DAC.??? maybe need to look at that. manuals are not very descriptive??....need some pointers
The Comparators are in all the modern M2 chips, as is the Data Signal Modulator, the Timer1 Gate, the Interrupt-on-Change Flags, the Alternate Pin Function Registers, and numerous other features not directly supported by the Interpreter, but accessible via the POKE/PEEKSFR commands. IMHO the "DAC" is relatively useless for generating output signals, but ideal as a programmable internal bias network for the Comparators, etc.. The PICaxe manuals can't be expected to be of much use for these more complex features; you need to delve into the relevant Microchip base PIC Data Sheet ("Advanced Technical Details" link).

Cheers, Alan.
 

piclt

Member
I have looked at it on my scope. Good square waveform on SRQ 0 volts to 4 volts. Good triangular waveform on SRI 1.5 volts to 2.0 volts.
SRQ goes high (sets) at point when SRI falls to 1.5 volts. SRQ goes low (resets) at point when SRI has risen to 2.0 volts. looks like level triggered.
although config set for clock pulse to set. Mark/space ratio varies with freq. at about 1 Khz is 46% and at about 37 Hz is 56%. but seems very stable.
trigger volts level stays same 1.5 volts to 2.0 volts at high and low freq. (triangular wave SRI)
 

AllyCat

Senior Member
Hi,
looks like level triggered .. although config set for clock pulse to set.
When the PIC{axe} is configured as the S-R Latch, the SRI pin is switched to a Schmitt Trigger (ST) input, so it's probably just acting as a traditional Single-(Schmitt)-Gate oscillator. Thus, alternatively, the oscillator probably could be configured around the DSM module, which also has ST-input pins.

Unfortunately, the ST Hysteresis (i.e. the voltage between Lower and Upper thresholds) is not characterised in the Data Sheet, so the operating frequency is not accurately "predictable" (from the Data Sheet). Configurations based on a half-Vdd threshold (e.g. "Pure" CMOS levels), or the classical discrete transistor "bootstrap" (voltage-doubling) arrangement, can be preferable because their period is always around the theoretical 0.7 * C * R. I can't explain why the duty cycle is changing, but then I don't know what component is causing the frequency to change. :)

The configured "clocked" Set pulse is probably being "ignored" because, as the Data Sheet says, "The [S-R] Latch is Reset-dominant. Therefore, if both Set and Reset inputs are high, the latch will go to the Reset state", and the capacitor will be still holding the input High at this time.

Cheers, Alan.
 

piclt

Member
Trying out alternatives .... If I set config2 bit6=0 the clock shoudn't be able to set the SRlatch. and 555 timer does not run with the RC circuit connected.
So, instead (still with bit6=0) if I put a SRSET in prog above the main loop it should set the SRlatch, start charging the capacitor and when cap. reaches 2 volts the SRlatch resets, but then after that first pulse there nothing to keep it running, so just get one pulse out only.
If I put a SRSET inside main loop this will set the latch, so the cap charges and resets the latch. The latch is set again on next round of main loop. This works and keeps it going, but time periods depend on length of command processing within the main loop. The cap volts can drop down below 1.5 volts even down to zero and latch will not set until the next SRSET is run again in the mainloop.
If I put back config2 bit6=1 again then the waveform seems to always be controlled by capacitor volts on SRI. .... 1.5 volts to SET and then charge cap up to 2 volts to RESET. There is slight difference in charge and discharge rate ... more noticeable on very low frequencies which seem to be cause of the change in mark/space ratio.
 

Attachments

AllyCat

Senior Member
Hi,

Yes, the first screenshot appears closest to the "expected" / predictable operation. The delay on the (internal) Set pulse is at most a few microseconds, so it's effectively always High. But the Reset input on SRI is "dominant", so the "Latch" simply follows the input signal, inverted on the SR(N)Q output. Thus it operates as a simple Schmitt Trigger inverting gate, with no significant "Latching" function as such.

The resistor values are quite high, so the average "discharging" current is about V / R = 1.75 / .220 = 8 uA, and the charging current = 2.25 / .220 = 10.2uA. But actually, the positive gradient is slightly less, so the effective charging current must be lower. Therefore, it looks as if there is a "leakage" of around 1.5 uA from the SRI / Capacitor down to Ground. Maybe that's inside or outside of the PICaxe? With the 487k resistor, the effective pullup current is around only 2.25 / .487 = (4.6 - 1.5) uA, so the effective current is about 3 uA, then the pull-down (3.6 + 1.5) uA = 5 uA giving the approximate 3 : 5 duty cycle.

In the third screenshot, the (clocked) "Set" pulse is disabled, so the SRI voltage falls until the Program initiates the "ramp up" state. Thus this appears to be basically a Program-triggered Monostable mode.

Cheers, Alan.
 

piclt

Member
The project I have at the moment is fairly basic I just need one pwm ouput for high frequency and another output for low frequency with the system running at 16 mhz for speed. The 18m2 lets me do that now that I have got the 555 timer working and both these don't need interrupts so dont affect timing of the rest of the program, but I was just trying to understand better how 555/SRlatch works. Thankyou for the time you have taken to provide help but I don't follow your reasoning or maybe I am mixing up the screenshot you are referring to..?.
The 3 screen dumps are actual dumps of picoscope with the 18m2 running, all 3 are the same picaxe wired the same. SRQ is connected always to the resistor of the RC with C to ground. The SRI pin is connected to the RC junction always. I don't have a SRNQ pin or a SET or RESET pin on the 18m2.
If we consider the 3rd screen dump "SRlatch18m2SRSETlooppause1000.jpg. This has bit6=0 and bit7=0 so config2 says that SRI high does not SET latch NOR Clock will not pulse SET latch, so it won't set or oscillate except by software SRSET command or "peeking or poking". I can see that from the waveform and you can see the SRSET command do it every 250 ms as per the delay in the loop. Setting SRQ high then charges the cap. and when voltage on cap and SRI rises to 2 volts the latch resets and waits on the next SRSET from the main loop.
If we consider the the first 2 screen dumps SRlatch18m2ClksetRCreset.jpg and SRlatch18m2ClksetSRIreset.jpg. both these 2 have the same config2 setting, that is bit7=0 and bit6=1 which the manual says that "Latch SET pin IS pulsed by clock". The bit I dont see is how can the SET interval be 9 ms on the higher freq wave and about 45 ms on the lower freq wave if it is supposed to be pulsed by the clock and no changes made to the clock period .....what clock are we talking about..??.... setting the clock divider bits in config1 doesn't make any difference. The voltage on SRI when the latch SETs and RESETs is same in both cases 1.5 volts and 2.0 volts.....?
 

Attachments

AllyCat

Senior Member
Hi,

I must admit that I've never looked practically into the S-R Latch, because its "intended" operation uses the (~1MHz) system clock, divided by 1 ... 128 (max), which are all pulses far shorter than a PICaxe's single instruction (~400 us). Also, having only one External input pin, it is arguably hardly a "Set-Reset" Latch, since either an External S or R must be preset by the hardware/software configuration.

However, the S-R is fundamentally a "symmetrical" design, so the differentiation between Set and Reset (or Q and NotQ) is largely arbitrary, except for the "Reset Dominance". For the ST-inverter type of oscillator to work ("Ramp Up when the Input is Low, and Ramp Down when it is High"), the Output needs to be the inverse of the Input, so with the High input (Reset) dominant the Q output (Reset = Low) should indeed be used. The Low and High thresholds of the oscillation are simply those of the largely Undocumented Schmitt Trigger (ST) Input characteristic, i.e. Low Input Threshold (parameter D031) => 0.2 Vdd, High Input Threshold (D041) =< 0.8 Vdd (for which the measured values of 1.5 and 2.0 volts are of course compliant). :(

PIC-InputCharacteristicST.pngPIC-SRIcharacteristicT.png

A non-inverting "bootstrap" configuration is also possible, by connecting a Capacitor to the Output(s), but generally has issues with Integrated Circuit designs (because IC input voltages are required to always remain between the Supply and Ground rails). Or an oscillator configured around the Comparator(s) can use adjustable, defined thresholds.

Cheers, Alan.
 
Last edited:

piclt

Member
Regards to 3 screenshots again....
The 3rd one is simple enough....it simply is set by SRSET and reset at time period after that when SRI voltage rises to 2 volts...then repeats at speed of main loop.

For the other 2 screenshots ... The SRCLK is gated to SET(S) if SRSCKE=1. This will SET the SRlatch and cause SRQ to go high because bit7 = SRLEN=1 and bit3 = SRQEN=1.
The cap will charge and raise the volts on SRI. SRI is gated to RESET if bit3 = SRRPE=1 (peripherial reset enable) and when SRI reaches 2 volts that will trigger RESET of the latch (above high value and reset dominates). SRQ goes LOW and the cap discharges and SRI volts fall and when 1.5 volts it is below the threshold to be "HIGH" and the latch SETs again due to HIGH still on SET(S). And process repeats. Does that mean that this particular config is using the internal hysteresis of the SRlatch and not programmable. To be programmable we would need to enable the C1out or C2out....but only available on picaxe X2 parts. ??
 

Attachments

AllyCat

Senior Member
Hi,
Does that mean that this particular config is using the internal hysteresis of the SRlatch [input gate] and not programmable. To be programmable we would need to enable the C1out or C2out....but only available on picaxe X2 parts. ??
Yes, that's (all) correct, except that the Comparators are available (Rev Ed can't take them out :) ). It's just there is no direct support for configuring their operation. But many of the PICaxe SETUP... and CONFIG... commands are basically just POKESFR ... under another name. So it's easily possible to use many other hardware functions, simply by reading the data sheet (and understanding the PEEK/POKESFR address mapping). I suspect that POKESFR $5A , %10101000 , %01001000 ' clock sets srlatch, SRI high (dominantly) resets it (untested) will work just a well.

Cheers, Alan.
 
Top