View Single Post
  #2   Spotlight this post!  
Unread 28-01-2008, 13:14
GRS GRS is offline
Registered User
FRC #1764
 
Join Date: Jan 2008
Location: KC, MO
Posts: 34
GRS is an unknown quantity at this point
Re: Program a motor to turn on and off every other second.....

Here's some untested code that should do what you're asking, basically this code toggles pwm01 between 0 and 127 every 44 loops, and makes pwm01 go back to off if the button is not pressed.

A static byte causes the compiler to not delete the data in a variable after it leaves a function, and "loops++" tells it to add 1 to the variable and store it back into itself, essentially saying loops = loops + 1

Code:
void code()
{
  static byte loops = 0; // which loop are we on?
  if (p3_sw_trig != 0)
  {
    loops++; // add 1 to the loop counter
    if (loops <= 44) {
      pwm01 = 127; // motor off
    } else if (loops <= 88) {
      pwm01 = 0; // motor on
    } else {
      loops = 0; // go back to 0
    }
  } else {
    pwm01 = 127; // switch not on, motor is off!
  }
}

Last edited by GRS : 28-01-2008 at 13:17.