We will show how to use interrupt in the program to cope with real world input. There are two examples for the same problem. One example uses second interrupt to generate time-based. Second example uses real-time clock instead of the interrupt in generating time-based.
Assume square wave input port generates events. Every transition from 0 to 5 is an event (positive transition). The number of events over a time period is counted.
This time period is easily determined by interrupt, using int1. Port 11 is a square wave input with period 1000. Therefore it will generate 10 events during the simulation time (10,000 ticks). If we use time base 4000, int1 will generate 2 interrupts. We can use the first one as 'start' and the second one as 'stop'. The time period will be the interval between interrupts, 4000 ticks.
Int0 is used to monitor the input. Every positive transition is counted. We detect the positive transition by detecting the change from 0 to 5. Detecting a transition is done by comparing the current reading with a previous reading (in lastx). Let ecount by the count of all positive transitions.
int0()
x = readport(11)
if lastx != x then
if x == 1 then ecount++
lastx = x // update
lastx
Interrupt1 is used to toggle the state of 'start' counting and 'stop'. flagstart is the current state of counting. At the end of the counting period (at the secont interrupt1) the total count in that period is reported (cnt2-cnt1).
int1()
if flagstart == 0 then
flagstart = 1
cnt1 = ecount
else
flagstart = 0
cnt2 = ecount
print(cnt2-cnt1)
main()
settimer0(200)
settimer1(4000)
flagstart = 0
ecount = 0
lastx = readport(11)
while(1)
doze()
We show how to use a real-time clock to determine the time period in the above counting events example. Port 13 connects to a real-time clock. This clock outputs the number of clock since the start of simulation. Each tick denotes one instruction executed. We can determine a time period by remember a starting time (t1) and keep monitoring the real-time clock until it is over our goal. Let assume we need 4000 ticks period then we can check is the current time is over t1 + 4000.
t = readport(13) // real-time clock port
if( t > (t1 + 4000))
process(t)
Once the report is done, we can update t1 to the current time to start a
new period. Please note that we do not use int1 as start/stop
anymore. int0 is used to monitor the positive transition as before
and now it is also used to check the time period. Here is the full
program.
// global
lastx, ecount
cnt1, cnt2, t1
process(t) // forward declaration
#noframe
int0()
x = readport(11)
if( x != lastx )
if ( x == 5 ) ecount = ecount + 1
lastx = x
t = readport(13) // master clock port
if( t > (t1 + 4000))
process(t)
process(t)
cnt2 = ecount
print(cnt2 - cnt1)
cnt1 = cnt2
t1 = t
main()
settimer0(200)
lastx = readport(11)
ecount = 0
t1 = 0
cnt1 = 0
while(1)
doze()
last update 29 Jan 2018