SpeedControl Ino
SpeedControl Ino
SpeedControl Ino
h>
// Pins
#define ENCA 2
#define ENCB 3
#define PWM 5
#define IN1 6
#define IN2 7
// globals
long prevT = 0;
int posPrev = 0;
// Use the "volatile" directive for variables
// used in an interrupt
volatile int pos_i = 0;
volatile float velocity_i = 0;
volatile long prevT_i = 0;
float v1Filt = 0;
float v1Prev = 0;
float v2Filt = 0;
float v2Prev = 0;
float eintegral = 0;
void setup() {
Serial.begin(115200);
pinMode(ENCA,INPUT);
pinMode(ENCB,INPUT);
pinMode(PWM,OUTPUT);
pinMode(IN1,OUTPUT);
pinMode(IN2,OUTPUT);
attachInterrupt(digitalPinToInterrupt(ENCA),
readEncoder,RISING);
}
void loop() {
// Set a target
float vt = 100*(sin(currT/1e6)>0);
Serial.print(vt);
Serial.print(" ");
Serial.print(v1Filt);
Serial.println();
delay(1);
}
void setMotor(int dir, int pwmVal, int pwm, int in1, int in2){
analogWrite(pwm,pwmVal); // Motor speed
if(dir == 1){
// Turn one way
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
}
else if(dir == -1){
// Turn the other way
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
}
else{
// Or dont turn
digitalWrite(in1,LOW);
digitalWrite(in2,LOW);
}
}
void readEncoder(){
// Read encoder B when ENCA rises
int b = digitalRead(ENCB);
int increment = 0;
if(b>0){
// If B is high, increment forward
increment = 1;
}
else{
// Otherwise, increment backward
increment = -1;
}
pos_i = pos_i + increment;