There are four sections to the code. The first is the declarations section and defines the names of the pins to use. The second is the setup routine, that is stuff that only happens once. The third section is the loop which repeats for ever while there is power. Lastly there are subroutines.
In the declarations I use const for pin names because they won't change. I use int because all of the examples do, but really I feel we should use byte. byte is only one byte, (int is two) and byte can only be positive. These suit the pins perfectly and would save one byte per pin - a few bytes might be important on these small controllers, but not in this case. There could be a down side if conversions take place - I'll experiment later. Setup includes a call to a routine which blinks the on-board LED. If the board resets for any reason the blinks will give it away.
The loop sets up the motor in one direction and steps up the speed to full speed in the for loop. It then stops the motor, giving it time to stop, reverses the motor and steps it up to full speed again. Then it stops the motor before the loop repeats.
The subroutines only have the blink routine, used to blink the on-board LED.
const int mot1Pin = 7;
const int mot2Pin = 8;
const int enablePin = 9;
const int ledPin = 13;
void setup() {
pinMode(mot1Pin,OUTPUT);
pinMode(mot2Pin,OUTPUT);
pinMode(enablePin,OUTPUT);
pinMode(ledPin, OUTPUT);
//demonstrate a reset by flashing the led
blink(ledPin,3,300);
//disable the motor
digitalWrite(enablePin, LOW);
}
void loop()
{
// simple test to change a motor speed bit by bit
// first set the motor in one direction
digitalWrite(mot1Pin, LOW);
digitalWrite(mot2Pin, HIGH);
//run the motor in stages up to full speed
for ( int i=0;i<255; i+=60) {
analogWrite(enablePin, i);
delay(1000);
}
analogWrite(enablePin, 255);
delay(1000);
//stop the motor
analogWrite(enablePin, 0);
digitalWrite(mot1Pin, LOW);
digitalWrite(mot2Pin, LOW);
// pause to allow stop
delay(2000);
//reverse
digitalWrite(mot1Pin, HIGH);
digitalWrite(mot2Pin, LOW);
//run the motor in stages up to full speed
for ( int i=0;i<255; i+=60) {
analogWrite(enablePin, i);
delay(1000);
}
analogWrite(enablePin, 255);
delay(1000);
//stop the motor
analogWrite(enablePin, 0);
digitalWrite(mot1Pin, LOW);
digitalWrite(mot2Pin, LOW);
// pause to allow stop
delay(2000);
}
// blink an LED
void blink(int pin, int num, int pause) {
int p=pause/2;
for ( int i=0;i
digitalWrite(pin, HIGH);
delay(p);
digitalWrite(pin, LOW);
delay(p);
}
}
No comments:
Post a Comment