From one to two buttons

Hey everyone,
i'm new to this field. i'd appreciate some help.
i have programmed a small program that print random number when i press a button. it works.
however, i dont know how to add a second button. can you help?

//constants
const int buttonPin = 2; //push button blue


const int ledPin = 13; // uno board led

//variables
int buttonState = 0; // current button state
int lastButtonState = 0; //previous button state

int randVal = 0; // random num. to be sent

void setup() {
  //initialise the button pin 2
  pinMode(buttonPin, INPUT);
  //initialise the LED
  pinMode (ledPin, OUTPUT);
  //initialise serial communication
  Serial.begin(9600);
  //end setup 
}

void loop() {
  //set rand number
  randVal = random(1000);

  //read button state
  buttonState = digitalRead(buttonPin);

  //compare the states
  if (buttonState != lastButtonState){

    if(buttonState==HIGH) {
      Serial.println(randVal);

    }else{
      
    }

    delay(50);
  }

  lastButtonState = buttonState;


}

Duplicate all code involving the button, only changing the name of the 'buttonPin' variable and changing the number assigned to it.

What have you tried to get this to work and where did you get stuck? If you managed to make the sketch for 1 button, surely you must have at least attempted modifying it to add a second. It's generally more educational/useful (and more fun) if you do the work and others help you along.

What does this second button do?

1 Like

Ask the teacher for a push. That's what he is there for.

thanks.
I'll clarify my wish.
I want to change the main function so it could be relevant to two or more buttons.
my logic says that I should declare different buttons, and then pass them to the function. I don't know how to do it.

is my logic right?

You can't watch any pin during delay() but you may not be ready for Blink Without Delay yet.

With only 2 buttons that fingers press, you can get away with short delays needed to debounce the buttons.... say 20ms and some code change in how you read (only delay after state change, not every time) the button and you won't notice the difference at all.

If/when you learn non-blocking and state machine (simple at the heart but need practice to really get) techniques, you also learn a different approach to coding that makes do multiple things at once much easier.. I've had beginners call it Ninja Code!

If you want, I will link you to tutorials written for beginners....

but for now you can get around that and increase your awareness to speed and timing.

Biggest reason to not use delay() is that every ms in delay completely wastes 16000 CPU cycles.

That's not really done for the first button either, so apparently it's not necessary.

How did you manage to make the code to work you've got now? Did you write it, or did you copy/borrow it from someone else?

1 Like

Your logic is tied to your approach. If it works, that's right enough!

i would be great. thanks

I know it is not in the code. Indeed not necessary for one button. but I want to expend the program and want to find a solution which is not copying the code again and again.

I wrote the code following a tutorial i saw on youtube. I connect the arduino to a music program and triger drums with the buttons.

Ok, I get it.

Well, how to code it efficiently depends on what kind of action you need from the buttons.

Alright, how does the Arduino 'talk to' the music program? Does it send text/characters over Serial? Can you show an example of this?

with one button, it just sends a number (randVal) through serial port. i get this number in the music program and use it to trigger the sound.
so with two (or more) buttons I need to somehow print two different randVal with an some kind of index.
for example:
BlueButton 847
RedButton 309
That will be great.
I do know how to process such data in the music program.

You will want to read about Arduino Arrays. This will allow you to configure and use many buttons with only a few lines...

Define the buttons...

const int buttonPins[] = {2, 3, 4, 5, 6, 7, 8, 9 };

Configure the buttons...

void setup() {
.
  for (int i = 0; i < 8; i++) {
    pinMode(buttonPin[i], INPUT_PULLUP);
.
}

Using the button pressed will be up to you.

OK, I see.

Hold on, because you're going to have to learn lots to do this right.

One way to handle this would be to use arrays; you can use a two-dimensional array with button numbers and the values you want to send, like this:
[1][847]
[2][309]
In this example, '1' would represent the blue button, '2' the red one. The values next to them would be the number that's sent over UART.
Instead of 1 and 2 you could also use the pin numbers that the buttons attach to.

In your coding, you would initialize the buttons (using pinMode) as inputs and then in the loop() read those buttons regularly. Each time a button is pressed, you use a for-loop to cycle through the array and then print out the value that matches the button that was pressed.

This is at a conceptual level the approach I would follow. I can imagine it will take some study to get this to work, so my suggestion is to begin by familiarizing yourself with arrays and for-loops. Regardless of which direction your programming is going to take you, you will reap the benefits of this knowledge, so it's a good investment.

Thanks a lot. I'll dig into that!

Thanks!

Here is the first --- it uses time, it's about not blocking execution in void loop() instead of do-nothing-while-waiting-for-something.

The principle is simpler than the techniques. It takes practice to get into long term memory. Practice and pick up tricks/techniques is a good way up.

This has a State Machine as the second example, it's filled with techniques!

State Machines are coding power tools!
State is short for Process State. The machine keeps track of what it is doing so it can exit and pick back up next time it runs.
A single timer that runs when the wait (exit till time is up no-block wait!) is > 0 followed by the state machine lets the state machine not need internal timers, just set start time and wait > 0 before exiting.
The state machine changes it's own State when the current state/step is finished. You will see that. I have put state machines inside of state machines to analyze text before.... simple principles can make very complex code!

The bigger library of explaining many how-to's.

Maybe finish what you're doing and revisit later?
The difference of the later version to the version now will be a real lesson you won't forget!

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.