change existing code for getting distance

Hi friends

I am working in a machine that was created a few years ago from a student.
Seems everything is working.
It has 1 encoder 200 PPR and car wheel that counts the pulses from a rackwheel.
The output from encoder is in RPM from both.
I want to add an output for number of pulses of each (I will convert in distance with wheels diameters) to get the distance from each wheel.

As I am a begginer in arduino I would appreciate the help
I advice the code is not from me and I seems quite confuse....
I try to do it and I add a D1 and D2 for distances, but the counter starts at 255 and gos to 0 and restarts :slight_smile:

//cpalha versao 0 out20
#include "math.h"
#include "Filter.h"                 
#define PWM1            6                       
#define encodPinA1      3                      
#define encodPinB1      11
#define pump1           4
#define pumpswitch      8
#define brakeswitch     7
#define valveswitch     9
#define pump1speed      5
#define LOOPTIME        100                  
unsigned long oldTime= 0; 
unsigned long lastMilli = 0;                     
unsigned long lastMilliPrint = 0;               
long lastProcess=0;
float val;
float val1;

int slip = 5;
// filtro celula:
const int numReadings = 100;
int sleep2= Serial.read();

int PWM_val = 0;                                
volatile long count = 0;  
volatile long count2 = 0;  
volatile double speed_act= 0;
volatile double speed_req= 0;
volatile double speed_act2= 0;
volatile double velocidade= 0;
volatile double catrito= 0;
volatile byte pulseCount1= 0;
volatile byte pulse1= 0;//novo
volatile byte pulse2= 0;//novo
int ps1=0;
double Kp =  0.001;                           
double Ki = 0.02 ;                            
double Kd = 0.095 ;

float readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
float total = 0;                  // the running total
float average = 0;                // the average

void setup() {
 Serial.begin(115200);
 pinMode(PWM1, OUTPUT);
 pinMode(encodPinA1, INPUT); 
 pinMode(encodPinB1, INPUT);
 pinMode(pumpswitch, OUTPUT);
 pinMode(brakeswitch,OUTPUT);
 pinMode(valveswitch,OUTPUT);
 digitalWrite(encodPinA1, HIGH);                     
 digitalWrite(encodPinB1, HIGH);
 digitalWrite(pump1,HIGH);
 pinMode(pump1speed,OUTPUT);
 attachInterrupt(1, rencoder, RISING);
 attachInterrupt(0, rencoder2,RISING);
 analogWrite(PWM1,PWM_val);
 analogWrite(pump1speed,ps1);
 digitalWrite(pumpswitch,LOW);
 digitalWrite(brakeswitch,LOW);
 digitalWrite(valveswitch,LOW);
// filtro célula
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
 
 }
 void loop() {
 delay (LOOPTIME);
 getParam();                                                                
 pulseCounter1();
 pulseCounter2();
 relay(); 
 printinfo();
 ps1=255;
 PWM_val= updatePid(PWM_val, speed_req, speed_act); 
 analogWrite(PWM1, PWM_val);
 if (sleep2 > 97 || sleep2 <122) sleep2 =0;
 else slip = sleep2; 
 }

   
void getParam()  {
 //leitura da celula de carga      
val=analogRead(0);
float voltage= (val) * (5.0 / 1024.0);
double forca=(0.0662*val+0.506);// calib cp 21out20 para a media (0.0598*val + 0.9045);     //11.164*voltage + 0.7191;


  total = total - readings[readIndex];
  readings[readIndex] = forca;
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  if (readIndex >= numReadings) {
    readIndex = 0;
  }
  average = total / numReadings;
  delay(1);     


float binario=(average*0.32);  //braco do travao a celula
float btraseiro= 1.8695652173913*binario ;
float fatrito=(btraseiro/0.21);
catrito=fatrito/64;

speed_req=((1.8695652173913)*(speed_act2)*(1-slip*0.01))*(0.605/0.42);

//velocidade da bomba de agua
velocidade=((speed_act2)*(1.90664*0.001*60));
analogWrite(pump1,LOW);
analogWrite(pump1speed,ps1); 
double litros= (velocidade*0.6)*1.25; 
double ps1 =180;//5.0009*litros - 56.972; 

}
//ajuste da RPM do travao
int updatePid(int command, int targetValue, int currentValue)   {            
float pidTerm = 0;                                                            
int error=0; 
double P=0,I=0,D=0;                                 
static int last_error=0;                            
static int last_speed_act=0;
float deltaTime = (millis()-lastProcess)/1000;
lastProcess=millis();
error =(abs(speed_act)-abs(speed_req));
P=Kp * error;
I+=(Ki * error);
D=Kd * (error - last_error);
last_speed_act = speed_act;
pidTerm = P+I+D;          
last_error = error;
return constrain(command + int(pidTerm), 0, 255);
}

