This program controls a DC motor attached to the microcontroller via a transistor or relay. Adaptation to make the motor speed change by Ryan Holsopple.
A simple version is at the bottom of the page
/*
DC motor control
by Ryan Holsopple
modification of Tom Igoe's DC motor code
I added function to start motor turning in one direction
I raised the threshold for my pot to work
**r.holsopple
Created 8 Feb. 2006
*/
int sensorValue = 0; // the variable to hold the analog sensor value
int sensorPin = 0; // the analog pin with the sensor on it
int motorPin = 9; // the digital pin with the motor on it
int threshold = 300; // the theshold of the analog sensor below which the motor should turn on
int forwardPin = 7;
int backwardPin = 8;
// prototype of the function that changes the motor's speed:
void changeMotorSpeed();
//function to begin motor turning in one direction
void forwardDirection();
void setup() {
// declare the inputs and outputs:
pinMode(motorPin, OUTPUT);
pinMode(forwardPin, OUTPUT);
pinMode(backwardPin, OUTPUT);
pinMode(sensorPin, INPUT);
}
void loop() {
// read the analog sensor
sensorValue = analogRead(sensorPin);
// determine whether its above or below the threshold
if (sensorValue > threshold) { // it's above the threshold
// turn off the motor
digitalWrite(motorPin, LOW);
}
else {
//start motor turning forward
forwardDirection();
// change the speed of the motor based on the sensor value:
changeMotorSpeed();
}
}
////////////////////////////////////////
void forwardDirection(){
digitalWrite (forwardPin, HIGH);
digitalWrite (backwardPin, LOW);
}
void changeMotorSpeed() {
analogWrite(motorPin, sensorValue);
}
The simple version:
int motorPin = 9; // where the transistor's base is attached
int analogPin = 0; // Analog input number for the potentiometer
int analogValue = 0; // variable for the analog reading
void setup() {
pinMode(motorPin, OUTPUT);
}
void loop() {
analogValue = analogRead(analogPin);
if (analogValue > 512) {
// turn the motor on
digitalWrite(motorPin, HIGH);
} else {
// turn the motor off
digitalWrite(motorPin, LOW);
}
}