From smart curtains to automated conveyor belts, DC motors power countless IoT solutions. However, directly connecting them to an Arduino isn’t enough. That’s where the L298N motor driver comes in—a powerful solution for speed and direction control in real-world automation projects. One of the most popular methods for achieving this is by using an Arduino with the L298N motor driver. This blog will guide you through the process of connecting and controlling DC motors with Arduino and L298N for IoT projects.
Why Use the L298N Motor Driver?
When working with DC motors in IoT automation projects, directly connecting them to an Arduino is not feasible. This is because DC motors require more current and voltage than what an Arduino can supply. This is where the L298n Motor Driver Arduino setup becomes essential, as it acts as a bridge between the Arduino and the motors.
1. Handles High Voltage and Current
The L298N can control motors with voltages up to 35V and currents up to 2A per channel.
Arduino operates at 5V and can only supply a few milliamps, which is not enough for a motor.
2. Bidirectional Motor Control (H-Bridge Design)
The L298N uses an H-Bridge circuit, allowing it to change the direction of the motor without needing extra relays or switches.
You can make the motor move forward, backward, or stop using simple digital signals from Arduino.
3. Speed Control with PWM
The L298N has ENA and ENB pins that accept PWM signals from the Arduino.
This allows for smooth speed control of DC motors.
4. Can Control Two Motors Simultaneously
The L298N has two motor channels (A & B), meaning it can control two motors independently.
Perfect for robotics, automated vehicles, or conveyor belt systems.
5. Built-in Protection and Voltage Regulation
It has thermal protection, preventing overheating.
Comes with an onboard 5V regulator, which can supply power to Arduino (if needed).
Comprehensive Control of a DC Motor:
Achieving full control over a DC motor in IoT automation requires the ability to regulate both its speed and direction. This is accomplished using two key techniques:
Pulse Width Modulation (PWM): Enables precise speed control by varying the motor’s input voltage.
H-Bridge Circuit: Facilitates bidirectional movement by dynamically reversing the motor’s polarity.
Let’s learn more about these techniques:
1. Controlling DC Motor Speed Using PWM The speed of a DC motor depends on the voltage supplied to it. To control this voltage efficiently, we use Pulse Width Modulation (PWM).
How PWM Works:
PWM rapidly switches the motor ON and OFF at a high frequency.
The Duty Cycle (percentage of time the signal is ON) determines the average voltage supplied to the motor.
A higher duty cycle means more power, making the motor run faster.
A lower duty cycle reduces power, making the motor run slower.
The image below illustrates the PWM technique, demonstrating different duty cycles and their corresponding average voltages.
The speed of a DC motor controlled by PWM can be calculated using the duty cycle formula:
2. H-Bridge – Controlling Motor Direction The direction of a DC motor can be changed by reversing the polarity of its input voltage. A common method to achieve this is using an H-Bridge circuit.
By activating specific switches, the voltage polarity across the motor changes, causing it to spin in the opposite direction.
This allows precise forward and reverse control of the motor.
H-Bridge Control Logic:
IN1
IN2
Motor Direction
HIGH
LOW
Forward
LOW
HIGH
Backward
LOW
LOW
Stop
The animation below illustrates how an H-Bridge circuit controls motor direction.
H-Bridge circuit controls motor direction
L298N Motor Driver Chip:
The L298N motor driver is a widely used dual H-Bridge IC that enables efficient control of DC motors and stepper motors. It is commonly used in robotics, IoT automation, and motor control systems where independent speed and direction control of multiple motors is required.
Key Features of the L298N Motor Driver
Controls Two DC Motors Independently – Allows separate speed and direction control for each motor.
Supports PWM for Speed Control – Enables smooth acceleration and deceleration.
Works with a Wide Voltage Range – Operates with motors from 5V to 35V and provides up to 2A per channel.
H-Bridge Circuitry – Enables bidirectional motor control (forward & reverse).
Built-in Thermal Shutdown – Protects against overheating and excessive current.
Compatible with Microcontrollers – Works with Arduino, ESP8266, ESP32, Raspberry Pi, and other platforms.
Technical Specification:
Parameter
Specification
Operating Voltage
5V – 35V
Output Current
Up to 2A per channel
Logic Voltage
5V
Logic Current
0 – 36mA
PWM Support
Yes
Controlled Motors
2 DC or 1 Stepper Motor
Built-in Protection
Thermal shutdown
Technical Specification
L298N Motor Driver Module Pinout Overview:
L298N Motor Driver Module Pinout Diagram
Understanding the Pinout of the L298N Motor Driver Module
The L298N motor driver module is designed to control two DC motors or one stepper motor using an H-Bridge circuit. Below is a brief explanation of each pin:
1. Power Pins:
The L298N motor driver has two input power pins: VS and VSS and one GND pin.
VS[1] → Connects to an external power source (5V to 35V) for driving the motors.
GND[2] → Common ground connection for both logic and motor power.
VSS[3] → Provides a regulated 5V output (used when operating at voltages above 7V).
2.Motor Output Pins:
The L298N motor driver module has two output channels for connecting motors:
OUT1 & OUT2[8] → Connect Motor A
OUT3 & OUT4 [9]→ Connect Motor B
These outputs are provided through screw terminals for easy wiring.
You can connect two DC motors (5V-12V) to these terminals. Each motor channel can provide up to 2A of current, but the actual current depends on your power supply’s capacity.
3. Control Pins (For Motor Direction):
IN1 & IN2 [5](Motor A Control):
IN1 = HIGH & IN2 = LOW → Motor A moves forward
IN1 = LOW & IN2 = HIGH → Motor A moves backward
IN1 = IN2 → Motor A stops
IN3 & IN4 [6](Motor B Control):
IN3 = HIGH & IN4 = LOW → Motor B moves forward
IN3 = LOW & IN4 = HIGH → Motor B moves backward
IN3 = IN4 → Motor B stops
4. Enable Pins (For Speed Control using PWM):
Setting these pins to HIGH will make the motors spin, while setting them to LOW will stop them. However, you can control the speed of the motors using Pulse Width Modulation (PWM), which allows you to adjust how fast they spin.
By default, the module has a jumper on these pins, which makes the motors run at full speed. If you want to control the speed programmatically, you need to remove the jumper and connect these pins to the PWM-enabled pins of an Arduino or microcontroller.
ENA [4] (Enable A) → Controls the speed of Motor A via PWM signal.
ENB [7] (Enable B) → Controls the speed of Motor B via PWM signal.
If ENA/ENB = HIGH, the corresponding motor is enabled.
If ENA/ENB = LOW, the corresponding motor is disabled.
Voltage Drop in L298N Motor Driver:
The L298N motor driver has an internal voltage drop due to its built-in transistors, which affects the voltage supplied to the motors. This drop depends on the motor power supply voltage and the current drawn by the motors.
Typical Voltage Drop:
When using a 12V power supply, the actual voltage available to the motors is around 10V due to a 2V drop per channel.
The voltage drop increases as motor current increases, typically between 1.8V to 3V per channel.
At higher currents (above 1A per channel), the voltage drop can reach up to 4V, reducing motor efficiency.
Impact of Voltage Drop:
If your motor requires a specific voltage (e.g., 12V), you should use a higher power supply voltage (e.g., 15V–18V) to compensate for the loss.
For low-voltage motors (5V–6V), the voltage drop can significantly affect performance, making other motor drivers (e.g., DRV8871, TB6612FNG) a better choice.
Wiring an L298N Motor Driver Module to an Arduino:
To control two DC motors using the L298N motor driver and Arduino, follow these wiring steps carefully:
1. Powering the Motor Driver:
Connect the 12V (VCC) pin of the L298N to the positive terminal of the battery pack (6V-12V). This powers the motors.
Connect the GND pin of the L298N to the negative terminal of the battery pack.
Connect the same GND pin of L298N to the GND pin of Arduino to ensure a common ground.
2. Connecting Motor A (Left Motor) to L298N:
Connect one motor terminal to the OUT1 pin on the L298N.
Connect the other motor terminal to the OUT2 pin on the L298N.
The motor’s direction depends on the HIGH/LOW signals sent to IN1 and IN2.
3. Connecting Motor B (Right Motor) to L298N:
Connect one motor terminal to the OUT3 pin on the L298N.
Connect the other motor terminal to the OUT4 pin on the L298N.
The motor’s direction depends on the HIGH/LOW signals sent to IN3 and IN4.
4. Connecting the L298N to Arduino:
ENA (Enable A) pin → Arduino Pin 9 (PWM) → Controls speed of Motor A.
IN1 pin → Arduino Pin 7 → Controls Motor A Direction.
IN2 pin → Arduino Pin 8 → Controls Motor A Direction.
ENB (Enable B) pin → Arduino Pin 10 (PWM) → Controls speed of Motor B.
IN3 pin → Arduino Pin 5 → Controls Motor B Direction.
IN4 pin → Arduino Pin 6 → Controls Motor B Direction.
5. Optional: Powering Arduino from L298N
If using a 12V battery pack, the 5V output of L298N can provide power to Arduino by connecting it to the Arduino’s 5V pin.
Important: If using an external Arduino power source, remove the jumper cap on the L298N 5V output to prevent damage.
Circuit Diagram:
Arduino Code:
#define ENA 9 // Enable A (PWM control for Motor A)
#define IN1 8 // Input 1 for Motor A
#define IN2 7 // Input 2 for Motor A
#define ENB 3 // Enable B (PWM control for Motor B)
#define IN3 5 // Input 1 for Motor B
#define IN4 4 // Input 2 for Motor B
void setup() {
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
}
void loop() {
moveForward();
delay(2000);
moveBackward();
delay(2000);
stopMotors();
delay(2000);
}
void moveForward() {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
analogWrite(ENA, 150);
analogWrite(ENB, 150);
}
void moveBackward() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
analogWrite(ENA, 150);
analogWrite(ENB, 150);
}
void stopMotors() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}
IOT Applications
1. Smart Home Automated Curtains
Description: A DC motor can be used to open and close curtains remotely via an IoT-based system.
Using the L298N motor driver with Arduino provides an efficient and reliable way to control DC motors for IoT automation. This setup enables smooth motor operation, including speed control and direction changes, making it ideal for smart home applications, robotics, and industrial automation.
By integrating an IoT module, such as ESP8266, ESP32, or Raspberry Pi, users can remotely control motors via a web interface or mobile app, thereby enhancing automation and convenience. The flexibility and scalability of this system make it a cost-effective solution for various IoT-based motor control applications.
With the right coding and hardware setup, this project can be extended for real-world use cases such as automated conveyor systems, smart locks, and home automation. By leveraging Arduino’s versatility and IoT connectivity, users can create more intelligent and responsive systems for modern automation needs.
Image(s) used in this blog belong to their respective owners. If you own the rights and would like credit or removal, please contact us on contact@spurqlabs.com.
As a Software Development Engineer in Test (SDET), I specialize in developing automation scripts for mobile applications with integrated hardware for both Android and iOS devices. In addition to my software expertise, I have designed and implemented PCB layouts and hardware systems for integrating various components such as sensors, relays, Arduino Mega, and Raspberry Pi 4. I programmed the Raspberry Pi 4 and Arduino Mega using C/C++ and Python to control connected devices. I developed communication protocols, including UART, I2C, and SPI, for real-time data transmission and also implemented SSH communication to interface between the hardware and testing framework.
Building a solenoid control system with a Raspberry Pi to automate screen touch means using the Raspberry Pi as the main controller for IoT Solenoid Touch Control. This system uses relays to control solenoids based on user commands, allowing for automated and accurate touchscreen actions. The Raspberry Pi is perfect for this because it’s easy to program and can handle the timing and order of solenoid movements, making touchscreen automation smooth and efficient. Additionally, this IoT Solenoid Touch Control system is useful in IoT (Internet of Things) applications, enabling remote control and monitoring, and enhancing the versatility and functionality of the setup.
Components Required:
Raspberry Pi (Any model with GPIO pins):
In our system, the Raspberry Pi acts as the master unit, automating screen touches with solenoids and providing a central control hub for hardware interactions. Its ability to seamlessly establish SSH connections and dispatch commands makes it highly efficient in integrating with our framework.
Key benefits include:
Effective Solenoid Control: The Raspberry Pi oversees and monitors solenoid operations, ensuring precise and responsive automation.
Remote Connectivity: With internet access and the ability to connect to other devices, the Raspberry Pi enables remote control and monitoring, enhancing flexibility and convenience.
Command Validation and Routing: Upon receiving commands, the Raspberry Pi validates them and directs them to the appropriate hardware or slave units. For instance, it can forward a command to check the status of a smart lock, process the response, and relay the information back to the framework.
Solenoide Holder(fix the solenoid):
A solenoid holder is crucial for ensuring the stability, protection, and efficiency of a solenoid control system. It simplifies installation and maintenance while improving the overall performance and extending the solenoid’s lifespan.
In this particular setup, the solenoid holders are custom-manufactured to meet the specific requirements of my system. Different screen setups may require differently designed holders.
Incorporating a solenoid holder in your Raspberry Pi touchscreen control system results in a more robust, reliable, and user-friendly solution.
Solenoid (Voltage matching your power supply):
Integrating solenoids into a Raspberry Pi touchscreen setup offers an effective method for adding mechanical interactivity and automating screen touches. To ensure optimal performance, it’s essential to choose a solenoid with the right voltage, current rating, and size for your specific application.
Whether you’re automating tasks, enhancing user experience, or implementing security features, solenoids play a vital role in achieving your project goals. With careful integration and precise control, they enable you to create a dynamic and responsive system.
Relay Module (Matching solenoid voltage and current rating):
A relay module acts as a switch controlled by the Raspberry Pi, enabling safe and isolated control of higher-power solenoids. To ensure reliable operation, choose a relay that can handle the solenoid’s current requirements.
Relay modules simplify complex wiring by providing clear connection points for your Raspberry Pi, power supply, and the devices you wish to control. These modules often come with multiple relays (e.g., 1, 2, 4, or 8 channels), allowing independent control of several devices.
Key terminals include:
COM (Common): The common terminal of the relay switch, typically connected to the power supply unit you want to switch.
NO (Normally Open): Disconnected from the COM terminal by default. When the relay is activated, the NO terminal connects to COM, completing the circuit for your device.
NC (Normally Closed): Connected to COM in the unactivated state. When the relay activates, the connection between NC and COM breaks.
Touchscreen display:
Touchscreens are like interactive windows on our devices. Imagine a smooth surface that reacts to your fingertip. This is the magic of touchscreens. They use hidden sensors to detect your touch and tell the device where you pressed. This lets you tap icons, swipe through menus, or even draw pictures – all directly on the screen. No more hunting for tiny buttons, just a natural and intuitive way to control your smartphones, tablets, and many other devices.
Breadboard and Jumper Wires:
Breadboard and jumper wires act as your temporary electronics workbench. They let you connect components without soldering, allowing for easy prototyping and testing. You can push wires into the breadboard’s holes to create circuits, making modifications and troubleshooting a breeze before finalizing the connections.
Voltage level Converter:
In our project, the voltage level converter plays a critical role in ensuring communication between the Raspberry Pi and the relay module. The relay module, like some other devices, needs a specific voltage (5V) to understand and respond to commands. However, the Raspberry Pi’s GPIO pins speak a different voltage language – they can only output signals up to 3.3V.
Directly connecting the relay module to the Raspberry Pi’s GPIO pin wouldn’t work. The lower voltage wouldn’t be enough to activate the relay, causing malfunctions. Here’s where the voltage level converter comes in. It acts as a translator, boosting the Raspberry Pi’s 3.3V signal to the 5V required by the relay module. This ensures clear and compatible communication between the two devices, allowing them to work together seamlessly.
Power Supply (Separate for Raspberry Pi and Solenoid):
We need two separate power supplies for safe and reliable operation.A 5V 2A power supply specifically powers your Raspberry Pi. It provides the lower voltage the Pi needs to function.A separate 24V 10A Switching Mode Power Supply (SMPS) powers the solenoid. This higher voltage and current capacity are necessary for the solenoid’s operation. Using separate power supplies isolates the Raspberry Pi’s delicate circuitry from the potentially higher power fluctuations of the solenoid, ensuring safety and proper operation of both.Each power supply is chosen to meet the specific requirements of its component: 5V for the Pi and a higher voltage/current for the solenoid.
Circuit Diagram:
Power Supply Connections:
Connect the Raspberry Pi power supply to the Raspberry Pi.
Connect the positive terminal of the separate power supply to one side of the solenoid.
Connect the negative terminal of the separate power supply to the common terminal of the relay.
Relay Module Connections:
Connect the Vcc pin of the relay module to the 5V pin of the Raspberry Pi.
Connect the GND pin of the relay module to the GND pin of the Raspberry Pi.
Connect a chosen GPIO pin from the Raspberry Pi (like GPIO 18) to the IN terminal of the relay module. This pin will be controlled by your Python code.
Connect one side of the solenoid to the Normally Open (NO) terminal of the relay module. This means the solenoid circuit is only complete when the relay is activated.
Connecting the Raspberry Pi to the Level Converter:
Connect a GPIO pin from the Raspberry Pi (e.g., GPIO17) to one of the LV channels (e.g., LV1) on the level converter.
Connecting the Level Converter to the Relay Module:
Connect the corresponding high-voltage (HV) pin (e.g., HV1) on the level converter to the IN1 pin of the relay module.
Connect the HV pin on the level converter to the VCC pin of the relay module (typically 5V).
Connect the GND pin on the HV side of the level converter to the GND pin of the relay module.
Powering the Relay Module:
Ensure the relay module is connected to a 5V power supply. This can be done using the 5V pin from the Raspberry Pi or a separate 5V power supply if needed. Connect this to the VCC pin of the relay module.
Ensure the GND of the relay module is connected to the GND of the Raspberry Pi to have a common ground.
Connecting the Relay Module to the Solenoid and 24V Power Supply:
Connect the NO (normally open) terminal of the relay to one terminal of the solenoid.
Connect the COM (common) terminal of the relay to the negative terminal of the 24V power supply.
Connect the other terminal of the solenoid to the positive terminal of the 24V power supply.
Software Setup:
Raspberry Pi Setup:
Let’s make setting up our Raspberry Pi with Raspbian OS, connecting it to Wi-Fi, and enabling VNC feel as straightforward as baking a fresh batch of cookies. Here’s a step-by-step guide:
1. Install Raspbian OS Using Raspberry Pi Imager:
Download Raspberry Pi Imager:
Install the Imager on our computer—it’s like the secret ingredient for our Raspberry Pi recipe.
Prepare Our Micro-SD Card:
Insert our micro-SD card into our computer.
Open Raspberry Pi Imager.
Choose the Raspberry Pi OS version you want (usually the latest one).
Select our SD card. Click “Write” and let the magic happen. This process might take a few minutes.
Connect Our Raspberry Pi via LAN Cable:
Plug one end of an ethernet cable into our Raspberry Pi’s Ethernet port.
Connect the other end to our router (the one with the internet connection).
Power Up Our Raspberry Pi:
Insert the micro-SD card into our Raspberry Pi.
Connect the power supply to our Pi.
Wait for it to boot up like a sleepy bear waking from hibernation.
Configure Wi-Fi and Enable VNC:
Find Our Raspberry Pi’s IP Address:
On our Raspberry Pi, open a terminal (you can find it in the menu or use the shortcut Ctrl+Alt+T).
Type hostname -I and press Enter. This will reveal our Pi’s IP address.
Access Our Router’s Admin Interface:
Open a web browser and enter our router’s IP address (usually something like 192.168.1.1) in the address bar.
Log in using our router’s credentials (check the manual or the back of our router for the default username and password)
Assign a Static IP to Our Raspberry Pi:
Look for the DHCP settings or LAN settings section.
Add a new static IP entry for our Raspberry Pi using the IP address you found earlier. Save the changes.
Enable VNC on Our Raspberry Pi:
On our Raspberry Pi, open the terminal again.
Type sudo raspi-config and press Enter.
Navigate to Interfacing Options > VNC and enable it.
Exit the configuration tool.
Access Our Raspberry Pi Remotely via VNC:
On our computer (not the Raspberry Pi), download a VNC viewer application (like RealVNC Viewer).
Open the viewer and enter our Raspberry Pi’s IP address.
When prompted, enter the password you set during VNC setup on our Pi.
2. Install Python Libraries:
Use the Raspberry Pi terminal to install the necessary Python libraries. You’ll likely need:
3. Python Code Development:
Write Python code to:
Activate the corresponding GPIO pin based on the touched button to control the relay.
Python code:
import RPi.GPIO as GPIO
import time
# GPIO pin numbers for the relays
relay_pins = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def setup():
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbering
for pin in relay_pins:
GPIO.setup(pin, GPIO.OUT) # Set each pin as an output
GPIO.output(pin, GPIO.HIGH) # Initialise all relays to off (assuming active low)
def activate_solenoid(solenoid_number, duration=1):
if 1 <= solenoid_number <= 12:
pin = relay_pins[solenoid_number - 1]
GPIO.output(pin, GPIO.LOW) # Turn on the relay (assuming active low)
time.sleep(duration) # Keep the solenoid activated for the specified duration
GPIO.output(pin, GPIO.HIGH) # Turn off the relay
def cleanup():
GPIO.cleanup()
def get_user_input():
while True:
try:
user_input = input("Enter the solenoid number to activate (1-12), or 'q' to quit: ")
if user_input.lower() == 'q':
break
solenoid_number = int(user_input)
if 1 <= solenoid_number <= 12:
activate_solenoid(solenoid_number)
else:
print("Please enter a number between 1 and 12.")
except ValueError:
print("Invalid input. Please enter a number between 1 and 12, or 'q' to quit.")
if _name_ == "_main_":
try:
setup()
get_user_input()
except KeyboardInterrupt:
print("Program terminated")
finally:
cleanup()
Additional Considerations:
Flyback Diode: Adding a flyback diode across the solenoid protects the circuit from voltage spikes when the relay switches.
Status LEDs: LEDs connected to the GPIO pins can visually indicate relay and solenoid activation.
Security Measures: Consider password protection or other security features to control solenoid activation, especially for critical applications.
Putting it all Together:
Assemble the circuit on a breadboard, following the connection guidelines.
Flash the Raspberry Pi OS with your written Python code.
Design and implement the touchscreen interface using your chosen framework.
Test the system thoroughly to ensure proper functionality and safety.
Remember:
Always prioritize safety while working with electronics. Double-check connections and voltage ratings before powering on.
Conclusion
In conclusion, building a solenoid control system using a Raspberry Pi for IoT-based automated screen touch demonstrates a seamless integration of hardware and software to achieve precise and automated touchscreen interactions. The Raspberry Pi’s versatility and ease of programming make it an ideal choice for controlling solenoids and managing relay operations in IoT Solenoid Touch Control systems. This system not only enhances the efficiency and accuracy of automated touch actions but also expands its potential through IoT capabilities, allowing for remote control and monitoring. By leveraging the power of the Internet of Things, the IoT Solenoid Touch Control project opens up new possibilities for automation and control in various applications, from user interface testing to interactive installations.
Click here to read more blogs like this and learn new tricks and techniques of software testing.
As a Software Development Engineer in Test (SDET), I specialize in developing automation scripts for mobile applications with integrated hardware for both Android and iOS devices. In addition to my software expertise, I have designed and implemented PCB layouts and hardware systems for integrating various components such as sensors, relays, Arduino Mega, and Raspberry Pi 4. I programmed the Raspberry Pi 4 and Arduino Mega using C/C++ and Python to control connected devices. I developed communication protocols, including UART, I2C, and SPI, for real-time data transmission and also implemented SSH communication to interface between the hardware and testing framework.
When we hear the word Arduino, the first thing that comes to mind is a microprocessor chip assembled on a single board to help us to create an IOT friendly environment and IOT projects using Arduino communication.
This chip helps us create various projects and electronic devices, and moreover, facilitates physical interaction with the world of technology. Although it’s not only Arduino which is used in IOT Testing, other devices like raspberry pi are also used but Arduino is preferred first due to its cost and ease of handling.
However, Arduino is not just limited to a microprocessor chip. It is also a company that designs, manufactures, and supports electronic hardware and software and help to develop Arduino communication for IOT Application.
Arduino, moreover, makes the interaction between advanced technologies and the physical world easy and fun.
Additionally, Arduino is open-source, allowing anyone to contribute to and expand its capabilities.
Today in this blog we will cover Arduino and its different types of communication.
How Does Arduino communication using for IOT Application:
The main key to creating a project using any microprocessor is, therefore, to have an IoT-enabled environment.
To have an IOT enabled environment using any microprocessor is to be able to communicate or to be able to program and manage it accordingly, so is important in Arduino communication for IOT App.
Arduino communication is classified into two parts: wired and wireless, each with further subdivisions.
1. Wired Communication
Wired communication is, therefore, the most reliable and straightforward way to establish a connection. However, we won’t limit Arduino to simple wired communication. Instead, we’ll expand this wired communication into three distinct categories to develop IOT project/application using Arduino.
These 3 categories are explain below for Arduino Communication for IOT App:
Serial Communication:
UART communication is another name for serial communication. UART stands for universal Asynchronous receiver and transmitter.
It is mostly used for communication between Arduino and computers, but it can be applied in various other ways depending on our requirements and develop IOT application using Arduino. To establish the connection easily, we typically use the ‘Serial library’ in Arduino.
Examples for Serial Communication:
For an example let’s try to have UART communication between 2 Arduino.
Hardware Set-up
Connect the ground pin of both the Arduino.
Connect the RX pin of first Arduino with TX pin of second Arduino and TX pin of first Arduino to second Arduino.
Code Example :
Master Arduino Code:
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bits per second
}
void loop() {
Serial.println("Hello from Master!"); // Send a message
delay(1000); // Wait for a second
}
Slave Arduino Code:
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bits per second
}
void loop() {
if (Serial.available() > 0) { // Check if data is available to read
String message = Serial.readString(); // Read the incoming data
Serial.println("Received: " + message); // Print the received message
}
}
Here we go with a successful Arduino communication using UART
SPI Communication
SPI communication stands for Serial Peripheral Interface, which is usually used for short-distance communication and IOT projects.
The difference between serial communication and SPI communication is that, in contrast, SPI communication is synchronous and uses a clock cycle to communicate. Additionally, SPI is full-duplex communication.
In SPI you will find that there is a master slave relation where SPI has 4 wires to communicate which is MOSI (Master out Slave in) MISO (Master in Slave out) SCL (Serial clock) SS (slave select). Here, the first master sends the signal to all slaves with the identity number; consequently, the slave who has the same identity number reverts back to the master. After hearing back from the slave master, then send data to the particular slave. After the master sends the data, it then sends a clock signal to indicate that the data transfer is complete.
Examples for SPI Communication:
For example, let’s try to have SPI communication between two Arduino boards.
Hardware Set-up
First define the Pins and include SPI.H library in the code
Here let’s consider 10, 11, 12, 13 digital pins SS, MOSI, MISO, SCK on Arduino UNO.
Now let’s initialize the pins in the code:
void setup() {
SPI.begin(115200);
// Set pin modes for SS, MOSI, MISO, and SCK
pinMode(SS, OUTPUT);
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(SCK, OUTPUT);
// Set slave select (SS) pin high to disable the slave device
digitalWrite(SS, HIGH);
}
I2C Communication stands for Inter Integrated Circuit, and it is a half-duplex communication that works on a 2-wire protocol. Additionally, it has an extra overhead with start and stop bits.
I2C has an acknowledgment bit after every byte of transfer. It has a pullup resistor requirement. I2c is slower but comes with clock stretch functionality.
Examples for I2C Communication:
For an example let’s try to have I2C communication between 2 Arduino
Hardware Set-up
I2C pins on the Arduino Uno are SDA (A4) and SCL (A5).
Connect the Ground pin of Both Arduinos.
Connect the SDA pin of Master to the SDA pin of slave.
Connect the SCL pin of Master to the SCL pin of Master.
Master Arduino Code:
#include <Wire.h>
void setup() {
Wire.begin(); // Join I2C bus as master
}
void loop() {
Wire.beginTransmission(8); // Begin transmission to device with address 8
Wire.write("Hello from Master!"); // Send a message
Wire.endTransmission(); // End transmission
delay(1000); // Wait for a second
}
Slave Arduino Code:
#include <Wire.h>
void setup() {
Wire.begin(8); // Join I2C bus with address 8
Wire.onReceive(receiveEvent); // Register a function to be called when data is received
}
void loop() {
// Do nothing, everything is handled in receiveEvent
}
void receiveEvent(int howMany) {
while (Wire.available()) { // Loop through all received bytes
char c = Wire.read(); // Read each byte
Serial.print(c); // Print the received message
}
Serial.println();
}
PFB Image of Connection
2. Wireless Communication
Sometime we want to develop the projects which need to have the flexibility due which we need to have wireless connection. Don’t worry Arduino covered you there too Arduino do have 4 types wireless communication for IOT project using Arduino.
Bluetooth: As the name is very familiar to us, let’s directly move to the components which help us to attain Bluetooth connectivity. By using HC-05 and HC-06 we can attain Bluetooth connectivity using Arduino. However Bluetooth provides connectivity to a short distance.
Wifi: Sometimes we don’t need short distance coverage then we can switch to the wifi or in cases where we want the internet accessibility for some of our projects we can move to wifi connection. You can use the ESP32 and ESP8266 modules for the same purpose.
RF (Radio Frequency): Uses radio waves for medium-distance communication, with modules like nRF24L01 and RF433.
LoRa (Long Range): Great for long-distance, low-power communication, ideal for remote monitoring systems.
Conclusion
In conclusion, Arduino offers a versatile platform for various types of communication, allowing users to create innovative and interactive projects in IOT. Through serial, SPI, and I2C communications, Arduino facilitates reliable and efficient data exchange, each method catering to different needs and scenarios for exploring Arduino communication for IOT App.
Whether you are connecting multiple Arduinos or interfacing with other devices, understanding these communication protocols enhances your ability to leverage Arduino’s full potential in the IOT world.
Deepti Rana is a passionate profession keen to learn new technologies and exceling them with expertise. She thrives to bridge the gap between real time problems and technical world. With a background in IT she has taken steps in robotics too. Her background in IT doesn’t stop her to explore different fields, that can be seen through her projects where see has used GSM, GPRS, ESP32, Arduino, PS2, line sensor, ultrasonic sensors, and fingerprint sensor. She does love to share her knowledge, which she accomplishes by volunteering in Bhumi NGO.