DC Motor

Let’s make Circuit 12 from the manual.

A DC motor works like an LED.

 
int motorPin = 9;
int onTime = 3000;  // milliseconds to turn the motor on
int offTime = 3000; // milliseconds to turn the motor off
  
void setup(){
  Serial.begin(9600);
  pinMode (motorPin, OUTPUT);
}
 
void loop(){
 
digitalWrite(motorPin, HIGH); // turn the motor on (full speed)
delay(onTime);                // delay for onTime milliseconds
digitalWrite(motorPin, LOW);  // turn the motor off
delay(offTime);  
}

Things get a bit more complicated when you want to control the speed.
Let’s control the DC motor using a potentiometer:

int analogInput = 0;
int motorSpeed = 0;

int motorPin = 9;
int potentiometerPin = A1;


void setup(){
  Serial.begin(9600);
  pinMode (motorPin, OUTPUT);
  pinMode (potentiometerPin, INPUT);
}
 
void loop(){
  
  analogInput = analogRead(potentiometerPin);

  Serial.println(analogInput);
  motorSpeed = map(analogInput, 0, 1024, 100, 0);
  digitalWrite(motorPin, HIGH); // turns the motor On
  delay(motorSpeed);                // waits for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turns the motor Off
  //delay(motorSpeed);  
  
  //analogWrite (motorPin, motorSpeed);
  
}

You can find more structured code in the SIK guide Circuit #12.

This is the circuit for the bigger white DC motor, it uses the big transistor:

Posted in

Post a comment