Here is part of a sketch i wrote to determine a number to analogWrite() to set the speed of a DC motor. I am using NodeMCU (esp8266) so the PCM range is 0-1023. Following the code segment is debug out put from the Serial monitor to demonstrate the issue. The carSpeed int is assigned value in the function and those values are shown on the debug output but by the end processing in the function it has a reported value of 0. Can anyone explain to me why the variable ends up 0 and how I can fix it?
Thanks, Richard
//functions
BLYNK_WRITE(V1)
{
int x = param[0].asInt();
int y = param[1].asInt();
Serial.println(" y is: " + String(y) + " x is: " + String(x)); //DEBUG
int carSpeed = calculateSpeed(x , y);
Serial.println("AFTER CALC Speed " + String(carSpeed) ); //DEBUG
turnSpeed = .5 * carSpeed;
moveControl(x, y, carSpeed, turnSpeed);
//Serial.println("AFTER MOVE Speed " + String(carSpeed) ); //BEGUG
Serial.println();
}
/*
1 2 3 4 5 6
int speedRange[] = {252, 378, 507, 517, 640, 765}; DEBUG
// set speed based speed tier above and below midRange */
int calculateSpeed(int x, int y)
{
Serial.println("In calculateSpeed function y " + String(y) + " x " + String(x)); //DEBUG
// base tier +- 5 from midRange..speed 0
if ( y < speedRange[3] || y > speedRange[4])
{ // 507 to 517
carSpeed = 0;
Serial.println("in if 507 to 517 carSpeed " + String(carSpeed)); //DEBUG
}
//in first tier upper or lower range .. speed 40%
if (y < speedRange[3] && y > speedRange[4])
{ //<507 or >517
carSpeed = .40 * speedMax ; //409
Serial.println("in if <507 or <517 carSpeed " + String(carSpeed)); //DEBUG
}
// in second tier upper or lower range .. up speed to 75%
if (y < speedRange[2] || y > speedRange[5] )
{ // <378 or >640
carSpeed = .75 * speedMax; //767
Serial.println("in if <378 or >640 carSpeed " + String(carSpeed)); // DEGUG
}
//in third tier upper and lower ranges...up speed to 100%
if (y < speedRange[1] || y > speedRange[6] )
{ // < 252 or > 765
carSpeed = speedMax; //1023
Serial.println("in < 252 or > 765 carSpeed " + String(carSpeed)); //DEBUG
}
//if not moving forward or back but want to turn
if (carSpeed = 0 && (x < speedRange[3] || x > speedRange[4]))
{ // 507 517
carSpeed = .40 * speedMax; //409
Serial.println("in carspeed 0, 507>x<517 " + String(carSpeed)); //DEBUG
}
Serial.println(" carSpeed val just before calc function return " + String(carSpeed)); //DEBUG
return carSpeed;
}
From Serial Monitor
y is: 1006 x is: 418
In calculateSpeed function y 1006 x 418
in if 507 to 517 carSpeed 0
in if <378 or >640 carSpeed 767
carSpeed val just before calc function return 0
AFTER CALC Speed 0
y is: 1024 x is: 431
In calculateSpeed function y 1024 x 431
in if 507 to 517 carSpeed 0
in if <378 or >640 carSpeed 767
in < 252 or > 765 carSpeed 1023
carSpeed val just before calc function return 0
AFTER CALC Speed 0