Skip to content

Instantly share code, notes, and snippets.

@IdrisCytron
Created April 24, 2019 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IdrisCytron/4788f264953139de7561afaa43dbc5b4 to your computer and use it in GitHub Desktop.
Save IdrisCytron/4788f264953139de7561afaa43dbc5b4 to your computer and use it in GitHub Desktop.
Controlling SmartDrive40 Using ESP32 board.
#define RXD_DUMMY 12
#define MDS40B_IN1 13
#define MDS40B_IN2 14
#define MDS40BSerial Serial1
#define BBRS_CE 25
#define BBRS_EA 26
#define BBRS_EB 27
int motorSpeed = 127;
boolean motorDirection = false;
volatile int lastEncoded = 0;
volatile long encoderValue = 0;
long lastencoderValue = 0;
int lastMSB = 0;
int lastLSB = 0;
boolean printEncoder = false;
void updateEncoder()
{
int MSB = digitalRead(BBRS_EA); //MSB = most significant bit
int LSB = digitalRead(BBRS_EB); //LSB = least significant bit
int encoded = (MSB << 1) | LSB; //converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to the previous encoded value
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) {
encoderValue ++;
}
if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) {
encoderValue --;
}
lastEncoded = encoded; //store this value for next time
encoderValue = constrain(encoderValue, 0, 100);
printEncoder = true;
}
void setup()
{
pinMode(BBRS_CE, INPUT);
pinMode(BBRS_EA, INPUT);
pinMode(BBRS_EB, INPUT);
pinMode(MDS40B_IN2, OUTPUT);
digitalWrite(MDS40B_IN2, HIGH);
Serial.begin(115200);
MDS40BSerial.begin(9600, SERIAL_8N1, RXD_DUMMY, MDS40B_IN1);
MDS40BSerial.write(motorSpeed);
delay(1000);
attachInterrupt(digitalPinToInterrupt(BBRS_EA), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(BBRS_EB), updateEncoder, CHANGE);
Serial.println();
Serial.println();
Serial.println("Controlling SmartDrive-40 Using ESP32 Controller");
Serial.println();
Serial.print("Enc:\tSpeed:");
}
void loop()
{
if (printEncoder == true) {
printEncoder = false;
if (motorDirection == false) {
motorSpeed = map(encoderValue, 0, 100, 127, 255);
}
else if (motorDirection == true) {
motorSpeed = map(encoderValue, 0, 100, 127, 0);
}
Serial.print(encoderValue);
Serial.print("\t");
Serial.println(motorSpeed);
MDS40BSerial.write(motorSpeed);
}
if (digitalRead(BBRS_CE) == LOW) {
motorDirection = !motorDirection;
encoderValue = 0;
motorSpeed = 127;
MDS40BSerial.write(motorSpeed);
Serial.println();
Serial.println("Change Direction!");
Serial.println();
Serial.print("Enc:\tSpeed:");
while (digitalRead(BBRS_CE) == LOW);
delay(100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment