Recent Posts

#2 Arduino Mega: Serial Communication to Toggle the LED


IoT Tutorial #2 [ Arduino Mega Tutorials #2 ]
Here I will demonstrate the mini project, Turning ON / OFF the LED using wired Serial Communication using Arduino Mega (ATMega 2560).

Problem Statement:
To Turn ON / OFF the LED using wired Serial Communication (Tx0 and Rx0).
Serial communication will be done by USB cable (A to B)

Requirements:
- Arduino Mega (ATMega 2560)
- USB Cable (A to B)
- 1 LED
- 1k Resistor
- Bread Board
- Male to Male wires (minimum 2)



Program Outcome:
Output is shown using LED
If Desktop keyboard key "a" / "A" is pressed  -> LED ON
If Desktop keyboard key "b" / "B" is pressed  -> LED OFF

Message displayed on Arduino Terminal on Desktop using 
serial communication (Tx0 and Rx0).
NOTE:
Baud Rate is set to 9600
Physical Connection:
Pin 13    ->  LED+ (Through 1K Resistor)
Gnd       ->  LED-

Serial Communication Through USB Cable (Tx0 and Rx0)
Downloads:
Download link is given in the Description of the YouTube video shown below.

Demonstration:





Program:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600); //Tx0 and Rx0  //Set Baud Rate to 9600 for Serial Communication Tx0 and Rx0
  //Serial1;  //Tx1 and Rx1
  //Serial2;  //Tx2 and Rx2
  //Serial3;  //Tx3 and Rx3

  pinMode(13, OUTPUT);  //Set Pin 13 as Output (Connected to LED)

  Serial.println("press \"a\" to switch ON the LED");
  Serial.println("press \"b\" to switch OFF the LED");
}

void loop() {
  // put your main code here, to run repeatedly:
  
  if(Serial.available() > 0)
  {
    int buffer_value = Serial.read();
    if(buffer_value == 'a')
    {
      digitalWrite(13, HIGH);  //Turn ON LED
      Serial.println("LED ON"); 
    }
    else if(buffer_value == 'b')
    {
      digitalWrite(13, LOW);  //Turn OFF LED
      Serial.println("LED OFF"); 
    }
  }
}

Click here to see more codes for Arduino Mega (ATMega 2560) and similar Family.

Feel free to ask doubts in the comment section. I will try my best to solve it.
If you find this helpful by any mean like, comment and share the post.
This is the simplest way to encourage me to keep doing such work.

Thanks and Regards,
-Akshay P. Daga

2 comments:

  1. I can not able to understand program given below
    if(Serial.available ()>0)
    {
    int buffer_value = Serial.read();
    if(buffer_value == 'a')
    {

    ReplyDelete
    Replies
    1. Harsh, Thanks for the feedback.
      I have made correction now.

      if(Serial.available() > 0)
      {
      int buffer_value = Serial.read();
      if(buffer_value == 'a')
      {

      Delete