Switch on and off LED in Arduino using PySerial

When one starts off learning about Arduino, the Blind LED is one of the most popular programs to begin with. As you go up the learning ladder you find asking the question of ‘Hang on! What if I want to change the blink rate dynamically ?’ How would one go about doing that ?

Or breaking it further, how to turn on and off led with my discretion

Well, off the bat the first thing I could think of is using the Serial port to send the signal to switch on and off the LED. Ardruino has a default command that can be used for this purpose:

Serial.available()

” Get the number of bytes (characters) available for reading from the serial port. This is data that’s already arrived and stored in the serial receive buffer (which holds 64 bytes). available() inherits from the Stream utility class ”

Arduino code:

char c;
int led = 13;
boolean ledLightUp = false;

void setup(){
  Serial.begin(9600);
  pinMode(led,OUTPUT);
}

void loop()
{
// When a user sends serial data then read and execute the following
   if (Serial.available() > 0)
    {
      c = Serial.read(); 
      Serial.println(c);
      if(c == 'y')
      {
        ledLightUp = true;
        Serial.println("LED ON");
      }
      else if(c == 'n')
      {
        ledLightUp = false;
        Serial.println("LED OFF");
      }
    }
  if(ledLightUp){
    digitalWrite(led,HIGH);
  }  
  else{
    digitalWrite(led,LOW);
  }
}

 

Python code:

>> import serial,struct
>> ser = serial.Serial('your port name', 9600)
>> ser.write(struct.pack('b',enter here 'y' or 'n' with paranthesis))

 

You can watch the following video I made that demonstrates the essence of this post.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s