void rencoder()  {                               
 if (PINB & 0b00000001)    count++;                
 else                      count--;                
}

void rencoder2()  {                                  
 if (digitalRead(encodPinB1)==HIGH)    count2++;                
 else                      count2--;                
}
                                                    
void pulseCounter1(){
 static long countAnt = 0;                                                  
 speed_act =((count - countAnt)*(60*(1000/LOOPTIME)))/(200);//encoder travao 200PPR
 pulse1=count - countAnt;  //novo
 if (speed_act>0){
 speed_act=speed_act;}
 if (speed_act<0){
 speed_act=speed_act*-1;}           
 countAnt = count;}
  

void pulseCounter2()  {                                                        
static long countAnt = 0;                                                  
 speed_act2 = (((count2 - countAnt)*(60*(1000/LOOPTIME)))/(52)); //encoder 2 rodas 52 PPR        
 pulse2=count - countAnt;  //novo
 countAnt = count2;  }
                               
  
void printinfo(){
   
   if((millis()-lastMilliPrint) >= 500)   {    //delay para o print  passei a 500               
   lastMilliPrint = millis();
double forca=(0.0662*val+0.506);//(0.0598*val + 0.9045); calib cp 21out20 valor instantaneo

//Serial.print("  RPMFW:   ");          Serial.print(speed_act2*1.8695652173913*(0.605/0.42)); //RPM das rodas da frente
Serial.print("RPMF");       Serial.print((speed_act));
Serial.print(" SR");           Serial.print(speed_req);
Serial.print(" PWM");             Serial.print(PWM_val);
Serial.print(" Ca");             Serial.print(catrito);
Serial.print(" AF");             Serial.print(average);
Serial.print(" F");             Serial.print(forca);
Serial.print(" D1");             Serial.print(pulse1);//novo
Serial.print(" D2");             Serial.print(pulse2);//novo
Serial.print(" SLIP");             Serial.println(slip);
//Serial.print("\n");  //fim de string novo

}
}


void relay(){
char usbdata=Serial.read();
  delay(10);                  
  usb_action(usbdata);
  Serial.flush();}       
void usb_action(char nova){
switch (nova) 
  {  
      case 'p':   
  digitalWrite(pumpswitch,HIGH);
      break;
      case 'o':    
     digitalWrite(pumpswitch,LOW);
      break;
      case 'b':   
  digitalWrite(brakeswitch,HIGH);
      break;
      case 'n':
  digitalWrite(brakeswitch,LOW);
      break;
      case'v':
  digitalWrite(valveswitch,HIGH);
      break;
      case'c':
  digitalWrite(valveswitch,LOW);
      break;
      case'+':
      slip++;
      break;
      case'-':
      slip--;
      break;
      
      case'4':
      Kp=Kp+0.0001;
      break;
      case'1':
      Kp=Kp-0.0001;
      break;

       case'5':
      Ki=Ki+0.01;
      break;
      case'2':
      Ki=Ki-0.01;
      break;

       case'6':
      Kd=Kd+0.001;
      break;
      case'3':
      Kd=Kd-0.001;
      break;
}
}

cpalha

You don't seem to have any means of debugging that code - fix that first with some serial prints.

Hi friend

It's working
Serial print from arduino nano (no sensors connected on it)

