0% found this document useful (0 votes)
2 views1 page

Arduino Motor Control Code Example

The document contains an Arduino sketch for controlling a motor's speed and direction using PWM signals. It defines constants for pin assignments and motor directions, initializes pins in the setup function, and adjusts the motor's speed based on input from two switches in the loop function. The motor speed increases when a switch is pressed and decreases when neither switch is activated, with a maximum speed limit set at 255.

Uploaded by

mostafa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Arduino Motor Control Code Example

The document contains an Arduino sketch for controlling a motor's speed and direction using PWM signals. It defines constants for pin assignments and motor directions, initializes pins in the setup function, and adjusts the motor's speed based on input from two switches in the loop function. The motor speed increases when a switch is pressed and decreases when neither switch is activated, with a maximum speed limit set at 255.

Uploaded by

mostafa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#define PWM 3

#define DIRECTION 2

#define RIGHT 4
#define LEFT 5

#define RIGHT_DIRECTION 1
#define LEFT_DIRECTION 0

#define MAX_SPEED 255

#define SWITCH_DETECCT 0

short int pwmValue = 0;

void setup() {
// put your setup code here, to run once:
pinMode(DIRECTION, OUTPUT);
pinMode(PWM, OUTPUT);
pinMode(RIGHT, INPUT_PULLUP);
pinMode(LEFT, INPUT_PULLUP);
}

void loop() {
// put your main code here, to run repeatedly:
byte rightDirection = 0;
byte leftDirection = 0;

byte directionOfTheMotor = 0;
rightDirection = digitalRead(RIGHT);
leftDirection = digitalRead(LEFT);

if (rightDirection == SWITCH_DETECCT)
{
directionOfTheMotor = RIGHT_DIRECTION;
++pwmValue;
pwmValue = pwmValue < MAX_SPEED? pwmValue: MAX_SPEED;
}
else if (leftDirection == SWITCH_DETECCT)
{
directionOfTheMotor = LEFT_DIRECTION;
++pwmValue;
pwmValue = pwmValue < MAX_SPEED? pwmValue: MAX_SPEED;
}
else
{
pwmValue = pwmValue > 1? pwmValue: 1;
--pwmValue;
}
analogWrite(PWM, pwmValue);
digitalWrite(DIRECTION, directionOfTheMotor);
delay(100);
}

You might also like