Go Down

Topic: Reset (Read 408 times) previous topic - next topic

kmtama

Hi,

I am working on a piece of code that indexes into an array based on the value of 7 bits that are inputted.  I have declared a "total" value = 0 on the outside, but it doesn't seem to be getting reset within the loop().  Any help would be appreciated :)

//code
Code: [Select]

int speakerOut = 9;
int pin0 = 2;
int pin1 = 3;
int pin2 = 4;
int pin3 = 5;
int pin4 = 6;
int pin5 = 7;
int pin6 = 8;
int led = 13;

int tones[] = {0, 101420, 107296, 218, 113636, 924, 488, 120482, 244, 259, 1369, 127551, 1037, 547, 2319, 307, 135135, 274, 580, 3071, 1628, 689, 143266, 291, 307, 326, 345, 365, 387, 151976, 308, 326, 345, 366, 1, 2714, 22, 411, 435, 160772, 326, 345, 365, 387, 410, 435, 461, 489, 170068, 345, 730, 773, 410, 42517, 919, 21, 487, 1, 2, 3618, 547, 180505, 366, 387, 410, 435, 460, 488, 2, 517, 549, 580, 614, 191571, 11269, 411, 435, 462, 489, 518, 549, 582, 34, 616, 1955, 692};

int total = 0;
int readVal0 = 0;
...
int readVal6 = 0;

void setup()
{
     pinMode(speakerOut, OUTPUT);
     pinMode(led, OUTPUT);
     pinMode(pin0, INPUT);
     ...
       pinMode(pin6, INPUT);

}

void loop()
{
     //read the pins
     readVal0 = digitalRead(pin0);
     ...
       readVal6 = digitalRead(pin6);

     //converts the input into a numerical value
     //number should be 1 <= x <= 86
     if (readVal0 == HIGH){
           total = total+1;
     }
     ...
     if (readVal6 == HIGH){
           total = total+64;
     }
     
     if (total < 1 || total > 86) {
           digitalWrite(speakerOut, LOW);
     }      
     
     else {
           digitalWrite(speakerOut, HIGH);
           delayMicroseconds(tones[total]);
           digitalWrite(speakerOut, LOW);
           delayMicroseconds(tones[total]);
     }
}

kg4wsv

Quote
I have declared a "total" value = 0 on the outside, but it doesn't seem to be getting reset within the loop().

That would be because you're not resetting it inside the loop.  If you want to start total at 0 every time through the loop, you'll need to assign 0 to total every time through the loop.

One easy way to do this is get rid of total as a global variable and declare it as a local variable inside the only function that uses it (loop()).  Once declared inside a function it will automatically become an automatic variable, the initialization will happen every time loop() gets called, and that bit of your code will work the way you expect it.

FYI, when you declare a variable you are stating its type (and usually allocating space for it).  When you assign a value to to a variable, you're making an assignment.  When you are assigning a value at the same time as you declare the variable, that's initialization.

-j

Go Up