Go Down

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

PaulS

Quote
Sorry, but the return type of "Seria.read" is "int".

True, but, if you KNOW that there is data to read, because you have called Serial.available(), you can store the output in a byte sized variable, with no data loss. Often, this is a desirable thing to do.

swilliams1284

SO anybody have any idea what is up? the sketch works perfectly fine if i remove the moving of the servo, the LED part I mean.

swilliams1284

nevermind everybody fixed it, used previous suggestion of adding a delay, added a 1500ms delay after writing the servo position!

PaulS

Quote
the sketch works perfectly fine

What sketch is that? The one full of errors that we have been pointing out, or something derived from that that fixes the errors?

What does removing the servo moving code have to do with incorrectly reading serial data?

swilliams1284

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]
#include <Servo.h>

Servo myservo;

const int buttonPin = 2;
const int ledPin = 13;
int incomingByte;

int buttonState = 0;

void setup(){
myservo.attach(9);
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);

}

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);

}

}

Go Up