# Arduino Forum

## Using Arduino => Programming Questions => Topic started by: littlewolf on Mar 12, 2013, 08:14 pm

Title: Binary counting using 12 LEDs
Post by: littlewolf on Mar 12, 2013, 08:14 pm
Hi guys,
I am currently working on a new project but, like always, I am a bit
struggling with the code.
My project include 12 LEDs connected to an Arduino Mega and a 4/3 keypad.
I would like to do binary counting using the LEDs and to change the rate of
increase or decrease using the keypad.
For example, by pressing 1 and "i++" or "i--"(I changed the "*" and "#" characters)
to either increase or decrease the counting by one.
Similarly, by pressing any other character, to either increase or decrease the counting
by its value.

Here is my code so far:

Code: [Select]
`/* Binary counting using 12 LEDs and a keypad to change the increasing or decreasing rate */#include <Keypad.h>int i;int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int counter;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'i--','10','i++'} };/* I want to use i-- and i++ to either increaseor decrease the binary counting */byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){      for(i=0; i<12; i++){  pinMode(ledPin[i], OUTPUT);      // sets the digital pins as output    char key = keypad.getKey();   if (key=1) {   counter = i+1 } else if(key=2) {   counter= i+2 } else if(key=3) { counter=i+3 } else if etc....      }}`

Could you help?
Regards
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Mar 12, 2013, 08:24 pm
Quote
{'i--','10','i++'}

It doesn't work like that. You should have an IF statement look for '*' or '#' and change the counter accordingly.

Quote
key=1,key=2,key=3

Again, it does not work like that. If anything, it should be if(key == '1'), if(key == '2') and so on.

Now you want to look at the keypad press a number and then decide whether it should be incremented or decremented? Ok well then you need to have if so that if a key is pressed, it then looks at another incoming key and see if it is '#' or '*'. So your looking at an IF within an IF statement.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 12, 2013, 09:42 pm
Something like this ...?
Code: [Select]
`/* Binary counting using 12 LEDs and a keypad to change the increasing or decreasing rate */#include <Keypad.h>int i;int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int counter;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'} };/* I want to use i-- and i++ to either increaseor decrease the binary counting */byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){      for(i=0; i<12; i++){  pinMode(ledPin[i], OUTPUT);      // sets the digital pins as output    char key = keypad.getKey();   if (key==1) {   if (key==*){     counter=i+1 /* start counting up by 1 */   } else if (key==-)   {     counter=i-1 /*etc  */   } } else if(key==2) {   if (key==*){     counter=i+2   } else if (key==-)   {     counter=i-2   } } else if(key==3) { counter=i+3 } else if etc....      }}`
I'm not sure how to write the counter function.
Title: Re: Binary counting using 12 LEDs
Post by: MarkT on Mar 12, 2013, 09:53 pm
character constants always have single quotes, so
Code: [Select]
` if (key==1)`
needs to be
Code: [Select]
` if (key=='1')`
and so on - the result of getKey() is one of the characters you put in the array so its a character code,
and the code for '1' is not 1.  Put another way '1' denotes the character code used, you never
need to see it or even know that its actually 49.

And if you are comparing the same integer or character variable against a set of possibilities then the
switch statement is much neater:
Code: [Select]
`  switch (key)  {  case '1': .....    break ;  case '*': ....    break ;  ......  }`
Title: Re: Binary counting using 12 LEDs
Post by: lloyddean on Mar 12, 2013, 10:36 pm
Code: [Select]
` if (key==1) {   if (key==*){     counter=i+1 /* start counting up by 1 */   } else if (key==-)`

If key equals '1' then it very well can't be '*' at the next 'if'
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Mar 12, 2013, 11:07 pm

Code: [Select]
` if (key==1) {   if (key==*){     counter=i+1 /* start counting up by 1 */   } else if (key==-)`

If key equals '1' then it very well can't be '*' at the next 'if'

That's why you read the key again. Also why is this not in the loop()?
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 13, 2013, 12:31 am
Code: [Select]
`/* Binary counting using 12 LEDs and a keypad to change the increasing or decreasing rate */#include <Keypad.h>int i;int x;int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int counter;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'} };/* I want to use i-- and i++ to either increaseor decrease the binary counting */byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);   for(i=0; i<12; i++){  pinMode(ledPin[i], OUTPUT);      // sets the digital pins as output  }void loop(){    char key = keypad.getKey();    if (key=='1') {   /* getKey for case A and case B   case A = increment   case B = decrement   */ } else if(key=='2') {    } else if(key=='3') { } else if(key=='4') {  } else if(key=='5') {  } else if(key=='6') {    } else if(key=='7') {    } else if(key=='8') {    } else if(key=='9') {    } else if(key=='0') {    }}`
Hope it looks better although it still has errors.
Now I have to figure out how to do the counting
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 13, 2013, 04:50 pm
There is an easier way to write this code by using "digitalWrite" but this
will result in a very long and boring code.
I'm not sure yet how this keypad will control  the binary counting.
Perhaps an attachInterrupt() might be needed to shift the code to a new loop.
I tried this with one switch only in order to control the LEDs but I wasn't able
to change "digitalWrite" into a counting loop.
I couldn't find any example on the internet of how to control a binary counting
using switches and I am a bit confused.

As you can see, I need your help.

Regards
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Mar 13, 2013, 04:59 pm
Try this.
Look at the key, if it is not '#' or '*' then store it in a variable, convert that variable to an int, and then wait for the key to be '#' or '*'. Once key is '#' or '*', the code will decide whether to make it + or - the counter.
Title: Re: Binary counting using 12 LEDs
Post by: spatula on Mar 13, 2013, 05:22 pm
Hi, I'm trying to figure out what you want to do and I'm still unsure. The case I have in mind is a sort of simple calculator using postfix notation, so if you type "123+-" this is translated into ((2+3)-1). Your case is probably simpler because you seem to allow only a value followed by an operator, so you never get two consecutive values or two consecutive operators.

Both ways, you need to make a distinction between values and operators: if a value key is entered you have to save the value until an operator key is pressed (you may display the value, but that is not essential and depends on how you design your "user interface"); if an operator key is pressed you need to perform the calculation and display it. You also need to save the last result, as input to the next operation.

In the simple case, you need to keep the last result and the last value entered in a variable that is not changed on each loop(), as the counter and x variables in your code (but using more meaningful names may help understand what they are for). Nothing prevents you from storing the last result (or last value, but not both) in digitalPins. Looks boring to code, but also instructive.

P.S. just saw HazardsMind's comment, seems we are on the same track.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 14, 2013, 09:38 am
I believe the last two replies are good answers to my problem.
This is exactly what I want to do:
get a key
if the key is an integer
get the second key
if second key is '*' or '#'
then, either increase or decrease the counting by the
value of the key
I will try to modify the above code during this weekend when I have more time
You are welcome with more suggestions.
Thank you guys for your help.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 16, 2013, 10:15 am

