Skip to content

Instantly share code, notes, and snippets.

@rndD
Last active December 3, 2017 19:35
Show Gist options
  • Save rndD/b84367fdfbb274c46a16ba19c70bc97c to your computer and use it in GitHub Desktop.
Save rndD/b84367fdfbb274c46a16ba19c70bc97c to your computer and use it in GitHub Desktop.
// Ее нужно поставить через твою среду разработки
#include <AccelStepper.h>
// Encoder
boolean TurnDetected;
boolean Up;
const int PinCLK = 18;
const int PinDT = 17;
const int PinSW = 16;
const int MaxRotation = 100;
// Motor
const int PinStep = 3;
const int PinDir = 4;
// Тут можно поиграть.
const int MaxSpeed = 1000;
const int StartDistance = 0;
const float Acceleartion = 100.0;
int Distance = 12000; // Тут надо смотреть. Измеряется в шагах твоего двигателя. Сколько у тебя шагов на один круг?
boolean Derection = true; // Вперед
AccelStepper Motor = AccelStepper(2, PinStep, PinDir);
float calcSpeed(int currentRotationPosition) {
int modif = 1;
if (Derection == false) {
modif = -1;
}
return float((MaxSpeed / MaxRotation) * currentRotationPosition * modif);
}
void interuption() {
delay(2);
if (digitalRead(PinCLK)) {
Up = digitalRead(PinDT);
} else {
Up = !digitalRead(PinDT);
}
TurnDetected = true;
}
void setup () {
pinMode(PinCLK, INPUT);
pinMode(PinDT, INPUT);
pinMode(PinSW, INPUT);
digitalWrite(PinSW, HIGH);
attachInterrupt(digitalPinToInterrupt(PinCLK), interuption, FALLING);
pinMode(PinStep, OUTPUT);
pinMode(PinDir, OUTPUT);
Motor.setSpeed(0);
Motor.setMaxSpeed(MaxSpeed);
Motor.setAcceleration(Acceleartion);
Serial.begin(9600);
Serial.println("Hello!");
}
void loop () {
static int RotaryPosition = 0;
// Encoder
// Button of encoder is pressed
if (!(digitalRead(PinSW))) {
Derection = !Derection;
}
if (TurnDetected) {
if (Up) {
// Set max pos == MaxRotation
if (RotaryPosition >= MaxRotation) {
RotaryPosition = MaxRotation;
} else {
RotaryPosition = RotaryPosition++;
}
// is Down
} else {
// Set min pos == 0
if (RotaryPosition < 0) {
RotaryPosition = 0;
} else {
RotaryPosition = RotaryPosition--;
}
}
TurnDetected = false;
// Motor
if (Motor.currentPosition() >= Distance) {
Derection = false;
}
if (Motor.currentPosition() <= StartDistance) {
Derection = true;
}
float Speed = calcSpeed(RotaryPosition);
Motor.setSpeed(Speed);
Motor.runSpeed();
Serial.print("Current encoder rot pos = ");
Serial.println(RotaryPosition);
Serial.print("Current speed = ");
Serial.println(Speed);
Serial.print("Current dirrection = ");
Serial.println(Derection);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment