serial comunication security system serial monitor problem

im trying to make a security system were you have to have # before the password to for the arduino to respond e.g if the password is pi you would have to write #pi in the serial monitor fro the arduino to actually respond. if the password is pi and i type in the serial monitor #pi the arduino is supposed to respond with acess.# then acess.a then, acess.b and then acess granted but so far it only responds with acess.# although im tyinping in #pi could someone plz help me.

ascii

= 35

p = 112
i = 105

code

int valhash = 0; // password initializer
int vala = 0;// first char in password
int valb = 0;// second char in password
void setup()
{
Serial.begin(9600);
}

void loop()
{
while( Serial.available()==0);

int val = Serial.read();
int vali= Serial.read(); // initialze pasword value

if(vali == 35)
{
if (val == 35) // if # key is pressed
{
Serial.println("acess.#");
valhash = 1;
Serial.println( valhash);
}

else
{
valhash == 0;
}
}
if(vali == 35)
{
if (val == 112) // p is pressed
{
Serial.println("acess.a");
vala = 1;
Serial.println( vala);
}

else
{
vala == 0;
}
} // end of p loop

if(vali == 35)
{
if ( val == 105)// i is pressed
{
Serial.println("acess.b");
valb = 1;
Serial.println( valb);
}

else
{
valb == 0;
}
} //end of i loop

else if ( vali == 35) // acess denied
{
Serial.println("acess denied");
}

if (vala == 1 && valb == 1 && valhash)
{
Serial.println( "acess granted");
}
// end of pass granted loop

if ( val >= 0)// resets values of val
{
vala == 0;
valb == 0;
valhash == 0;
}
}

Please put this in code tags, #

It's best not to use the ascii values use '#', 'p','i' instead.

Mark

  while( Serial.available()==0);
 
 int val = Serial.read();
 int vali= Serial.read(); // initialze pasword value

Wait until there is at least 1 character in the serial buffer, then read both of them. Doesn't sound right, does it? When you type multiple characters into the Serial monitor and hit send, those characters aren't sent all at the same time; your loop function could run hundreads of times before the second character gets there.

if (val == 35) // if # key is pressed

Using decimal values for ASCII characters only makes the code more confusing. This makes much more sense:

if (val == '#')
 while( Serial.available()==0);
 
 int val = Serial.read();
 int vali= Serial.read(); /

Oh dear! The usual complaint.

while( Serial.available()==0);
 
 int val = Serial.read();
 int vali= Serial.read(); // initialze pasword value

The odds are that there is only one char in the buffer so vali will be -1.

Mark

Ok thanks , but is there a way to send a string in the serial monitor

You are sending a string with the serial monitor. But it is sent in serial and the processor is so much faster than the Serial comms than it will see only one char at a time.

Mark