Go Down

Topic: Communication with the PC problem! (Read 519 times) previous topic - next topic


Hello. I wrote some code after watching a tutorial on Youtube. Basically, I'd like to control an LED through the communication window.

However, the code does not work. Please take a look at it.

Code: [Select]
int ledPin = 5;

void setup(){

void loop(){

  while(Serial.available() == 0);

     int val = Serial.read() - '0';

if(val == 1){
  digitalWrite(ledPin, HIGH); // this doesn't executed
  Serial.println("LED ON"); // this gets executed
else if(val == 0){
  digitalWrite(ledPin, LOW);
  Serial.println("LED OFF"); this gets executed



Also, the Serial.flush() doesn't work. If I type in "asd" in the window, I get three "ERROR!" lines, instead of just one.

Please help me control the LED and figure the Serial.flush() out!

Thx in advance!


It might work better if you call pinMode() in setup to set the LED pin as an output.



And, you should read up on what flush() does, now. It blocks until the outgoing serial buffer is empty. Hardly useful in your situation.

There is no means of emptying the incoming serial buffer without reading everything. For good reason.
The art of getting good answers lies in asking good questions.


There is at least one fundamental flaw in your program.  This line
Code: [Select]
  while(Serial.available() == 0);checks to make sure that there is nothing in the serial input buffer and if there is nothing there it reads a byte from it.
Code: [Select]
    int val = Serial.read() - '0';
Is that going to work I wonder ?
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.


Very simple LED on/off via the serial monitor.

Code: [Select]

// zoomkat 8-6-10 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later

int ledPin = 13;
String readString;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.println("serial on/off test 0021"); // so I can keep track

void loop() {

  while (Serial.available()) {
    char c = Serial.read();
    readString += c;

  if (readString.length() >0) {

    if (readString == "on")     
      digitalWrite(ledPin, HIGH);
    if (readString == "off")
      digitalWrite(ledPin, LOW);


Google forum search: Use Google Search box in upper right side of this page.
Why I like my 2005 Rio Yellow Honda S2000  https://www.youtube.com/watch?v=pWjMvrkUqX0


Thanks guys! I added "pinMode(5, OUTPUT);" & changed the first line in the loop to "while(Serial.available()){", now it works just as intended. Thx!

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131