Needs assistance for my codes (digitalRead HIGH and LOW)

Hi guys I'm a newbie, I need you to check if the codes I've written are correct... coz I'm not sure what's the problem.. I was supposed to come up with a HIGH value in (Arduino nano) pin8 only when pin 2 (input) send a high value (i used 5vdc, and then the LOW value of pin2 is 1.2vdc and HIGH value of 4vdc...) But the problem here is that the output reading starts with a LOW value and even if a haven't set up a HIGH value yet on pin2 (input), pin8 (output) goes high for 3 to 4 seconds and then returns to zero.. this goes on and on... However, if a send a HIGH value to the Input pin2, the HIGH output is ok... I'm confused why Im having a HIGH output even I haven't done in the INPUT... Here are the codes....

//assign variables int lev1 = 2; //input from ckt1 int alert1 = 8; //1st LED alarm output

void setup() { // initialize input ckt pins as input: pinMode(lev1, INPUT); // initialize alarm LEDs as outputs pinMode(alert1, OUTPUT);

Serial.begin(9600); }

void loop() { // read input pins: int voltagevalue = digitalRead(lev1);

if (voltagevalue == HIGH) { digitalWrite(alert1, HIGH); } else { digitalWrite(alert1, LOW); } Serial.println(voltagevalue); delay(500); }

Here's how to post code, formatted & in code tags. They're going to beat you up for not doing that. Any minute now..

//assign variables
int lev1 = 2; //input from ckt1
int alert1 = 8; //1st LED alarm output


void setup() {
  // initialize input ckt pins as input:
  pinMode(lev1, INPUT);
  // initialize alarm LEDs as outputs
  pinMode(alert1, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  // read input pins:
  int voltagevalue = digitalRead(lev1);

  if (voltagevalue == HIGH)
  {
    digitalWrite(alert1, HIGH);
  }
  else
  {
    digitalWrite(alert1, LOW);
  }
  Serial.println(voltagevalue);
  delay(500);
}

-jim lee

ok thanks..

Oh try..

pinMode(lev1, INPUT_PULLUP);

-jim lee

yup i tried that one.... but still the same..

Then you should post your circuit.

Clearly.

And, why all the periods? You get them in bulk or something?

-jim lee

jim are my codes ok? coz if it is ok, i guess there's problem on my circuit

are my codes ok?

IF you have wired the switch correctly, the code is correct, although voltagevalue is a dumb name for the state of a pin.

Ok thanks. I'll check the circuit connection