Basic DC motor sketch

The C sketch for running the DC motor using a push button is provided in the following. The sketch is designed to run the motor for 1 second and then stop it every time the push button is pressed.

The code in this chapter may be freely downloaded from the location for this chapter mentioned in Chapter 1, Boot Camp.

The following code is a basic DC motor sketch:

//**********************************************************/ 
// Step-1: CONFIGURE VARIABLES
//**********************************************************/
int motorPin = 3; //this is a PWM capable pin
int buttonPin = 8;
int buttonState = LOW;

//**********************************************************/
// Step-2: INITIALIZE I/O PARAMETERS
//**********************************************************/
void setup()
{
pinMode(motorPin, OUTPUT);
pinMode(buttonPin, INPUT);
}


//**********************************************************/
// Step-3: MAIN PROGRAM
//**********************************************************/
void loop()
{
buttonState = digitalRead(buttonPin);

if(buttonState == HIGH)
{
analogWrite(motorPin, 160); //run the motor
delay(1000);
analogWrite(motorPin, 0); //stop the motor
}
}

Now let us understand the preceding program. As soon as the push button is pressed, the program reads the status via pin 2 and enters the if block and executes the analogWrite(motorPin, HIGH) statement; sending an analog signal on pin number 3, which in turn switches the transistor ON. This allows the current to flow across the motor and make it run.

After a delay of 1 second, the analogWrite(motorPin, 0) statement executes and sends a near zero voltage signal on pin 3. The very low signal turns the transistor OFF, thereby breaking off the power supply circuit of the DC motor. The preceding cycle is executed every time the push button is pressed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.129.19