Hello, friends! I have been developing a project with arduino about the use of sensor readings for control the direction and the speed of stepper motor! Below, there is my code and I would like to know how to adjust for the best number of the steps, numbers of readings (i’m using moving average to filter the sensor values), correction (at the moment i’m using 100) and tolerance! I would like to have a smooth movement of the motor and sometimes the angle, that the motor goes through for certain steps quantity , isn’t the same that the indicate for the steps number (each step is equal to 1.8°)? How do I solve this? Thanks all!
define NUMREADINGS 8
const int stepPin = 7;
const int dirPin = 8;
const int Passosporvolta = 200;
const int numberofsteps= 3;
const int Mode0 = 2;
const int Mode1 = 4;
const int Mode2 = 3;
const int DelayMin = 2;
const int DelayMax = 500;
const int nRESET = 11;
const float tolerance = 2;
const int ldrE = 0;
const int ldrD = 1;
boolean dir;
int readingsE[NUMREADINGS];
int readingsD[NUMREADINGS]; // qtde de amostras
int indice = 0; // índice da leitura atual
float totalD = 0;
float totalE = 0;// total móvel
float customDelay;
int newCustom ;
float ldrEvalue = 0;
float ldrDvalue = 0;
float difldr = 0;
void setup() {
// Sets the two pins as Outputs
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode (nRESET, OUTPUT);
pinMode(Mode0, OUTPUT);
pinMode(Mode1, OUTPUT);
pinMode(Mode2, OUTPUT);
pinMode (0, INPUT);
pinMode (1, INPUT);
digitalWrite(Mode0,LOW);
digitalWrite(Mode1, HIGH);
digitalWrite(Mode2, LOW);
Serial.begin(9600);
for (int i = 0; i < NUMREADINGS; i++){
readingsE[i] = 0;
readingsD[i] = 0; // inicializa todas as leituras com 0
}
}
void loop()
{
mediamovel();
float medValue = ((ldrEvalue + ldrDvalue)/2) ;
difldr = (ldrEvalue - ldrDvalue);
float correction = 100*(difldr/medValue);
customDelay = abs(correction);
if (customDelay < tolerance)
{
digitalWrite(nRESET,LOW);
}
else
{
if (correction<0)
{
dir = HIGH;
}
else
{
dir = LOW;
}
newCustom = map(customDelay,tolerance,50,DelayMax,DelayMin);
digitalWrite (nRESET,HIGH);
digitalWrite(dirPin,dir);
for(int i =1; i<=numbersofsteps;i++){
digitalWrite(stepPin, HIGH);
delayMicroseconds(newCustom);
digitalWrite(stepPin,LOW);
delayMicroseconds(newCustom);
}
}
//Serial.println(String(dir) + ";"+ newCustom +";"+ldrEvalue +";"+ldrDvalue+";"+customDelay+";"+readingsE[indice]+";"+readingsD[indice]);
}
void mediamovel () {
totalE -= readingsE[indice];
totalD -= readingsD[indice]; // subtrair a última leitura
readingsE[indice] = analogRead(ldrE);// ler do sensor
readingsD[indice] = analogRead(ldrD);
totalE += readingsE[indice];
totalD += readingsD[indice]; // adicionar leitura ao total
indice = (indice + 1); // avançar ao próximo índice
if (indice >= NUMREADINGS) // se estiver no fim do vetor...
indice = 0; // ...meia-volta ao início
ldrEvalue = (totalE)/ NUMREADINGS;
ldrDvalue = (totalD)/ NUMREADINGS; // calcular a média
}