Different behavior when powered from 9V power source vs USB

Hello. I have done some looking around and have not been able to find anything relating to the problem I am having.

Setup:

I am running a Mega 2560 REV3.

I have an led on digital pin 4 and a momentary push button (NO) signal on digital pin 5. The switch is connected to the 5V supply pin.

Code:

// Pin Identification

const int led = 4;
const int button = 5;


void setup() {


  // Name led pin as output
  pinMode(led, OUTPUT);
  
  // Name button pin as input
  pinMode (button, INPUT);
 
 }


void loop() {

    // Turn on led if button is pressed
    digitalWrite(led, LOW);
    if (digitalRead(button) == HIGH)
    {digitalWrite(led, HIGH);}
   }

Issue:

When the Arduino is being powered by my computer via the USB connection, the LED functions as I expected, turning on when I depress the switch and turning off when I release the switch.
My power supply I planned on using in my project is 9V (measures 9.23V), and is plugged in the built-in port. As soon as I turn on the power supply, the LED lights up at about half brightness. It then gets brighter when I depress the switch. Why is that? Is that something I can overcome?

It is running the exact same code each time; all I do is flip on the switch to the power supply.

In troubleshooting this, I wrote and uploaded code to make the same LED flash on and off with a two second delay and no switch input. That worked fine, with the LED turning all the way off and all the way back on.

I am new to this, so I am hoping there is a simple solution that I am unaware of. I'd appreciate any help.

Thanks

Is it a 9V battery or a decent power supply?

Do you have a resistor in series with the led?

Lastly, your input is floating and hence constantly toggling between low and high when not pressed; use a pull-down resistor or wire the switch between pin and ground and use pinMode(button, INPUT_PULLUP).

Thanks for the reply.

It is a good power supply, not a battery.

I do not have a resistor in the circuit with the led.

Wiring the switch between pin and ground and using pinMode(button, INPUT_PULLUP) solved my problem.

Thanks again!

You have to put a resistor in series with the led. Not doing so will overload the processor of the Arduino and, when using an external power supply, the regulator of the Arduino.