Hi, I'm trying to figure out what you want to do and I'm still unsure. The case I have in mind is a sort of simple calculator using postfix notation, so if you type "123+-" this is translated into ((2+3)-1). Your case is probably simpler because you seem to allow only a value followed by an operator, so you never get two consecutive values or two consecutive operators.

Both ways, you need to make a distinction between values and operators: if a value key is entered you have to save the value until an operator key is pressed (you may display the value, but that is not essential and depends on how you design your "user interface"); if an operator key is pressed you need to perform the calculation and display it. You also need to save the last result, as input to the next operation.

In the simple case, you need to keep the last result and the last value entered in a variable that is not changed on each loop(), as the counter and x variables in your code (but using more meaningful names may help understand what they are for). Nothing prevents you from storing the last result (or last value, but not both) in digitalPins. Looks boring to code, but also instructive.

P.S. just saw HazardsMind's comment, seems we are on the same track.

I'm struggling to do all of this.
This is my code for now.
Code: [Select]
`/* Binary counting using 12 LEDs and a keypad to control the increasing or decreasing rate by the value of the key pressed*/#include <Keypad.h>int i;int x;int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int counter;int firstKey;int secondKey;int mostSignificantBit;int leastSignificantBit;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'}} byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);   for(i=0; i<12; i++){  pinMode(ledPin[i], OUTPUT);      // sets the digital pins as output  }void loop(){    char key = customKeypad.getKey();    if (firstKey=='1') {  if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='2') {    if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='3') {  if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='4') {   if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='5') {   if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='6') {   if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='7') {   if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='8') {   if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else if(firstKey=='9') {   if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } } else (firstKey=='0') {   if (secondKey=='*'){   for(   }   else (secondKey=='#') {     for (   } }}`

I just wanted to make sure I am going in the right direction.
Can you check my code please to see what else is missing.
Some code examples would be useful.
I still don't know how to declare all the variables needed for my code.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: UKHeliBob on Mar 16, 2013, 02:41 pm
Your code as posted does not compile.

Apart from anything else the loop() function starts before the setup() function ends
I strongly suggest that you put each curly bracket in its own line so that you can see the indentation properly
Code: [Select]
`void setup(){  Serial.begin(9600);   for(i=0; i<12; i++)   {  pinMode(ledPin[i], OUTPUT);      // sets the digital pins as output  }void loop(){`
I would like to have Auto Formatted the code but it won't due to errors in it so I will leave that to you.

I still don't understand what you are trying to do.  Can you please explain it again ?
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 16, 2013, 03:35 pm

I still don't understand what you are trying to do.  Can you please explain it again ?

Perhaps the title of my topic is the wrong one.
It should have been: "Increment/decrement binary counter by any number"
or perhaps "Control a binary counter with a keypad".

I will explain it again.
My project include an Arduino Mega, a 4/3 keypad and 12 LEDs.
I want to give the keypad keys (number keys) their values and for '*' and '#' an operator function (increment or decrement).
At any time I only want to press two keys, a value key (number keys) and an operator key.
The operator key will either increment or decrement the binary counting (displayed on LEDs) by the
value of the number key pressed.
Hope this is clear.
I had a look at the increment/decrement operators but coudn't find
how to increase the counting by 3 for example.
In my case I want to use all the numbers from 1 to 10.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: UKHeliBob on Mar 16, 2013, 03:42 pm
How to increase a variable called number by 3
Code: [Select]
`number += 3;`
http://arduino.cc/en/Reference/IncrementCompound

or easier to understand perhaps
Code: [Select]
`number =  number + 3;`
http://arduino.cc/en/Reference/Arithmetic
Title: Re: Binary counting using 12 LEDs
Post by: spatula on Mar 16, 2013, 04:05 pm
Hi, the missing element in your description is what is the initial value that is incremented/decremented n times. I assume it is the last value computed by your function.

Obviously, incrementing a number n times is the same as adding n to the number. In code:
Code: [Select]
`for (int i = 0; i < incr; i++){  result++;}`

is equivalent to
Code: [Select]
`result = result + incr; // can also be abbreviated result += incr;`

Nobody would choose the first form, unless what you want is to show the intermediate results, i.e. switch the leds on and off until you reach the result. If this is the case you should state it in your description.

Another variation is: you don't keep the last result in memory, but just display it as a particular configuration of leds (each led is a bit, and the number is represented by the sequence of bits, i.e. on/off leds). This is interesting, because then each increment operation translates into toggling the current state of an led (with carry). But again, if this is what you want you should state it in your description.

About the code, as by previous suggestions you should start concentrating on the distinction between value keys and operator keys, without nesting the ifs (firstKey, secondKey). When an operator key is pressed perform the calculation and display the result, no need to remember the last operator key pressed in the next loops. To get a first working sketch, ignore the fact that entering 10 requires two value key presses.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 16, 2013, 04:29 pm
What if I could set a counting default (for example counting up by 1 until another keys are pressed)
instead of memorizing the last sequence?
It would be interesting, once the counting has started, to be able to modify it
by pressing two keys in sequence. This would start the counter from the default sequence,
but later, after managing to make it working I would try to modify the counter again and to start
from the last sequence.
This way, my binary counter will become a basic 12 bits binary calculator.
Anyway, first of all I have to figure out how to set a default counting
and to test it.
Many thanks for your replies.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Mar 16, 2013, 04:33 pm
Your if statements are driving me nuts, if key == '1', if key == '2'... Just make one that gets the key, stores it and converts it to a number. Use "number = key - '0' " to convert it.
Title: Re: Binary counting using 12 LEDs
Post by: spatula on Mar 16, 2013, 05:00 pm

What if I could set a counting default (for example counting up by 1 until another keys are pressed)
instead of memorizing the last sequence?
It would be interesting, once the counting has started, to be able to modify it
by pressing two keys in sequence. This would start the counter from the default sequence,
but later, after managing to make it working I would try to modify the counter again and to start
from the last sequence.
This way, my binary counter will become a basic 12 bits binary calculator.
Anyway, first of all I have to figure out how to set a default counting
and to test it.
Many thanks for your replies.
Regards

Remember you'll be working within a loop, letting the counter run free may defeat your intention to show that something changes when you press a key. Anyway, I think I finally figured out what you want: from a given configuration of 12 LEDs move to a different configuration representing a value 1 bit more or 1 bit less. E.g. (taking the rightmost 4 bits only) from [0 1 0 0] to [0 1 0 1] to [0 1 1 0] if the counter is 2 and the operation is ++.

Have you worked out the algorithm?
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Mar 16, 2013, 05:43 pm