RPMF0.00 SR0.00 PWM0 Ca0.06 AF1.37 F26.44 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.12 AF2.68 F25.24 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.18 AF3.94 F24.29 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.23 AF5.15 F23.39 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.28 AF6.32 F22.67 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.33 AF7.45 F22.07 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.38 AF8.56 F21.60 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.43 AF9.65 F21.18 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.48 AF10.72 F20.82 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.52 AF11.78 F20.58 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.57 AF12.83 F20.40 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.62 AF13.86 F20.22 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.66 AF14.90 F20.10 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.71 AF15.92 F20.04 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.75 AF16.94 F19.98 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.80 AF17.96 F19.92 D10 D20 SLIP5
RPMF0.00 SR0.00 PWM0 Ca0.84 AF18.98 F19.92 D10 D20 SLIP5

The encoders part should be here, the part that I add was the

pulse1=count - countAnt;
pulse2=count - countAnt;

for getting D1 and D2 distances (or in this case pulses)

void rencoder()  {                               
 if (PINB & 0b00000001)    count++;                
 else                      count--;                
}

void rencoder2()  {                                  
 if (digitalRead(encodPinB1)==HIGH)    count2++;                
 else                      count2--;                
}
                                                    
void pulseCounter1(){
 static long countAnt = 0;                                                  
 speed_act =((count - countAnt)*(60*(1000/LOOPTIME)))/(200);//encoder travao 200PPR
 pulse1=count - countAnt;  //novo
 if (speed_act>0){
 speed_act=speed_act;}
 if (speed_act<0){
 speed_act=speed_act*-1;}           
 countAnt = count;}
  

void pulseCounter2()  {                                                        
static long countAnt = 0;                                                  
 speed_act2 = (((count2 - countAnt)*(60*(1000/LOOPTIME)))/(52)); //encoder 2 rodas 52 PPR        
 pulse2=count - countAnt;  //novo
 countAnt = count2;  }

Dear Friends

After doing some changes in code, I still have difficult to add in that code a change to count pulses and after it distance.

I have 2 wheels with 2 encoders each ( 1 with an incremental encoder other with a kind of proximity switch - car sensor) But both works for RPMs.

I will be really thank you if somebody could help me make a small part of code (only for 1 encoder) to count pulses.

#include "math.h"
#include "Filter.h"                 
#define PWM1            6                       
#define encodPinA1      3                      
#define encodPinB1      11
#define pump1           4
#define pumpswitch      8
#define brakeswitch     7
#define valveswitch     9
#define pump1speed      5
#define LOOPTIME        100                  
unsigned long oldTime= 0; 
unsigned long lastMilli = 0;                     
unsigned long lastMilliPrint = 0;               
long lastProcess=0;
float val;
float val1;

int slip = 10;
// filtro celula:
const int numReadings = 100;
int sleep2= Serial.read();

int PWM_val = 0;                                
volatile long count = 0;  
volatile long count2 = 0;  
volatile double speed_act= 0;
volatile double speed_req= 0;
volatile double speed_act2= 0;
volatile double velocidade= 0;
volatile double catrito= 0;
volatile byte pulseCount1= 0;
int ps1=0;
double Kp =  0.001;                           
double Ki = 0.02 ;                            
double Kd = 0.095 ;

float readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
float total = 0;                  // the running total
float average = 0;                // the average

void setup() {
 Serial.begin(115200);
 pinMode(PWM1, OUTPUT);
 pinMode(encodPinA1, INPUT); 
 pinMode(encodPinB1, INPUT);
 pinMode(pumpswitch, OUTPUT);
 pinMode(brakeswitch,OUTPUT);
 pinMode(valveswitch,OUTPUT);
 digitalWrite(encodPinA1, HIGH);                     
 digitalWrite(encodPinB1, HIGH);
 digitalWrite(pump1,HIGH);
 pinMode(pump1speed,OUTPUT);
 attachInterrupt(1, rencoder, RISING);
 attachInterrupt(0, rencoder2,RISING);
 analogWrite(PWM1,PWM_val);
 //analogWrite(pump1speed,ps1);  novo
 digitalWrite(pumpswitch,LOW);
 digitalWrite(brakeswitch,LOW);
 digitalWrite(valveswitch,LOW);
// filtro célula
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
 
 }
 void loop() {
 delay (LOOPTIME);
 getParam();                                                                
 pulseCounter1();
 pulseCounter2();
 relay(); 
 printinfo();
 ps1=255;
 PWM_val= updatePid(PWM_val, speed_req, speed_act); 
 analogWrite(PWM1, PWM_val);
 if (sleep2 > 97 || sleep2 <122) sleep2 =0;
 else slip = sleep2; 
 }

   
