Dear: LMR
Just to let you know I am trying to control all my robots motors and encoders in a single function. It is not going so well obviously since I am starting a forum. This code is supposed to work that function void move has parameters that are leftMotorSpeed, rightMotorSpeed, leftMotorDistance, and rightMotorDistance. Left and Right motor speed control the motor's speed. The other parameters represent the number of ticks the motors are supposed to tick. When they reach a certain amount of ticks the function returns. As should the loop function.
You should know all the motors are moving fine unplugged from the usb. My orginal code to move the motors work fine plugged and unplugged from the USB. The only problem is they control the motors entirely not the encoders as well. The encoders are printing values into computer through the arduino serial monitor but the motors aren't moving on there own.
Also I am using arduino mega 2560 with cytron 10 amp motor driver. I am also using this encoder library. Thank you.
From: Noah
#include <Encoder.h>
Encoder MtrEnc1(20,21); const int MtrDir1 = 2; const int MtrPWM1 = 3; Encoder MtrEnc2(18,19); const int MtrDir2 = 4; const int MtrPWM2 = 5;void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(MtrDir1, OUTPUT);
pinMode(MtrPWM1, OUTPUT);
pinMode(MtrDir2, OUTPUT);
pinMode(MtrPWM2, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
Move(255, 0, 1000, 0);
return;
}
long position1 = -999;
long position2 = -999;
void Move(int LeftMotorSpeed, int RightMotorSpeed, int LeftMotorDistance, int RightMotorDistance)
{
long EncRead1, EncRead2;
bool LeftMotorMatched = false;
bool RightMotorMatched = false;
EncRead1 = MtrEnc1.read();
EncRead2 = MtrEnc2.read();
if (Serial.available())
{
Serial.read();
MtrEnc1.write(0);
MtrEnc2.write(0);
}
if (EncRead1 != position1 || EncRead2 != position2) {
position1 = EncRead1;
position2 = EncRead2;
Serial.print(EncRead1);
Serial.print(EncRead2);
Serial.println();
}
if (EncRead1 == LeftMotorDistance)
{
LeftMotorMatched = true;
}
if (EncRead2 == RightMotorDistance)
{
RightMotorMatched = true;
}
if (LeftMotorDistance > 0 && LeftMotorMatched == false)
{
digitalWrite(MtrDir1, LOW);
analogWrite(MtrPWM1, LeftMotorSpeed);
}
if (LeftMotorDistance < 0 && LeftMotorMatched == false)
{
digitalWrite(MtrDir1, HIGH);
analogWrite(MtrPWM1,LeftMotorSpeed);
}
if (RightMotorDistance > 0 && RightMotorMatched == false)
{
digitalWrite(MtrDir2, LOW);
analogWrite(MtrPWM2, RightMotorSpeed);
}
if (RightMotorDistance < 0 && RightMotorMatched == false)
{
digitalWrite(MtrDir2, HIGH);
analogWrite(MtrPWM2,RightMotorSpeed);
}
if (LeftMotorMatched == true && RightMotorMatched == true)
{
return;
}
}