Go Down

Topic: help with serial (Read 370 times) previous topic - next topic

flyboy

I'm trying to get my arduino to respond to serial commands so that I can then progress toward implementing a remote control home automation-esque application later on.  The problem is that I can't get it to switch between states.  Can someone please review my code and give me some input?  I'm getting tripped up somewhere, but I'm not sure where.

Code: [Select]
int ledPin = 13;
int number_in = 0;
int state = 0;
#define BLINK   0
#define NO_BLINK   1

    void setup() {
      pinMode(ledPin, OUTPUT);
      Serial.begin(115200);
    }

    void loop() {
      readSerial();
     
      switch(state) {

        case BLINK:

           digitalWrite(ledPin, HIGH);
           delay(1000);
           digitalWrite(ledPin, LOW);
           delay(300);
           readSerial();
           if(number_in == 1)
            {
                state = NO_BLINK;
            }
        break;

        case NO_BLINK:

           digitalWrite(ledPin, LOW);
           readSerial();
           if(number_in == 0)
                {
                    state = BLINK;
                }
         break;
        }
    }

    void readSerial() {
        if (Serial.available() > 0) {
          number_in = Serial.read();
        }
      }         

wildbill

I'd guess that this:
Code: [Select]
           if(number_in == 1)

should be this:
Code: [Select]
           if(number_in == '1')

and the same for the similar test below. I assume you're typing 1 and 0 into the serial monitor, not somehow sending ascii char 1 and 0?

robtillaart

try it with char's first

Code: [Select]

int ledPin = 13;

char char_in = '';

int state = 0;

#define BLINK   0
#define NO_BLINK   1

void setup()
{
 pinMode(ledPin, OUTPUT);
 Serial.begin(115200);
}

void loop()
{
 char_in = readSerial();
   
 switch(state)
 {
   case BLINK:
     digitalWrite(ledPin, HIGH);
     delay(1000);
     digitalWrite(ledPin, LOW);
     delay(300);
     char_in = readSerial();
     if (char_in == '1')
     {
       state = NO_BLINK;
     }
     break;

   case NO_BLINK:
     digitalWrite(ledPin, LOW);
     char_in = readSerial();
     if(char_in == '0')
     {
       state = BLINK;
     }
     break;
 }
}

char readSerial()
{
 if (Serial.available() > 0) return Serial.read();
 return '';  // empty char
}      
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

flyboy

That did it!  I figured it was something simple.  Thanks guys.

Go Up