Shop OBEX P1 Docs P2 Docs Learn Events
Incrementing a variable at a certain frequency — Parallax Forums

Incrementing a variable at a certain frequency

smbakersmbaker Posts: 164
edited 2011-06-04 23:34 in Propeller 1
I have a variable, and I'd like it continuously incremented at a frequency (frequency to vary between 1 Hz and 100,000 Hz, as specified from another cog). Currently I have this implemented in a cog:
VAR
  long freq

PUB setFreq(x)
  freq := x

PRI countLoop
  repeat
      if (freq>0)
          value := value + 1
          waitcnt(clkfreq/freq + cnt)
      else
          ' freq = 0, wait a while to see if someone changes it
          waitcnt(clkfreq/10 + cnt)

The code works pretty well, but ties up a cog. I can see from the manual that the prop has several different counter modes, although I don't really understand how to use them, nor do I see an example that does exactly this sort of thing. Any suggestions?

Thanks,
Scott

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2011-06-03 22:19
    Yes, it ties up a cog. That's why you have 8 of them.

    Each cog does have two counters and each of them can be incremented at the system clock rate or in response to an external input. You can set up the two counters so that one of them toggles an I/O pin at a frequency related to the system clock and the the second counter counts the positive (or negative) transitions of the I/O pin. The I/O pin doesn't have to be connected to anything, just configured as an output. Just don't try this at a frequency close to the system clock rate (80MHz usually).
  • localrogerlocalroger Posts: 3,452
    edited 2011-06-04 18:19
    Scott, as Mike Green says you can use the counters to do something like this, but the problem is you can't use the counters to do it to a variable in Hub RAM. The counters do it to a register which is in the Cog RAM of the cog that owns the counters. So while you don't need to run actual PASM (or Spin) code to update the var, if you want it echoed to Hub RAM you do need to run code to copy it. Depending on the other processing you are doing you might be able to interleave this with some other processing in a single cog.
  • smbakersmbaker Posts: 164
    edited 2011-06-04 23:34
    Currently I have cogs to spare, so it isn't a problem. I was just wondering if there was some clever mechanism that I was missing (the prop is full of clever ways to do things!). I'm going to have to try out Mike's suggestion of using two counters and a pin. If not for my current project, then some time just to see how it works. Counters in general are something I'd like to get some more practice with. I've used them a few times for PWM, but only by using existing code examples without really taking the time to understand how they're actually working.
Sign In or Register to comment.