What if I could set a counting default (for example counting up by 1 until another keys are pressed)
instead of memorizing the last sequence?
It would be interesting, once the counting has started, to be able to modify it
by pressing two keys in sequence. This would start the counter from the default sequence,
but later, after managing to make it working I would try to modify the counter again and to start
from the last sequence.
This way, my binary counter will become a basic 12 bits binary calculator.
Anyway, first of all I have to figure out how to set a default counting
and to test it.
Many thanks for your replies.
Regards

Remember you'll be working within a loop, letting the counter run free may defeat your intention to show that something changes when you press a key. Anyway, I think I finally figured out what you want: from a given configuration of 12 LEDs move to a different configuration representing a value 1 bit more or 1 bit less. E.g. (taking the rightmost 4 bits only) from [0 1 0 0] to [0 1 0 1] to [0 1 1 0] if the counter is 2 and the operation is ++.

Have you worked out the algorithm?

If that's the case then he should be using HEX.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Mar 16, 2013, 09:39 pm
I got it to work on my end, and the way I did it was just using regular ints, however I think you need it in HEX, but anyways here is my way.

What you need to do is look at the incoming char and see if it does not equal '#' AND '*', and then store it in another variable.
Next convert that variable into an int with "var = (Key - '0')"
Now you press the # or * and using if statements for each, you either add or subtract the variable and put the result in a new variable.

Note I have a 4x4 keypad, and I used my 'A' key to clear my variables back to zero. I suggest you have something similar, otherwise you will need to set the final result back to 0 manually. OR, you can just hold the value and adjust it as you please.

I really don't know any other way to explain how to do this, other than just giving you the code. This should be clear enough to understand and get it to work.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 17, 2013, 03:45 pm
Hi guys,
I did my best and modified my code following your suggestions.
Now this is my code:
Code: [Select]
`/* Binary counting using 12 LEDs and a keypad to control the increasing or decreasing rate by the value of the key pressed*/#include <Keypad.h>int i;int x; // variable to be used for the       // storage of the last sequenceint ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int number;int counter;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'}}; byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){     for(i=0; i<12; i++)   {    pinMode(ledPin[i], OUTPUT);      // sets the digital pins as output   }}void loop(){    char key = customKeypad.getKey();    if (key != '*' && key !='#'){        number = key - '0' ;        char key = customKeypad.getKey();        if (key = '#') // increment binary counter    {     for(counter = 0; counter < 4096; counter = counter + number){          digitalWrite(ledPin[i], HIGH);      delay (1000);    }    }        else if (key = '*') // decrement binary counter    {      for(counter = 0; counter < 4096; counter = counter - number ){      digitalWrite(ledPin[i], HIGH);      delay (1000);      }          }      } //end of if    } `
It now compiles without errors but I feel there is still something missing.
Can you have a look please?
Thanks again for your suggestions.
Regards

Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 17, 2013, 04:33 pm
I would like to give to key '0' on keypad the value 10.
Also, I'm not sure that I should state the most and least significant bits in my code
and how to memorize the value in binary of the last sequence.
It would be interesting if I could stop the counter (with LEDs on HIGH)
when pressed any key
until the start of the new counter, so I can prove that the last sequence
plus or minus the new key pressed adds up to the new sequence.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Mar 17, 2013, 04:56 pm
There are still issues in your code, but at the moment, it looks like you want to enter a number and then count up to it. So for that part, I would get rid of the 4096 and replace that with "number" and just have counter increment or decrement to it.

Also digitalWrite(ledpin, HIGH) does not do anything right now, because it does not know what "i" is. Change i to counter.

Let the dissection begin.
Code: [Select]
` void loop(){    char key = customKeypad.getKey();  if(key) {  //blocking from anything not needed.  if (key != '*' && key !='#'){       number = key - '0' ;  } // end of sort      if (key == '#') // increment binary counter  {     for(counter ; counter < number; counter++){ // Set counter = 0, at the top of code.      digitalWrite(ledPin[counter], HIGH);      delay (1000);      } // end of inc counter  } //end of '#'      if (key == '*') // decrement binary counter  {      for(counter; counter > number; counter--) {        if(counter < 0) counter = 0; // checks to see if counter does past zero then set it back to zero.        digitalWrite(ledPin[counter], LOW);        delay (1000);      }  // end of dec counter  } // end of '*'  } //end of if(key) } // end of loop`

Now, you only have 12 LEDs so why not enter 2 numbers and then decide to dec or inc them? Enter 1 and 2 to make 12, or 1 and 0 to get 10. It will be a little more coding but, give it a try. With these counters, the way you have them set up, you don't particularly need to you HEX anymore.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Mar 17, 2013, 09:05 pm

Now, you only have 12 LEDs so why not enter 2 numbers and then decide to dec or inc them? Enter 1 and 2 to make 12, or 1 and 0 to get 10. It will be a little more coding but, give it a try. With these counters, the way you have them set up, you don't particularly need to you HEX anymore.

This is a great idea and seems much simpler.
Perhaps there is no more need to store the last LEDs configuration.
Using all the numbers from 0 to 99 seems more interesting.
Thank you for your help.
Hope I can do it.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 02, 2013, 09:40 pm
Hi guys,
Sorry to bother you again but it still doesn't work.
This is my code:
Code: [Select]
`/* Binary counting using 12 LEDs and a keypad to control the increasing or decreasing rate by the value of the key pressed*/#include <Keypad.h>int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int number=0;int keyPressed=0;int counter=0;char firstKey;long previousMillis = 0;long interval = 1000;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'}}; byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);     for(counter=0; counter<12; counter++)   {    pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output   }}void loop(){    char key = customKeypad.getKey();  /*if (key) {    Serial.println(key);  }*/  if (key) { // blocking from anything not needed   keyPressed= keyPressed+1;   if (key != '*' && key !='#'){        number =key - '0' ; // convert key to its value  } // end of sort   if (keyPressed ==1){     firstKey=key;   }   if ( keyPressed==2){  Serial.println(firstKey);   //Serial.println(number);          if (key == '#') // increment binary counter    {       Serial.println("i"+firstKey);       //digitalWrite(13, HIGH);       //delay (1000);     for(counter=0; counter< number; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);       unsigned long currentMillis = millis();       if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis                } // end of increment counter    } // end of '#'            if (key == '*') // decrement binary counter    {      for(counter; counter < number; counter-- ){        if (counter < 0) counter = 0; // checks to see if        // counter does past zero then set it back to zero      digitalWrite(ledPin[counter], LOW);      unsigned long currentMillis = millis();      if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis           } // end of decrement counter          } // end of '*'    keyPressed=0;   } // end of keycount  } //end of if(key)    } // end of loop`

