See the picture of serial monitor showing I get a large number, 4 billion, when I multiply two called functions together. It always happens after 53 if I change the amount the if statement counts to. I serial monitored the if statement and it counts to 600 then down then up and repeats good and the sensorValue stays the same.
I get rid of the division in y and I put it all in the for loop and still get a large number. My purpose is to fade pin and adjusts analogWrite at same time. It adjusts but does not fade. Does replacing for loop with if statement or calling to many functions create a bug.
int analogInPin = A0;
int analogOutPin3 = 3;
int sensorValue;
int i = 0;
int a;
int y;
void sens(int &sensorValue){
sensorValue = (((long)analogRead(analogInPin)*255)/1023);
}
void inOut(int &i){
if (i > -1){
i = i + a;
if (i == 0){
a = 1;
}
if (i == 600){
a = -1;
}
return i;
}
}
void updateFade(){
sens(sensorValue);
inOut(i);
unsigned long y = ((sensorValue*i)/600);
Serial.println(sensorValue);
}
void setup() {
Serial.begin(9600);
pinMode(analogInPin,INPUT);
pinMode(3,OUTPUT);
}
void loop() {
updateFade();
delay(100);
analogWrite(3, y);
}
2 Answers 2
You define i,y,i as global variables so there is no need to hand them over to different functions. They can be accessed and changed in all parts of your program.
define instead of
int y;
change to
long y;
and change
void inOut(int &i){
to
void inOut(){
and remove
return i;// Its a global var
change the line
unsigned long y = ((sensorValue*i)/600);
to
y = ((sensorValue*i)/600);
Try to avoid the same names for global and local vars. It might happen that the compiler handles it as a redefinition, which might lead to all sort of trouble in complex programs. (Also for you if you look onto an ill documented code some months later)
And get rid of the delay it stops processing (also your subroutines) see Blinkwithoutdelay how to do it properly
ArduinoIDE->file->examples->2 Digital->Blinkwithoutdelay
Thanks for the help, this is my working code. I changed things to long, got rid of some long's, stopped passing variables, and forced number in sensorValue to be long. It now counts up and down were I set the potentiometer every minute.
int analogInPin = A0;
int analogOutPin3 = 3;
long sensorValue;
int i = 0;
int a;
long y;
void sens(){
sensorValue = ((analogRead(analogInPin)*255L)/1023); //force 255 to be long
}
void inOut(){
if (i > -1){
i = i + a;
if (i == 0){
a = 1;
}
if (i == 600){
a = -1;
}
}
}
void updateFade(){
sens();
inOut();
y = ((sensorValue*i)/600);
Serial.println(y);
}
void setup() {
Serial.begin(9600);
pinMode(analogInPin,INPUT);
pinMode(3,OUTPUT);
}
void loop() {
updateFade();
delay(100);
analogWrite(3, y);
}
i
is -1 then what isy
going to be?1111 1111 1111 1111 1111 1111 1100 1010
== hexadecimalFFFFFFCA
== unsigned decimal4294967242
== signed decimal-54