Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- April 3, 2019
- Reddit motor + servo driver
- Board = Uno
- This sketch sets a DC motor to spin at a single speed, and moves a servo back and forth between two settings.
- The DC motor speed is assumed to be set by PWM also.
- */
- int dc_motor_pin = 3; // The PWM input to the DC motor controller is connected here.
- int dc_motor_speed = 128; // This is the speed setting for the DC motor, that can range from zero to 255.
- // This assumes that you are using a DC motor controller that allows setting the motor speed with a PWM value.
- int servo_pin = 5; // The servo control pin is connected here.
- int servo_interval_time = 100; // This is the time interval that the servo will change at, in milliseconds.
- int servo_change_value = 5; // This is the amount that the servo will change, at each change interval.
- int servo_current_value = 32; // This is the starting point for the servo. It must be a number between the minimum and maximum value.
- int servo_minimum_value = 32; // This is the low end of where you want the servo to stop at. Zero is the lowest value you can put here.
- int servo_maximum_value = 200; // This is the high end of where you want the servo to stop at. 255 is the highest value you can put here.
- int servo_direction = 1; // This variable will flip back and forth between 1 and -1.
- // Setting it to 1 will make the servo begin by turning upwards, and setting it to -1 will make the servo begin by turning downwards.
- void setup() {
- analogWrite(dc_motor_pin, dc_motor_speed); // This sets the DC motor on at a fixed speed.
- }
- void loop() {
- change_servo_value(servo_change_value, servo_direction);
- check_current_servo_value();
- analogWrite(servo_pin, servo_current_value);
- delay(servo_interval_time);
- }
- void change_servo_value(int changeValue, int servoDirection) {
- // This changes the servo value up or down, depending on if servoDirection is 1 or -1.
- servo_current_value = servo_current_value + (changeValue * servoDirection);
- }
- void check_current_servo_value() {
- // This prevents the servo from turning past the minimum and maximum values,
- // and changes the direction when it hits either of the end values.
- if (servo_current_value < servo_minimum_value) {
- servo_current_value = servo_minimum_value;
- flip_servo_direction();
- }
- if (servo_current_value > servo_maximum_value) {
- servo_current_value = servo_maximum_value;
- flip_servo_direction();
- }
- }
- void flip_servo_direction() {
- // Because the direction control value is 1 or -1, you can change it to the "other" value just by multiplying it by -1.
- servo_direction = servo_direction * -1;
- }
Add Comment
Please, Sign In to add comment