void getParam()  {
       
val=analogRead(0);
float voltage= (val) * (5.0 / 1024.0);
double forca=(0.0598*val + 0.9045);     //11.164*voltage + 0.7191;


  total = total - readings[readIndex];
  readings[readIndex] = forca;
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  if (readIndex >= numReadings) {
    readIndex = 0;
  }
  average = total / numReadings;
  delay(1);     


float binario=(average*0.32);
float btraseiro= 1.8695652173913*binario ;
float fatrito=(btraseiro/0.21);
catrito=fatrito/64;

speed_req=((1.8695652173913)*(speed_act2)*(1-slip*0.01))*(0.605/0.42);

velocidade=((speed_act2)*(1.90664*0.001*60));
analogWrite(pump1,LOW);
//digitalWrite(pump1speed,HIGH);                       //analogWrite(pump1speed,ps1); 
//double litros= (velocidade*0.6)*1.25; 
//double ps1 =180;//5.0009*litros - 56.972; novo

}

int updatePid(int command, int targetValue, int currentValue)   {            
float pidTerm = 0;                                                            
int error=0; 
double P=0,I=0,D=0;                                 
static int last_error=0;                            
static int last_speed_act=0;
float deltaTime = (millis()-lastProcess)/1000;
lastProcess=millis();
error =(abs(speed_act)-abs(speed_req));
P=Kp * error;
I+=(Ki * error);
D=Kd * (error - last_error);
last_speed_act = speed_act;
pidTerm = P+I+D;          
last_error = error;
return constrain(command + int(pidTerm), 0, 255);
}

void rencoder()  {                               
 if (PINB & 0b00000001)    count++;                
 else                      count--;                
}

void rencoder2()  {                                  
 if (digitalRead(encodPinB1)==HIGH)    count2++;                
 else                      count2--;                
}
                                                    
void pulseCounter1(){
 static long countAnt = 0;                                                  
 speed_act =((count - countAnt)*(60*(1000/LOOPTIME)))/(200);
 if (speed_act>0){
 speed_act=speed_act;}
 if (speed_act<0){
 speed_act=speed_act*-1;}           
 countAnt = count;}
  

void pulseCounter2()  {                                                        
static long countAnt = 0;                                                  
 speed_act2 = (((count2 - countAnt)*(60*(1000/LOOPTIME)))/(52));         
 countAnt = count2;  }
                               
  
void printinfo(){
   
   if((millis()-lastMilliPrint) >= 100)   {        // loop time             
   lastMilliPrint = millis();
double forca=(0.0598*val + 0.9045);

//Serial.print("  RPMFW:   ");          Serial.print(speed_act2*1.8695652173913*(0.605/0.42));
Serial.print("  RPMFreio:   ");       Serial.print((speed_act));
Serial.print("  S.R:    ");           Serial.print(speed_req);
//Serial.print("  Kp:    ");           Serial.print(Kp*10000);
//Serial.print("  Ki:    ");           Serial.print(Ki*100);
//Serial.print("  Kd:    ");           Serial.print(Kd*1000);
//Serial.print("  PWM:   ");             Serial.print(PWM_val);
//Serial.print("  vel:    ");            Serial.print(  velocidade );
//Serial.print("  C.at:    ");           Serial.print(  catrito  );
//Serial.print("  força média   ");   Serial.print(  average  );
//Serial.print("  força   ");          Serial.print(  forca  ); 
//Serial.print("  Slip:   ");            Serial.print(  slip  );

Serial.print("       ");             Serial.print(PWM_val);
Serial.print("       ");             Serial.print(  catrito  );
Serial.print("       ");             Serial.print(  average  );
Serial.print("       ");             Serial.print(  forca  ); 
Serial.print("       ");             Serial.print(  slip  );


int bomba = digitalRead(pump1speed); //le estado da saida digital da bomba
Serial.print(" bomba  ");            Serial.print(bomba);

int valveb = digitalRead(pumpswitch); //le estado da saida digital board da valvula
Serial.print("  vON  ");            Serial.print(valveb);

int  valveo = digitalRead(valveswitch); //le estado da saida digital da valvula
Serial.print("  vA  ");            Serial.println(valveo);

//Serial.print("  bomba:   ");          Serial.print(ps1);

//Serial.println("   MAPA ");                                                         
//Serial.print(velocidade);
//Serial.print(",");
//Serial.print(catrito);
//Serial.print("\n");

}
}


