Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <analogWrite.

h> //library for analog write with esp32


#include <ESP32Encoder.h> // encoder library
#include <PID_v1.h> // PID library

//#define PIN_OUTPUT 3
ESP32Encoder encoder; //encoder created by the name "encoder"

//Define Variables we'll be connecting to


double Setpoint, Input, Output;// variable created mus be double

const int dirA=4; // only this pin is for directio


const int dirB=27; // this pin is used as enable on motor driver
int i = 0;

//Specify the links and initial tuning parameters


double Kp=50, Ki=20 , Kd=6; // tune PID value here
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT); //PID creaded by the
name "myPID"

void setup(){

Serial.begin(115200); // serial begin


// Enable the weak pull up resistors
ESP32Encoder::useInternalWeakPullResistors=UP;

// use pin 19 and 18 for the first encoder


encoder.attachHalfQuad(19, 18); // these are the pins of encoder connection

// set starting count value after attaching


encoder.setCount(0); // on startup the encoder value will be 0

//Serial.println("Encoder Start = " + String((int32_t)encoder.getCount()));


pinMode(4, OUTPUT);
pinMode(2, OUTPUT);
pinMode(27, OUTPUT);
//initialize the variables we're linked to
Setpoint = 300; // target value to be achieved by the motor
Input= encoder.getCount(); // this is the input of PID which is encoder in
this case
//turn the PID on
myPID.SetMode(AUTOMATIC); //
myPID.SetSampleTime(10); // pid update time in millis
myPID.SetOutputLimits(-255, 255); // pid output range.
Serial.println("LABEL,Time,Counter,millis,encoder value");
analogWriteResolution(LED_BUILTIN, 12); // this is setting of analog write
library, leave as is for pin 2
// if other analog pin is to be used then change LED_BUILTIN to desired pin
number
}

void loop(){
Input = encoder.getCount(); // update the input value with new encoder value
myPID.Compute(); // compute PID

//Serial.println(Setpoint-Input); //this show how much target is remaining or


error
//Serial.println("Output value from PID = " + String(Output));
//Serial.print("target value = ");
Serial.println(Setpoint);
Serial.println(encoder.getCount());
if(Output<0){ //this is CW direction
digitalWrite(dirA,LOW); // low is CW direction
digitalWrite(dirB,HIGH); // dir B is enable pin
analogWrite(2, abs(Output)); // motor pwm is pwm
}
else if(Output>=0){ // this ccw direction
digitalWrite(dirA,HIGH);
digitalWrite(dirB,HIGH);
analogWrite(2, Output);
}
//Serial.print("DATA,TIME,");
//Serial.print(i++);
Serial.print(",");Serial.print(millis());Serial.print(",");
//Serial.println(encoder.getCount());
//above 3 lines are used to measure time period
}

You might also like