Go Down

Topic: Help with code that is not working correctly (Read 1 time) previous topic - next topic

el_supremo

The two 'if' statements with && should be inside the first 'if' statement so that they are only tested when a serial character is available.
Code: [Select]
void loop()
{
  buttonState = digitalRead(buttonPin);

  if (Serial.available() > 0) {
    incomingByte = Serial.read();
    if (incomingByte == 'H' && buttonState == HIGH) {
      myservo.write(180);
      delay(1500);
      digitalWrite(ledPin, HIGH); 

    }
    if (incomingByte == 'L' && buttonState == LOW) {
      myservo.write(90);
      delay(1500);
      digitalWrite(ledPin, LOW);

    }
  }
}


Pete

guix

So you have to type a command AND use a button to move the servo? Are you sure you don't need to use || instead, so you either type a command, or use the button ?

swilliams1284

the servo will be used to lock a deadbolt, the switch will detect when the door is closed so the deadbolt only moves when the door is closed, also i ahave already tried it with || with no luck

CrossRoads

#18
Oct 16, 2012, 05:25 am Last Edit: Oct 16, 2012, 06:33 am by Coding Badly Reason: 1
Try adding some ()s, such as:

if ((incomingByte == 'H') && (buttonState == HIGH)) {
Designing & building electrical circuits for over 25 years. Check out the ATMega1284P based Bobuino and other '328P & '1284P creations & offerings at  www.crossroadsfencing.com/BobuinoRev17.
Arduino for Teens available at Amazon.com.

Coding Badly


Apparently @swilliams1284 wanted a change of scenery.  He's moved the conversation here...
http://arduino.cc/forum/index.php/topic,127428.0.html

Nick Gammon


I'm thinking it has something to do with the && operators? Any ideas?


You've found a problem with the && operator? Well done!

Meanwhile, please don't start a new thread about exactly the same code as the existing one.

Threads merged.

Nick Gammon

Would you mind telling us why you have to type a command on the serial console, and hit a button to lock/unlock this door?

Nick Gammon


in the code i have a servo move to 180 degrees if it detects that the button is in a HIGH state and it reads an H from the serial port. The individual pieces of the circuit work when being tested by them selves so its not hardware related as far as i can tell, I'm thinking it has something to do with the && operators? Any ideas?

Code: [Select]


void loop()
{
  buttonState = digitalRead(buttonPin);

if (Serial.available() > 0) {

incomingByte = Serial.read();

}

if (incomingByte == 'H' && buttonState == HIGH) {
  myservo.write(180);
  delay(1500);
  digitalWrite(ledPin, HIGH); 
 
}




You are testing incomingByte whether or not you just read it. Why?

PaulS

Something I'm curious about. You seem to be able to use the Serial Monitor and Serial class to get data to the Arduino, but you don't seem to be able to use the Serial class and Serial Monitor to get data FROM the Arduino. Curious.

Go Up