It only works when I insert the first input then, nothing.
I mean that it turns all the LEDs on (the number key pressed)
and keeps them on.
What about the binary counting?
Regards
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 12:05 am
Any suggestions...?
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 01:05 am
Try this.
http://arduino.cc/forum/index.php/topic,137352.30.html (http://arduino.cc/forum/index.php/topic,137352.30.html)
Title: Re: Binary counting using 12 LEDs
Post by: lloyddean on Apr 03, 2013, 04:16 am
This is posted with honest intent, not to criticize or discourage.

I posted some code earlier in an attempt to help, but then upon rereading your requirements decided that your requirements are ambiguous and deleted the post.

My suggestion (which you've seen stated here by others more than once) is to CLEARLY define your requirements.

Post them, accept feed back, modify and repost the requirements and looping until they are completely stated and can be coded from.

Without good documented requirements you haven't much of a chance in completing your task as you don't even know what it is you're trying to accomplish let alone getting useful assistance for someone who only thinks they know what you want.

I'm listening ...
Title: Re: Binary counting using 12 LEDs
Post by: lloyddean on Apr 03, 2013, 06:35 am
Concerning your current code the following snip-it, occurring twice, does nothing

Code: [Select]
`unsigned long currentMillis = millis();if ( (currentMillis - previousMillis) > interval ){    previousMillis = currentMillis;}`

If a multiple association condition test succeeds then you may safely use 'else' to exclude additional tests.

Code: [Select]
` if ( keyPressed == 1 ) { ... } else if ( keyPressed == 2 ) { ... if ( key == '#' ) { ... } else if ( key == '*' ) { ... } ... }`
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 08:50 am

My suggestion (which you've seen stated here by others more than once) is to CLEARLY define your requirements.

The reason I'm trying to use "millis" is because when using "delay" the keypad
reads the input only once then does nothing.
I am trying to use the keypad to control the binary counting on LEDs.
There are number keys (0,1,2,3,4,5,6,7,8,9) and operator keys (* and #).
I want to use the operator keys to either increase (pressing #) or decrease
(pressing *) the binary counting by the value of the number keys pressed.
Perhaps it would be nice to read two number keys at the time (going up to 99)
followed by an operator key.
To make it even more simpler:
2+5+'#' would count up by 25 (in binary)
I will try your last suggestion and also "HasardsMind's" suggestion.
In fact I'm working now on them.
I'll let you know about my progress.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 11:08 am
I think I made the matter worse.
The topic suggested by "HazardsMind" is not very useful.
I changed the if statements as suggested by "lloiddean"
and I think it should be fine. Then, I tried to add the first two keys
together and to store the result into the "sum".
Now, I get instead very big numbers instead (for example 9+9= 114 ).
The LEDs don't blink any more and I am not very sure about the loop
for getting the third key.
This is my code:
Code: [Select]
`/* Binary counting using 12 LEDs and a keypad to control the increasing or decreasing rate by the value of the key pressed*/#include <Keypad.h>int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int number=0;int keyPressed=0;int counter=0;int sum=0;char firstKey;char secondKey;long previousMillis = 0;long interval = 1000;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'}}; byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);     for(counter=0; counter<12; counter++)   {    pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output   }}void loop(){    char key = customKeypad.getKey();  /*if (key) {    Serial.println(key);  }*/  if (key) { // blocking from anything not needed   keyPressed= keyPressed+1;   if (key != '*' && key !='#'){        number =key - '0' ; // convert key to its value  } // end of sort   if (keyPressed ==1){     firstKey=key;   }  else if ( keyPressed==2){    secondKey=key;    sum=firstKey+secondKey;  Serial.println(sum);   //Serial.println(number);   if (keyPressed==3){   keyPressed=key;  // I'm not sure about this loop        if (key == '#') // increment binary counter    {       Serial.println("i"+firstKey);       //digitalWrite(13, HIGH);       //delay (1000);     for(counter=0; counter< number; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);       unsigned long currentMillis = millis();       if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis                } // end of increment counter    } // end of '#'            else if (key == '*') // decrement binary counter    {      for(counter; counter < number; counter-- ){        if (counter < 0) counter = 0; // checks to see if        // counter does past zero then set it back to zero      digitalWrite(ledPin[counter], LOW);      unsigned long currentMillis = millis();      if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis           } // end of decrement counter          } // end of '*'    } // end of keyPressed == 3    keyPressed=0;   } // end of keycount  } //end of if(key)    } // end of loop`
Title: Re: Binary counting using 12 LEDs
Post by: spatula on Apr 03, 2013, 11:50 am

Now, I get instead very big numbers instead (for example 9+9= 114 ).

Guess what the ASCII value of '9' is? 57. In
Code: [Select]
` sum=firstKey+secondKey;`
you are adding the characters ('0'..'9'), not the numbers (0..9).
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 03:59 pm

Guess what the ASCII value of '9' is? 57. In
Code: [Select]
` sum=firstKey+secondKey;`
you are adding the characters ('0'..'9'), not the numbers (0..9).

You are right.
I managed to do the code for addition.
Code: [Select]
`#include <Keypad.h>int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int number1=0;int number2=0;int keyPressed=0;int counter=0;int sum=0;char firstKey;char secondKey;long previousMillis = 0;long interval = 1000;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'}}; byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);     for(counter=0; counter<12; counter++)   {    pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output   }}void loop(){    char key = customKeypad.getKey();  /*if (key) {    Serial.println(key);  }*/  if (key) { // blocking from anything not needed   keyPressed= keyPressed+1;   if (key != '*' && key !='#'){      // number =key - '0' ; // convert key to its value  } // end of sort   if (keyPressed ==1){     number1= key - '0';     firstKey=key;   }  else if ( keyPressed==2){    number2= key - '0';    secondKey=key;    sum=(number1 *10)+number2;  Serial.println(sum);   //Serial.println(number);   if (sum){    char key = customKeypad.getKey();    // I'm not sure about this loop        if (key == '#') // increment binary counter    {       Serial.println("i"+firstKey);       //digitalWrite(13, HIGH);       //delay (1000);     for(counter=0; counter< sum; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);       unsigned long currentMillis = millis();       if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis                } // end of increment counter    } // end of '#'            else if (key == '*') // decrement binary counter    {      for(counter; counter < sum; counter-- ){        if (counter < 0) counter = 0; // checks to see if        // counter does past zero then set it back to zero      digitalWrite(ledPin[counter], LOW);      unsigned long currentMillis = millis();      if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis           } // end of decrement counter          } // end of '*'    } // end of sum    keyPressed=0;   } // end of keycount  } //end of if(key)    } // end of loop`
Now, when I press two numbers I get the right sum on the serial monitor.
However, if I press '*' I get minus 6. Similarly, for '#' I get minus 13.
How do I convert the third key to either increase the decrease the counting?
At the moment my LEDs don't do anything.
I also have to convert the input to binary counting.
How do I do it?
Regards
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 04:14 pm
The reason your getting -6 and -13 for # and * is beacuse you took out,
Quote
if (key != '*' && key !='#'){

// number =key - '0' ; // convert key to its value
} // end of sort

This part was making all the button work correctly. Try to do include this with "keyPressed ==1" and "keyPressed ==2".

Also that link I gave works fine. Im guessing you didn't fully understand it, no problem though. Your method will suffice.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 04:33 pm
How do I get then the sum If I put it back?
It doesn't work.
For the sum I need:
sum=(number1 *10)+number2;
Can I do it differently?
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 04:43 pm
Code: [Select]
`if (key != '*' && key !='#' && keyPressed ==1 ){     number1= key - '0';     firstKey=key;   }`

Repeat for second key press
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 05:08 pm
Thanks,
It works but I can only press two number keys at the time.
If I press either * or # it stops everything
The * and # keys still don't do anything and the counting doesn't start.
Now, what next?
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 05:32 pm
According to your code, you have everything inside keypress2, and with the "key != '*' && key !='#' ", it will never get to the other buttons. You need to fix your brackets. Keypress1 is fine, now do the same thing for Keypress2. You can keep the sum inside, but everything else must come out.

Im not home right now, nor did I bring my stuff with me to work.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 07:47 pm

According to your code, you have everything inside keypress2, and with the "key != '*' && key !='#' ", it will never get to the other buttons. You need to fix your brackets. Keypress1 is fine, now do the same thing for Keypress2. You can keep the sum inside, but everything else must come out.

Thanks,
I really don't know how to close that bracket or more exactly, where is
the right place to put it. It shows me lots of errors.
Look, this is my modified code:
Code: [Select]
`#include <Keypad.h>int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int number1=0;int number2=0;int keyPressed=0;int counter=0;int sum=0;char firstKey;char secondKey;long previousMillis = 0;long interval = 1000;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'}}; byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);     for(counter=0; counter<12; counter++)   {    pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output   }}void loop(){    char key = customKeypad.getKey();  /*if (key) {    Serial.println(key);  }*/  if (key) { // blocking from anything not needed   keyPressed= keyPressed+1;   if (key != '*' && key !='#'){      // number =key - '0' ; // convert key to its value  } // end of sort   if (key != '*' && key !='#'&& keyPressed ==1){     number1= key - '0';     firstKey=key;    } // end of key==1  else if (key != '*' && key !='#'&& keyPressed==2){    number2= key - '0';    secondKey=key;    sum=(number1 *10)+number2;     // end or key==2    //Serial.println(number);  if (sum){    char key = customKeypad.getKey();    // I'm not sure about this loop        if (key == '#') // increment binary counter    {       Serial.println("i"+firstKey);       //digitalWrite(13, HIGH);       //delay (1000);     for(counter=0; counter< sum; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);       unsigned long currentMillis = millis();       if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis               } // end of increment counter    } // end of '#'            else if (key == '*') // decrement binary counter    {      for(counter; counter < sum; counter-- ){        if (counter < 0) counter = 0; // checks to see if        // counter does past zero then set it back to zero      digitalWrite(ledPin[counter], LOW);      unsigned long currentMillis = millis();      if(currentMillis - previousMillis > interval) {        previousMillis = currentMillis;      } // end of millis          } // end of decrement counter          } // end of '*'    } // end of sum    keyPressed=0;   } // end of keycount   }//end of if(key)    }// end of loop`
If I close the bracket after "end of key==2", see above, I also
have to close the loop which is worse.
I've been trying since this morning.
I really don't know
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 08:00 pm
This is not needed.
Quote
if (sum){
char key = customKeypad.getKey();

Once you enter the two numbers, it should add them, then go back and allow you to enter # or *.

Code: [Select]
`else if (key != '*' && key !='#'&& keyPressed==2){    number2= key - '0';    secondKey=key;    sum=(number1 *10)+number2;}// done with else if`
Title: Re: Binary counting using 12 LEDs
Post by: lloyddean on Apr 03, 2013, 08:16 pm
I say again this code ...

Code: [Select]
`unsigned long currentMillis = millis();if ( currentMillis - previousMillis > interval ){ previousMillis = currentMillis;}`

... performs absolutely NO USEFUL PURPOSE and might as well be replaced with ...

Code: [Select]
`// WHAT ARE YOU LOOKING AT, NOTHING TO SEE HERE CARRY ON `

... or, a lot less typing ...

Code: [Select]

Code: [Select]
`else if ( key == '*' ){    // decrement binary counter        for ( counter; counter < sum; counter-- )   // << DOES COUNTER HAVE A USEFUL VALUE HERE    {`
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 08:29 pm
This is what I originally gave you.
Quote
if (key == '*') // decrement binary counter
{
for(counter; counter > number; counter--) {
if(counter < 0) counter = 0; // checks to see if counter does past zero then set it back to zero.        digitalWrite(ledPin[counter], LOW);
delay (1000);
}  // end of dec counter
} // end of '*'
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 09:46 pm
Hi guys,
I modified the code again following the last suggestions.
It compiles but doesn't work when I connect the circuit.
This is my code:
Code: [Select]
`#include <Keypad.h>int ledPin[12]={13,12,11,10,9,8,7,6,5,4,3,2};int number=0;int number1=0;int number2=0;int keyPressed=0;int counter=0;int sum=0;char firstKey;char secondKey;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'}}; byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypad Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);     for(counter=0; counter<12; counter++)   {    pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output   }}void loop(){    char key = customKeypad.getKey();  /*if (key) {    Serial.println(key);  }*/  if (key) { // blocking from anything not needed   keyPressed= keyPressed+1;   if (key != '*' && key !='#'){      // number =key - '0' ; // convert key to its value  } // end of sort   if (key != '*' && key !='#'&& keyPressed ==1){     number1= key - '0';     firstKey=key;    } // end of if  else if (key != '*' && key !='#'&& keyPressed==2){    number2= key - '0';    secondKey=key;    sum=(number1 *10)+number2;  }// end of else if    //Serial.println(number);     if (key == '#') // increment binary counter    {       Serial.println("i"+firstKey);       //digitalWrite(13, HIGH);       //delay (1000);     for(counter=0; counter< number; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);       delay(1000);           } // end of increment counter    } // end of '#'            if (key == '*') // decrement binary counter    {      for(counter; counter > number; counter-- ){        if (counter < 0) counter = 0; // checks to see if        // counter does past zero then set it back to zero      digitalWrite(ledPin[counter], LOW);        delay(1000);           } // end of decrement counter          } // end of '*'       keyPressed=0;       }//end of if(key)     }// end of loop`
What is wrong now?
It doesn't show any character on serial monitor
and the LEDs don't blink.
I have a question for "HazardsMind".
Should I use sum or number in counter loop?
Since I used sum = (number1*10)+number2,
perhaps is better to use sum.
What else is missing from this code?
Thank you everyone for your help.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 09:58 pm
No longer needed.
Quote
if (key != '*' && key !='#'){

// number =key - '0' ; // convert key to its value
} // end of sort

Take out "else" from here:
Quote
else if (key != '*' && key !='#'&& keyPressed==2){
number2= key - '0';
secondKey=key;
sum=(number1 *10)+number2;
}// end of else if

Right now your LEDs will only light up, not blink. You need to learn how to use the millis() timer properly.
Look into the blink without delay sketch.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 10:24 pm
Thank you very much
I did what you said but it still doesn't work.
I put the serial.println(sum); after
the end of the second if (end of else if in the above code)
and deleted the code you said.
I can assure you that my circuit is properly connected and it works
when I use either the keypad or LEDs separately.
Perhaps there is still something wrong in my code.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 03, 2013, 10:32 pm
I forgot to say that I get zero if I press
any key or combinations of keys.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 03, 2013, 11:51 pm
What about a serial print of number1 and 2 when you press them?
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 04, 2013, 01:05 am
If this is not what you want then I give up.
Code: [Select]
`#include <Keypad.h>int ledPin[12]={  13,12,11,10,9,8,7,6,5,4,3,2};int number[]={  0,0};int count = 0;int keyPressed=0;int counter=0;int sum=0;char firstKey;char secondKey;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = {  {    '1','2','3'    }  ,  {    '4','5','6'    }  ,  {    '7','8','9'    }  ,  {    '*','0','#'    }};byte rowPins[ROWS] = {  31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {  39, 41, 43}; //connect to the column pinouts of the keypadKeypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);  for(counter=0; counter<12; counter++)  {      pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output  }}void loop(){  char key = customKeypad.getKey();  /*if (key) {   Serial.println(key);   }*/  if (key) { // blocking from anything not needed    if (key != '*' && key !='#'){      Serial.print(key);      Serial.print(" ");      number[count] = key - '0';      if(count == 1) {        count = 0;         sum=(number[0] *10)+number[1];        Serial.print('\t');        Serial.println(sum);      }      else {        count++;       }     }  }  // end of else if  //Serial.println(number);  if (key == '#') // increment binary counter  {    Serial.println(sum++);    //digitalWrite(13, HIGH);    //delay (1000);    for(counter=0; counter< sum; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);      //delay(1000);    } // end of increment counter  } // end of '#'  if (key == '*') // decrement binary counter  {    Serial.println(sum--);    for(counter; counter > sum; counter-- ){      if (counter < 0) counter = 0; // checks to see if      // counter does past zero then set it back to zero      digitalWrite(ledPin[counter], LOW);      //delay(1000);    } // end of decrement counter  } // end of '*'}//end of loop`
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 10:08 am
Thanks,
It's much better.
It shows integer numbers on the LEDs
Perhaps I cannot expect more since this
project was a nightmare.
Just wondering, has anyone done it before?
I mean, to control a binary counting with a keypad.
HazardsMind is right to give up. I understand he's had enough.
Imagine how I feel, with less experience in programming.
I guess I have to give up too, since there is no way to do it.
Thank you again for your help.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: lloyddean on Apr 04, 2013, 10:28 am
In other words if you don't know what you want, or how it's to work, how can we help you  program it or debug it.

It's just not possible.

See my earlier suggestion and don't just ignore it as an unnecessary  inconvenience it's the basis of programming.
Title: Re: Binary counting using 12 LEDs
Post by: AWOL on Apr 04, 2013, 10:45 am
Quote
It shows integer numbers on the LEDs

You were expecting floating point, perhaps?
Imaginary numbers?
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 10:49 am

In other words if you don't know what you want, or how it's to work, how can we help you  program it or debug it.

It's just not possible.

I can assure you that I payed attention to all the messages for this topic
and I also clarified many times what I want.
Shall I do it again?
The keypad is in decimal and the LEDs are in binary.
The 12 bits in binary gives 4096 in decimal.
I want to get two numbers and an operator(either increment or decrement)
at the time and to convert it to binary.
Therefore, I want to either count up or down in binary
by the value of the number entered (in decimal).
Since two numbers (in decimal) gives the maximum value of 99, there is
enough room for the counter to go up to 4096.
I want the LEDs to show the different combinations of binary numbers
according to the chosen value.
Hope it's clear.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 10:50 am

Quote
It shows integer numbers on the LEDs

You were expecting floating point, perhaps?
Imaginary numbers?

No. I was expecting binary numbers.
Title: Re: Binary counting using 12 LEDs
Post by: AWOL on Apr 04, 2013, 10:58 am
Quote
No. I was expecting binary numbers.

And what did you get?
(I'm sorry - I'm really struggling to see your problem here)
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 11:05 am
For example, if I press 2+3+#
I get the first 5 LEDs HIGH
Instead I want to count up by this value in binary
Title: Re: Binary counting using 12 LEDs
Post by: AWOL on Apr 04, 2013, 11:16 am
So you're saying instead of five LEDs lighting (unary), you want to see 101? (where 1 is a lit LED)

If that's all you want, then rip out this bit
Code: [Select]
`for(counter=0; counter< sum; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);      //delay(1000);    }`
and substitute code based on "bitRead", "digitalWrite" and "sum"
Title: Re: Binary counting using 12 LEDs
Post by: UKHeliBob on Apr 04, 2013, 11:42 am
Can we review what you have got working and what still needs to be done ?

Can you output the current number to the Serial monitor ?  Forget the LEDs for now.
Can you add to or subtract from the number using the keypad ?

If you have got that far, then converting the number to binary for display on the LEDs should be relatively easy, but let's solve one problem at a time.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 01:53 pm

So you're saying instead of five LEDs lighting (unary), you want to see 101? (where 1 is a lit LED)

If that's all you want, then rip out this bit
Code: [Select]
`for(counter=0; counter< sum; counter++){      //digitalWrite(ledPin[counter-1], HIGH);      digitalWrite(ledPin[counter], HIGH);      //delay(1000);    }`
and substitute code based on "bitRead", "digitalWrite" and "sum"

Yes, that's exactly what I want
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 02:06 pm

Can we review what you have got working and what still needs to be done ?

Can you output the current number to the Serial monitor ?  Forget the LEDs for now.
Can you add to or subtract from the number using the keypad ?

If you have got that far, then converting the number to binary for display on the LEDs should be relatively easy, but let's solve one problem at a time.

OK,
I pressed some combinations of keys and this is the result:
1+ 2    12
1+ 9    19
2+ 7    27
1+ 1    11
11
1+2    12
12
1+0    10
10
0+0    0
0+5    5
5
0+2    2
2
1
0
This is what I got from my serial monitor.
The numbers on the left are the combinations of two keys.
On the right is the sum
Single numbers on the left is what I see on the LEDs
(the LEDs turned on)
If I press a big number (bigger than 12) all the LEDs will turn on
then, by pressing '*' many times I can subtract from the sum and
consequently turn LEDs off, one at the time.
then I can press '#' many times and turn LEDs on, one at the time
Hope this explains everything

Title: Re: Binary counting using 12 LEDs
Post by: UKHeliBob on Apr 04, 2013, 02:32 pm
Does adding or subtracting the number entered on the keypad change the number to be displayed OK ?
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 03:00 pm
Yes, that's right.
I'm using the code posted by HazardsMind
since the last code I posted is not able to turn on the LEDs.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 04, 2013, 03:02 pm
Quote
substitute code based on "bitRead", "digitalWrite" and "sum"

for(counter = 0; counter < 12; counter++)
{
byte My_bits = bitRead(sum, counter);
digitalWrite(counter,My_bits);
// some delay
}
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 03:25 pm
Thanks,
I changed the code following the last suggestion.
This is the code:

Code: [Select]
`#include <Keypad.h>int ledPin[12]={  13,12,11,10,9,8,7,6,5,4,3,2};int number[]={  0,0};int count = 0;int keyPressed=0;int counter=0;int sum=0;char firstKey;char secondKey;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = {  {'1','2','3'},    {'4','5','6'},    {'7','8','9'},    {'*','0','#'}};byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypadKeypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);  for(counter=0; counter<12; counter++)  {      pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output  }}void loop(){  char key = customKeypad.getKey();  /*if (key) {   Serial.println(key);   }*/  if (key) { // blocking from anything not needed    if (key != '*' && key !='#'){      Serial.print(key);      Serial.print(" ");      number[count] = key - '0';      if(count == 1) {        count = 0;        sum=(number[0] *10)+number[1];        Serial.print('\t');        Serial.println(sum);      }      else {        count++;      }    }  }  // end of else if  //Serial.println(number);  if (key == '#') // increment binary counter  {    Serial.println(sum++);    //digitalWrite(13, HIGH);    //delay (1000);    for(counter=0; counter<= 12; counter++)      {       byte My_bits=bitRead(sum,counter);      digitalWrite(counter, My_bits);      //delay(1000);      } // end of increment counter  } // end of '#'  if (key == '*') // decrement binary counter  {    Serial.println(sum--);    for(counter; counter > sum; counter-- )    {      if (counter < 0) counter = 0;      byte My_bits = bitRead(sum,counter);      digitalWrite(counter, My_bits);      //delay(1000);    } // end of decrement counter  } // end of '*'}//end of loop]`
It shows some LEDs on but it's not in binary.
At least I know how to count in binary.
I guess I am very close to my solution.
Title: Re: Binary counting using 12 LEDs
Post by: AWOL on Apr 04, 2013, 03:32 pm
Quote
It shows some LEDs on but it's not in binary.

But you're not going to describe any of it.

OK, good luck with the rest of your project.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 04, 2013, 03:32 pm
Quote
It shows some LEDs on but it's not in binary.

Ok so then what is it outputting?

Oh, you need to add +2 to the counter, because your leds start at pin 2.
So its, digitalWrite(counter + 2, My_bits);
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 04:06 pm

Quote
It shows some LEDs on but it's not in binary.

But you're not going to describe any of it.

OK, good luck with the rest of your project.

Of course I'm going to let you know about my progress
after so much trouble.
HazardsMind is right, so I added 2 to the counter.
Now I can insert any number in binary up to 99
then I can count up by one, by pressing '#' repeatedly.
However, I cannot count down, or subtract in binary.
Addition only works when adding 1, one at the time
That's it.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 04, 2013, 04:14 pm
This is wrong
Quote
for(counter; counter > sum; counter-- )
you still need to count up to 12, because your reading the position of the bits in the sum. Check out this link. http://wiring.org.co/reference/bitRead_.html (http://wiring.org.co/reference/bitRead_.html)
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 04, 2013, 04:25 pm
You are right.
Thanks
What about the two remaining problems?
Counting up by any number and
Counting down
In other words I want to be able to make
binary addition and subtraction
Regards
Title: Re: Binary counting using 12 LEDs
Post by: AWOL on Apr 04, 2013, 04:33 pm
The Arduino is quite capable of performing addition and subtraction.

If you've got the display of any given binary number between 0 and 4095 solved, then isolating your remaining problems should be trivial.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 04, 2013, 04:56 pm
Quote
Counting up by any number and
Counting down

Ok, so this would mean you need to save the old number and just add or subtract it from the new number. Once you have the sum or difference of the two, THEN you turn your LEDs on/off.

I suggest you make this, its own function and just pass in the sum or difference. You do know how to make functions that allow data to be inserted, right?
Code: [Select]
`for(counter=0; counter < 12; counter++)      {       byte My_bits=bitRead(sum,counter);       digitalWrite(counter, My_bits);      //delay(1000);      }`
Title: Re: Binary counting using 12 LEDs
Post by: UKHeliBob on Apr 04, 2013, 05:06 pm
Code: [Select]
`  for(counter=0; counter<= 12; counter++)`
Probably doing no harm, but how many LEDs have you got, 12 or 13 ?

Code: [Select]
`    for(counter; counter > sum; counter-- )`
What is the value of counter and sum when this loop executes ?

You could turn the display of the binary representation of your sum variable into a function and call it when necessary.  Get it working once and use it many times.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 04, 2013, 05:08 pm
Quote
for(counter=0; counter<= 12; counter++) Probably doing no harm, but how many LEDs have you got, 12 or 13 ?
I caught that and fixed the code I gave him. Now did he see the fix, I dont know, most likely not.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 05, 2013, 10:00 am
Hi guys,
Thank you for the last replies.
Just wondering what is missing now
To get a number displayed on the LEDs I usually
get that number plus 1
So I modified
sum=(number[0] *10)+number[1];
to
sum=(number[0] *10)+number[1]-1;
Now I get the right answer on LEDs but the wrong
one on the serial monitor(since new sum is sum minus 1)
I tried a different combination of:
counter+2 or counter +1 but it only works properly
when I use counter+2.
When using counter+1 I usually get sum minus half
Title: Re: Binary counting using 12 LEDs
Post by: AWOL on Apr 05, 2013, 10:25 am
Quote
but it only works properly
when I use counter+2.

If, instead of "counter", you used the word "outputPinIndex" or "binaryPlace", would that make it easier to understand?
Title: Re: Binary counting using 12 LEDs
Post by: UKHeliBob on Apr 05, 2013, 11:26 am
If you do
Code: [Select]
`sum = aNumber;`
then Serial.print the number and output it to the LEDs in binary and get a different number displayed on each, then obviously one or other is wrong and I know which one my bet would be on.  Do I remember correctly that your bit to pin conversion needed an offset of 2 because your LED pin numbers start at 2 ?

Have you tried
Code: [Select]
`Serial.println(sum, BIN);`
to get a binary output to the serial monitor ?

Have you written a function to input the number in binary to the LEDs as I suggested in an earlier post ?  That way you only have one place to look for the problem and put it right and you can test the function in a very simple program before you commit it to the main one,
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 05, 2013, 02:06 pm
I tried now what you said but the results are the same:
the correct answer on LEDs and sum-1 on serial monitor.
This is the code:
Code: [Select]
`#include <Keypad.h>int ledPin[12]={  13,12,11,10,9,8,7,6,5,4,3,2};int number[]={0,0};int count = 0;int keyPressed=0;int counter=0;int sum=0;char firstKey;char secondKey;const byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = {  {'1','2','3'},    {'4','5','6'},    {'7','8','9'},    {'*','0','#'}};byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypadKeypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);  for(counter=0; counter<12; counter++)  {      pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output  }}void loop(){  char key = customKeypad.getKey();  /*if (key) {   Serial.println(key);   }*/  if (key) { // blocking from anything not needed    if (key != '*' && key !='#'){      Serial.print(key);      Serial.print(" ");      number[count] = key - '0';      if(count == 1) {        count = 0;         sum=(number[0] *10)+number[1]-1;        Serial.print('\t');        Serial.println(sum,BIN);      }      else {        count++;       }     }  }  // end of else if  //Serial.println(number);  if (key == '#') // increment binary counter  {    Serial.println(sum++);        for(counter=0; counter<= 12; counter++)      {       byte My_bits=bitRead(sum,counter);       digitalWrite(counter+2, My_bits);      //delay(1000);      } // end of increment counter  } // end of '#'  if (key == '*') // decrement binary counter  {    Serial.println(sum--);    for(counter; counter > sum; counter-- )    {      if (counter < 0) counter = 0;       byte My_bits = bitRead(sum,counter);      digitalWrite(counter+2, My_bits);      //delay(1000);    } // end of decrement counter  } // end of '*'}//end of loop`
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 05, 2013, 02:14 pm
I modified it a little, it should work now. Also now you can set the number of digits you want to enter, with "limit": default is 1.
Code: [Select]
`#include <Keypad.h>int ledPin[12]={  13,12,11,10,9,8,7,6,5,4,3,2};int number[]={  0,0};int limit = 1; //  1= 00 - 99, 2 = 000 - 999, 3 = 0000 - 4095 New variable, THE NUMBER OF DIGITS YOU NEED TO ENTER.int count = 0;int counter=0;My_number = 0; // New variableFinal_Num = 0;  // New variableconst byte ROWS = 4; //four rowsconst byte COLS = 3; //three columnschar keys[ROWS][COLS] = {  {'1','2','3'},    {'4','5','6'},    {'7','8','9'},    {'*','0','#'}};byte rowPins[ROWS] = {31, 33, 35, 37}; //connect to the row pinouts of the keypadbyte colPins[COLS] = {39, 41, 43}; //connect to the column pinouts of the keypadKeypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );void setup(){  Serial.begin(9600);  for(counter=0; counter<12; counter++)  {      pinMode(ledPin[counter], OUTPUT);      // sets the digital pins as output  }}void loop(){  char key = customKeypad.getKey();  /*if (key) {   Serial.println(key);   }*/  if (key) { // blocking from anything not needed    if (key != '*' && key !='#'){      Serial.print(key);      Serial.print(" ");      number[count] = key - '0';      if(count == limit) {        count = 0;      if( limit == 3)  My_number = (number[0] *1000) + (number[1] * 100) + (number[2] * 10) + number[3];      else if( limit == 2) My_number = (number[0] *100) + (number[1] * 10) + number[2];      else My_number = (number[0] *10) + number[1] ;        Serial.print('\t');        Serial.println(My_number);      }      else {        count++;      }    }  }  // end of else if  //Serial.println(number);  if (key == '#') // increment binary counter  {    Final_Num += My_number;    if(Final_Num > 4095) {          Final_Num = 4095;     }    Serial.println(Final_Num);    //digitalWrite(13, HIGH);    //delay (1000);    for(counter = 0; counter < 12; counter++)      {       byte My_bits=bitRead(Final_Num,counter);      digitalWrite(counter + 2, My_bits);      //delay(1000);      } // end of increment counter  } // end of '#'  if (key == '*') // decrement binary counter  {    Final_Num -= My_number;    if(Final_Num < 0) {          Final_Num = 0;     }    Serial.println(Final_Num);    for(counter = 0; counter < 12; counter++)    {      byte My_bits = bitRead(Final_Num,counter);      digitalWrite(counter + 2, My_bits);      //delay(1000);    } // end of decrement counter  } // end of '*'}//end of loop`
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 05, 2013, 02:52 pm
These are both ints
Quote
My_number = 0; // New variable
Final_Num = 0;  // New variable

fixed
Code: [Select]
`int My_number = 0; // New variableint Final_Num = 0;  // New variable`

I knew I forgot something.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 05, 2013, 03:26 pm
Hi guys,
I want to thank everyone who helped me sort out this code.
Now is working and I can do the things I wanted to do:
a basic binary calculator with addition and subtraction and with
the display of the results on LEDs.
I've taken so long to answer because I wanted to make sure
it works, so I tested it many times.
However, may I ask you the last question?
There is still something I don't understand.
Sometimes it doesn't take all the input (all the keys pressed)
and so affecting the results
and I'm trying to figure out this strange behavior.
Is there anything to do with the delay?
Thanks guys for everything.
Regards
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 05, 2013, 03:31 pm
What does it not take? As for right now, it is set to only take 00 - 99, as set by the limit. Since you only have 12 LEDs, you can only go as high as 4095, anything higher and it will automatically make it 4095. Unless you want rollover in which case you would need to add more code.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 05, 2013, 03:46 pm
It's not about rollover.
Imagine I insert 12, then 12 again, then I take a few seconds break.
It stops everything and I have to start again from zero since it
doesn't take any more input.
Perhaps the little break might stop the key input.
I don't think this is a big problem.
Title: Re: Binary counting using 12 LEDs
Post by: HazardsMind on Apr 05, 2013, 04:23 pm
Here is why.
Quote
int number[]={
0,0};

change it to,
Code: [Select]
`int number[]={  0,0,0,0};`

You might be able to modify the code a little more, to where you can enter any number and have it count. So right now if limit is 1, you need to enter 2 digits. 0 2 => 2 or 1 9=> 19. But you can modify it so that if you press 5 # it should just add 5, without needing to enter 0 5. Its something you should be able to do on your own.
Title: Re: Binary counting using 12 LEDs
Post by: littlewolf on Apr 05, 2013, 10:01 pm
Thank you again
I'm thinking already of a new challenging project.
See you then.
Regards