void relay(){
char usbdata=Serial.read();
  delay(10);                  
  usb_action(usbdata);
  Serial.flush();}       
void usb_action(char nova){
switch (nova) 
  {  
    case 'q':   
  digitalWrite(pump1speed,HIGH);
      break;
      case 'w':    
     digitalWrite(pump1speed,LOW);
      break;  
    
    case 'p':   
  digitalWrite(pumpswitch,HIGH);
      break;
      case 'o':    
     digitalWrite(pumpswitch,LOW);
      break;
      case'v':
  digitalWrite(valveswitch,HIGH);
      break;
      case'c':
  digitalWrite(valveswitch,LOW);
      break;
      case 'b':   
  digitalWrite(brakeswitch,HIGH);
      break;
      case 'n':
  digitalWrite(brakeswitch,LOW);
      break;
      case'+':
      slip++;
      break;
      case'-':
      slip--;
      break;
      
      case'4':
      Kp=Kp+0.0001;
      break;
      case'1':
      Kp=Kp-0.0001;
      break;

       case'5':
      Ki=Ki+0.01;
      break;
      case'2':
      Ki=Ki-0.01;
      break;

       case'6':
      Kd=Kd+0.001;
      break;
      case'3':
      Kd=Kd-0.001;
      break;
}
}

Best regards
carlos

I think I would write a simple program to count the pulses and calculate the distance .
Get that working first and then add it as a separate function .

As said use lots of print statements so you can “see “what is happening .

Hi Farady

Thanks, but why write a newone if I have many writed?

void rencoder()  {                               [color=#222222][/color]
 if (PINB & 0b00000001)    count++;               [color=#222222][/color]
 else                      count--;               [color=#222222][/color]
}[color=#222222][/color]
[color=#222222][/color]
void rencoder2()  {                                 [color=#222222][/color]
 if (digitalRead(encodPinB1)==HIGH)    count2++;               [color=#222222][/color]
 else                      count2--;               [color=#222222][/color]
}[color=#222222][/color]
                                                   [color=#222222][/color]
void pulseCounter1(){[color=#222222][/color]
 static long countAnt = 0;                                                 [color=#222222][/color]
 speed_act =((count - countAnt)*(60*(1000/LOOPTIME)))/(200);//encoder travao 200PPR[color=#222222][/color]
 pulse1=count - countAnt;  //novo[color=#222222][/color]
 if (speed_act>0){[color=#222222][/color]
 speed_act=speed_act;}[color=#222222][/color]
 if (speed_act<0){[color=#222222][/color]
 speed_act=speed_act*-1;}           [color=#222222][/color]
 countAnt = count;}[color=#222222][/color]
 [color=#222222][/color]
[color=#222222][/color]
void pulseCounter2()  {                                                       [color=#222222][/color]
static long countAnt = 0;                                                 [color=#222222][/color]
 speed_act2 = (((count2 - countAnt)*(60*(1000/LOOPTIME)))/(52)); //encoder 2 rodas 52 PPR       [color=#222222][/color]
 pulse2=count - countAnt;  //novo[color=#222222][/color]
 countAnt = count2;  }[color=#222222][/color]

In this part of the code if i printout the count and count2 it gives the pulses?

Best
cpalha

Hi friends

After comparing encoder codes and explore this code, I try to add 2 lines

Serial.print for count and

Serial.print for count2

And it works!!!
I have now the output for counting pulses.

Best regards
cpalha