Turn LEDs on/off

Hi,

I have made my first Arduino prototype, consisting of two LEDs (one red, one green), a stepper motor and a button. It’s going to be a prototype of a pill dispenser. What i want is, make the red LED light up when the programs starts, then when the button is pressed, the red LED turns off, and the green turns on (while the stepper motor turns)

The problem now, is that the red LED turns on, and when the button is pressed, the green LED turns on while the stepper motor turns. But then the green LED turns off again, and the red turns on, but it should not be on again?

#include <Stepper.h>

#define STEPS 100
Stepper stepper(STEPS, 8, 9, 10, 11);

const int buttonPin = 2;   
const int ledPinRed =  12;
const int ledPinGreen =  13;

int buttonState = 0;   

void setup() {
  
  pinMode(ledPinRed, OUTPUT);
  pinMode(ledPinGreen, OUTPUT);
  pinMode(buttonPin, INPUT); 
  stepper.setSpeed(100);

}

void loop() {
  int val = 1;
  buttonState = digitalRead(buttonPin);
  if(val == 1){
  digitalWrite(ledPinRed, HIGH);
  digitalWrite(ledPinGreen, LOW);
  }
  
  if (buttonState == HIGH){ 
  digitalWrite(ledPinRed, LOW); 
  digitalWrite(ledPinGreen,HIGH);
  stepper.step(200);
  val = 2;
  }
}

Hope that some of you can help out with the code

If you want the red LED to be on only until a green light is on and never again then move the digitalWrite that turns it on into the setup function.

However you are not very clear on what you want to happen.

void loop() {
  int val = 1;
  buttonState = digitalRead(buttonPin);
  if(val == 1){

When will val not be 1 when it is tested ?

Well the purpose of the program is to simulate af pill dispenser scenario.

The red LED will be on (or turn on after some seconds), to indicate it's time to take pills. Then the user press the button, and the stepper motor turns, while the red LED turns off, and the green LED turns on, and stays on

@UKHeliBob

I see. I will get that corrected.

Try and remember that the code in loop gets repeated a couple of thousand time per second.

Then the user press the button, and the stepper motor turns, while the red LED turns off, and the green LED turns on, and stays on

So it this a one shot, one time only pill dispenser?

What you describe is way more complected than your code.

@UKHeliBob

I see. I will get that corrected.

The way this forum works is that you now correct this, and if it does not do what you want you post your code again and say what it does and what you expected to do.