I want to move servo motors for loop without stopping! What is wrong?
#include <Adafruit_PWMServoDriver.h>
#include <Wire.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
int motors[] = {0, 1, 2, 3};
int degrees[] = {0, 0, 0, 0};
void setup() {
Serial.begin(9600);
pwm.begin();
pwm.setPWMFreq(50);
pwm.setOscillatorFrequency(27000000);
for(int i=0; i<15; i++){
pwm.setPWM(i, 0, 150);
}
Serial.setTimeout(10);
}
void joystick_val(int pin){
Serial.print(pin);
Serial.print(" ");
}
void Move_motor(int motor, int degree, int int_val){
if(int_val <= 1){
degree += 5;
if(degree > 180) degree = 180;
int pul = map(degree,0,180,150,600);
pwm.setPWM(motor, 0, pul);
}
else if(int_val >= 4){
degree -= 5;
if(degree < 0) degree = 0;
int pul = map(degree,0,180,150,600);
pwm.setPWM(motor, 0, pul);
}
}
void loop() {
//int e = Serial.parseInt();
int analogPin[] = {analogRead(A0), analogRead(A1), analogRead(A2), analogRead(A3)};
int int_Pin[] = { map(analogPin[0], 0, 1023, 0, 5),
map(analogPin[1], 0, 1023, 0, 5),
map(analogPin[2], 0, 1023, 0, 5),
map(analogPin[3], 0, 1023, 0, 5)
};
int Pin_amount = sizeof(analogPin)-4;
Move_motor(motors[0], degrees[0], map(analogPin[0], 0, 1023, 0, 5));
Move_motor(motors[1], degrees[1], map(analogPin[1], 0, 1023, 0, 5));
Move_motor(motors[2], degrees[2], map(analogPin[2], 0, 1023, 0, 5));
Move_motor(motors[3], degrees[3], map(analogPin[3], 0, 1023, 0, 5));
for(int j=0; j<Pin_amount; j++){
Serial.print(map(analogPin[j], 0, 1023, 0, 5));
Serial.print(" ");
}
Serial.println("");
}
Originally the servo motors must keep rotating so long as the joystick connected to the motor is held, and only stop if the joystick is released. However, the servo motors stop after rotating for a split second instead of rotating continuously when the joystick is moved.
I tried using “for” loops and also tried changing the frequencies of PWM. What I want is make it so that the code functions the same without writing the Move_motor function four times. Thank you in advance.
user16975087 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.