ATtiny85 digitalRead

I recently got a ATtiny85(And a Sparkfun tiny AVR programmer) that I want to read if a button is pressed or not. I cannot use just a basic circuit to make an LED turn on if a button is pressed because I want the LED to stay on for one second, regardless of how long the button is pushed.

So, for a basic test, I tried the ATtiny just turning on the LED when the button is on. My code is below:

int blinkPin = 0;
int val = 0;
int inpin = 3;
int sendpin = 2;
void setup()
  pinMode(blinkPin, OUTPUT);
  pinMode(sendpin, OUTPUT);
  pinMode(inpin, INPUT);

void loop()
  digitalWrite(sendpin, HIGH);
  val = digitalRead(inpin);
  digitalWrite(blinkPin, val);

I compile and run the code, and there are no errors, but the problem is the LED randomly fluctuates between off, on, and some analog reading. To make sure this wasn't a problem with the programmer, I changed the pin numbers and ran it on an Adafuit Feather M0. It did the exact same thing as on my ATtiny. This leads me to think that it is either something stupid I overlooked in the program or some other setting. Please note I am using Arduino 1.8.9 and Windows 8.1.

Thank you very much for any help you can give.

You are not showing your circuit/connections.

Do you have any pullup on the input pin? If not, try pinMode(inpin, INPUT_PULLUP);


When you have a pin connected to a button, when the button is not pressed, the pin is not connected to anything. If you have the pin set INPUT, the pin is in an undefined state; it is said to be "floating" - it will pick up electromagnetic noise from the environment, and have an effectively random voltage (somewhere between Gnd and Vcc, because the protection diodes will keep it within that range). To solve this, you put a resistor between the pin and whatever supply rail it should take the voltage of when not pressed.

If the button connects the pin to Vcc when pressed, it needs to have a resistor from Gnd to the pin.

If the button connects the pin to Gnd when pressed, it needs to have a resistor from Vcc to the pin - there is an internal pullup that you can use with INPUT_PULLUP, so you don't need an external resistor; that's one of the reasons this is the preferred configuration for a button (it's also safer, because you don't need the other side of all your buttons tied to Vcc, just ground, so damaged wiring is less likely to end up shorting out the power supply).

If you do have to use an external resistor, values between 10k and 100k are suitable.

Thanks! It's working now. I really appreciate your help.