Add Basic Functions in WordPress Plugin
Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to Add Basic Function in WordPress Plugin. In the previous tutorial, we have seen
How to Create a Simple WordPress Plugin, and today we are gonna add some basic functions in it, which are kind of compulsory. You may not find them useful right now but they will come in handy when we will work on complex plugins.
It's the second tutorial in WordPress plugin creation series. If you got into any trouble then ask in comments and I will try my best to resolve them all. So, let's get started with these basic functions and add then in our newly created WordPress plugin:
Add Basic Functions in WordPress Plugin
- As we have already created the class for our wordpress plugin so now its time to add some functions in it.
- The first function we are going to add is the construct function.
- Construct is the default function, which is called by the class on initialization.
- So in simple words, when our plugin will start then construct function will be automatically called.
- Here's our code for the construct function:
/* Main class code starts here */
if ( !class_exists( 'NamePluginTEP' ) )
{
class NamePluginTEP
{
public $pluginName;
function __construct()
{
$this -> pluginName = plugin_basename(__FILE__);
}
}
$namePluginTEP = new NamePluginTEP();
}
/* Main class code ends here */
- We have already seen How to initialize the class NamePluginTEP.
- Inside this class, I have created a new variable named pluginName.
- After that I have added a construct function and this function will be called by default, it's simple object oriented programming.
- Within this construct function, I have used plugin_basename, which will give us the name of our plugin.
- I have saved the name in our variable pluginName.
- We are not gonna use this variable rite now but soon in the coming tutorials.
- The next two functions we are gonna add are Activate and Deactivate.
- These functions will be executed, when you will activate or deactivate your plugin in the WordPress plugin section.
- Here's the code for these two functions:
/* Main class code starts here */
if ( !class_exists( 'NamePluginTEP' ) )
{
class NamePluginTEP
{
public $pluginName;
function __construct(){
$this -> pluginName = plugin_basename(__FILE__);
}
function activate(){
}
function deactivate(){
}
}
$namePluginTEP = new NamePluginTEP();
}
/* Main class code ends here */
register_activation_hook( __File__, array( $namePluginTEP, 'activate') );
register_deactivation_hook( __File__, array( $namePluginTEP, 'deactivate') );
- As you can see in the above code that we have added both of these functions activate and deactivate in our Main Plugin class.
- Now in order to call these functions, we have to use built-in WordPress hooks.
- We have used two hooks, which are:
- register_activation_hook.
- register_deactivation_hook.
- These registration hooks will check the __File__ and then will find the activate/deactivate function in our class.
- Instead of adding all codes in a single PHP file, it's always a better approach to create separate PHP files for each method or routine.
- So, now we are gonna create two more PHP files for Activation and Deactivation and then will call them in our main PHP file.
Creating Activation & Deactivation PHP Files
- Till now, we have just created one Folder named NamePluginTEP and then we have created a php file of the same name, which is actually name of our plugin.
- So, now in this Main Plugin Folder, create a new folder and rename it to inc (short for include).
- In this inc folder, you have to create a two php files, named as:
- Activate.php
- Deactivate.php
- In the Activate.php file, place the below code:
<?php
/*
* @package NamePluginTEP
*/
class Activate
{
public static function activatePlugin()
{
flush_rewrite_rules();
}
}
- In the Deactivate.php file, place the below code:
<?php
/*
* @package NamePluginTEP
*/
class Deactivate
{
public static function deactivatePlugin()
{
flush_rewrite_rules();
}
}
- In both of these files, we have created a new class and then added a public static function.
- We have just used the method flush_rewrite_rules() , which is kind of a refresh and I am not adding any more codes in it.
- Don't worry in coming tutorials, these all are gonna come in handy, rite now we are just building the foundation.
- Now we have to call these functions in our Main PHP File.
- So our main PHP class will be something like that:
<?php
/**
*
* @package NamePluginTEP
*
*/
/*
Plugin Name: NamePluginTEP
Plugin URI: https://www.theengineeringprojects.com/
Author: Syed Zain Nasir
Author URI: https://twitter.com/syedzainnasir
Description: It's our First Simple WordPress Plugin.
Version: 1.0.0
License: GPLv2
*/
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
defined( 'ABSPATH' ) or die( 'We are having an error.' );
/* Main class code starts here */
if ( !class_exists( 'NamePluginTEP' ) )
{
class NamePluginTEP
{
public $pluginName;
function __construct(){
$this -> pluginName = plugin_basename(__FILE__);
}
function activate()
{
require_once plugin_dir_path( __FILE__ ).'inc/Activate.php';
Activate::activatePlugin();
}
function deactivate()
{
require_once plugin_dir_path( __FILE__ ).'inc/Deactivate.php';
Deactivate::deactivatePlugin();
}
}
$namePluginTEP = new NamePluginTEP();
}
/* Main class code ends here */
register_activation_hook( __File__, array( $namePluginTEP, 'activate') );
register_deactivation_hook( __File__, array( $namePluginTEP, 'deactivate') );
- We have just added two lines in both of our activate and deactivate functions.
- This method require_once plugin_dir_path is used to include the Activate.php file for once and we have passed its path.
- In the second line, we have simply called our function Activate::activatePlugin() , static functions can easily be called that way.
- Now activate or deactivate your plugin in WordPress Plugin section but it won't do anything as still we haven't added any remarkable code in it, we are just building the foundation. :P
- But the good thing is it's not crashing or giving any error, that's a good sign. :)
- Here's a screenshot of our WordPress plugin:
- I have activated the plugin but still its not doing anything but it will do something soon. :P
So, that was all for today. I hope you will easily Add these Basic Functions in WordPress Plugin. In the coming tutorial, we are gonna have a look at How to
Enqueue Scripts Files in WordPress Plugin. Till then take care and have fun !!! :)
How to Create a Simple WordPress Plugin
Hello friends, I hope you all are doing great. In today's tutorial, I am gonna show you
How to Create a Simple WordPress Plugin. I am starting this new series on WordPress Plugins and we will cover everything from basics to pro. This WordPress Plugin series is gonna be a long one. As today's our first post, so we are just gonna create a plugin and in later tutorials, we will add different features in it. I will try to cover all the basics but if you got into any trouble then ask in comments and I will try to resolve them out.
I have been working a lot these days on WordPress and have learnt many new things so I thought to share them on my blog. It will be helpful for computer software engineers, as if you have created your own site with WordPress then you must have thought about creating custom WordPress plugins as well. So, let's get started with How to Create a Simple WordPress Plugin:
Note:
- I would recommend you to use xampp and then install WordPress on it and test everything there.
Create a Simple WordPress Plugin
- First of all, what you need to do is, you need to find the wp-config.php file in the root directory of your WordPress installation.
- Open this file and place the below code in it:
define('WP_DEBUG', true);
- It will bring the WordPress in debugging mode and if we got any error while plugin development then we will also get the reason for that error.
- If its already defined and set to False then you need to change it to True.
- Now let's create some files for our first plugin, so open the folder named wp-content in the root WordPress installation.
- In this folder you will find a folder name Plugins, so open it up.
- In Plugins folder, create a new folder and the name of the folder should be the name of your plugin.
- So, I have renamed this new folder to NamePluginTEP as its my plugin name.
- The name of your plugin must have to be unique because if we have the preexisting plugin with the same name then our plugin will not index.
- So make sure your plugin's name must be different.
- Open this folder and now create a new php file with the same name so my file's name will be NamePluginTEP.php.
- For WordPress, it will be the main file of our plugin, it checks the name the file and compares it with name of the folder.
- Now we have to add some code in this php file for basic configuration.
- So place this code in the NamePluginTEP.php file:
<?php
/**
*
* @package NamePluginTEP
*
*/
/*
Plugin Name: NamePluginTEP
Plugin URI: https://www.theengineeringprojects.com/
Author: Syed Zain Nasir
Author URI: https://twitter.com/syedzainnasir
Description: It's our First Simple WordPress Plugin.
Version: 1.0.0
License: GPLv2
*/
?>
- You have to copy and paste the above code as its the defined syntax by WordPress.
- Now save your file and open the plugins page of your WordPress and if everything goes fine then you will get something as shown in below figure:
- You can activate or deactivate this plugin but it's not gonna make any change as its just created and doesn't have any functions in it.
- First of all, we need to secure our plugin so that if someone is accessing our plugin file externally then he can't get it.
- So, we need to add this line just below the copyrights:
defined( 'ABSPATH' ) or die( 'We are having an error.' );
- So, if the user is accessing the file from ABSPATH (absolute path) then its fine otherwise generate an error and exit.
- Now we need to create a new class for our plugin and the name of this class will be the same as our plugin's name:
if ( !class_exists( 'NamePluginTEP' ) )
{
class NamePluginTEP
{
}
$namePluginTEP = new NamePluginTEP();
}
- In the above code, first of all I have placed a check to see if the class already exists. It's a safety precaution.
- If the class doesn't exist, then we have created a new class of the same name.
- After the class, I have simply created a new instance of this class and saved it in a variable starting with small "n" while the class starts with capital "N".
- If you already know php, then it won't be much of an issue for you as it's simple object oriented programming.
- So, now when our plugin is loaded then this class will be initialized.
- Here's the complete php code of our plugin:
<?php
/**
*
* @package NamePluginTEP
*
*/
/*
Plugin Name: NamePluginTEP
Plugin URI: https://www.theengineeringprojects.com/
Author: Syed Zain Nasir
Author URI: https://twitter.com/syedzainnasir
Description: It's our First Simple WordPress Plugin.
Version: 1.0.0
License: GPLv2
*/
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
defined( 'ABSPATH' ) or die( 'We are having an error.' );
if ( !class_exists( 'NamePluginTEP' ) )
{
class NamePluginTEP
{
}
$namePluginTEP = new NamePluginTEP();
}
- Here's our plugin in activate mode and there's no error generated by it:
That was all for today. I hope you can now easily create a simple WordPress plugin. I am not giving any files to download rite now as we have just covered the basics. In the next tutorial, we will have a look at How to
Add Basic Functions in WordPress Plugin. So, will meet you guys in next tutorial. Till then take care and have fun !!! :)
Guide to Writing an Engineering Research Paper
The engineering field is not typically known for its literary style or its compelling prose, in large measure because engineering is better known as an applied field than a theoretical one. Most engineering students expect to spend their time working with mathematical equations and applying these equations to discover engineering solutions rather than researching term papers. But engineering is a discipline with an academic component, and research is an essential element of its academic aspect. In short, if you’re a student in an engineering program, you need to be able to write a great research paper just as much as you need to be able to solve complex mathematical problems.
However, many students in application-based fields like engineering are much more comfortable with numbers than they are with words. Because of this, research papers can be challenging for them. Fortunately, there are a few key steps you can take to make sure your next engineering research paper truly shines.
Guide to Writing an Engineering Research Paper
- Plan your research early: Many students who are less comfortable with research paper writing tend to wait to research as they write, but this creates problems. First, it means that you are wasting time going back and revising each new piece of information rather than starting with a complete understanding of your topic. Second, it also means that you will be scrambling to research as you write, costing you time through inefficiency and redundancy. Instead, the better choice is to start your research process as quickly as possible in order to give yourself time to analyze and digest what you are reading and to develop original ideas about what the research has to say about your topic. Separating the research process from the writing process will help you to develop stronger ideas and prepare for the writing process, making the actual writing of your paper that much faster and more efficient.
- Use only the most current research: While there are some cases where historical articles can be important for understanding the development of an idea, you will want to use current research to support your analysis. Current research keeps you abreast of the latest information in your field. This is especially important because of the changing nature of engineering. New information and new approaches can render older ways of doing things obsolete. You want to ensure that your paper is the strongest it can be, which means that you need to stay current to ensure your paper is on the cutting edge.
- Select data by quality, not by quantity: Many engineering students rightly value numbers and data because this is the raw material used in engineering. However, a research paper is a little different from other types of engineering work. In a research paper, you should focus on high-quality data, not simply the volume of data you can pack into your paper. In a research paper, focusing on the best and most important information is paramount. Extraneous information, redundant data, or irrelevant data don’t make a manuscript stronger, even if they make it longer. They are a distraction and can undercut the power of your main points.
- Discuss the theory, not just the results: Because engineering is an applied discipline, many students minimize or ignore theory in favor of discussing results. While results are important, in a research paper it’s also essential to talk about the methodology and theory used to obtain those results. By explaining the background of a theory and the underpinnings that demonstrate why it is true, you show the reader that you know what you are talking about and have considered the strengths and weaknesses of the approach you have used to obtain your results. It also shows that you have an understanding of the conventions and requirements of academic writing.
- Remember to explain your hypothesis: When you have explained the theories behind your work, you will need to tell the reader what your paper will investigate and what you hope to demonstrate or prove. Outlining the hypothesis is important to make sure that the audience understands why you have chosen to present specific data, and what it all means.
Writing an engineering research paper doesn’t have to be hard! It just takes a little bit of work and a bit of mindfulness about how to employ and deploy research to support and defend your great ideas. Before you know it, you’ll have an excellent engineering research paper! If you still need professional assistance from academic experts in the engineering field, don’t hesitate to address a research paper writing service that will help you immediately with your project.
Rain Sensor Library for Proteus
Hello friends, I hope you all are doing great. In today's tutorial, I am going to share a new
Rain Sensor Library for Proteus. I have got a lot of requests for designing this sensor. So finally it has been designed by our team and is ready to use in your Proteus Simulations.
Rain Sensor, as the name shows, is used for detection of rain and is common sensor used in Embedded Systems Projects. Both analog and digital rain sensors are available these days but we have only designed the digital Rain Sensor. It will give digital output and its output will be HIGH when there's rain and will remain LOW if it won't detect any rain.
As Proteus is a simulation software and we can't actually bring the rain so that's why I have placed a TestPin. If you apply HIGH to this TestPin then that's means there's rain and if TestPin is LOW then it will give LOW output and will show there's no rain. So, now let's have a look at How to download and use this Rain Sensor Library for Proteus:
Rain Sensor Library for Proteus
- First of all, download this Rain Sensor Library for Proteus, by clicking the below button:
Rain Sensor Library for Proteus
- You will get a zip file so extract it and you will find these three Library Files in it:
- RainSensorsTEP.LIB
- RainSensorsTEP.IDX
- RainSensorsTEP.HEX
- Now place these Library files in the Library folder of your Proteus software.
Note:
- Now restart your Proteus software if its already open.
- In the components search box, make a search for rain sensor as shown in below figure:
- I have designed these two rain sensors so now place both of them in your workspace.
- If everything goes fine then you will get something as shown in below figure:
- So now we have to add the hex file in our sensor, so I am gonna use the Rain Sensor Blue and will double click it to open its Properties Panel.
- In the Properties Panel, you have to find the Program File section.
- In the Program File, browse to RainSensorsTEP.HEX File and select it.
- We have download this file and placed it in the Library folder of our Proteus software.
- Here's the screenshot of my Properties Panel of Rain Sensor:
- Now after adding the Hex file, click OK to close the Properties Panel.
- Your rain sensor is now ready to be used in your Proteus Simulation.
- So, let's design a simple circuit to have a look at How this Rain Sensor works in Proteus.
- Here's the screenshot of my simple Rain Sensor simulation in Proteus:
- I have attached LogicState to TestPin and LED on the output.
- As I have explained earlier that we can't bring rain in the Proteus software, that's why I have placed a TestPin.
- So, now when TestPin is LOW that means there's no rain and when you change the TestPin to HIGH then sensor will detect rain.
- I have run my simulation and here's the output:
So that was all for today. If you got into any trouble then ask in comments and I will help you out. Thanks for reading. Take care. :)
Solar Panel Library for Proteus
Hello friends, I hope you all are doing great. In today's tutorial, I am going to share a new
Solar Panel Library for Proteus. I hope you guys are gonna enjoy this Proteus Library as it's not available in
Proteus and we are presenting it for the first time. :) I am quite proud of my team. B|
We all know about Solar Panels which is an excellent renewable energy source. It is widely adopted by the inhabitants of this green planet as its totally free and converts solar energy into electricity. Solar panels are also used a lot in
Engineering Projects especially related to renewable energy sources. Proteus doesn't have solar panels in its database that's why our team has designed this library. Using this
Solar Panel Library for Proteus, now you can easily simulate solar panels in Proteus and can design your projects' simulations. I will also share some projects in which I will interface it with different
Microcontrollers like
Arduino,
PIC Microcontroller or
8051 Microcontroller etc. So, let's get started with How to download and simulate Solar Panel in Proteus:
Solar Panel Library for Proteus
- First of all, download the Solar Panel Library for Proteus by clicking the below button:
Solar Panel Library for Proteus
- You will get a zip file which will have these two library files in it:
- SolarPanelTEP.IDX
- SolarPanelTEP.LIB
- Now place these two files in the library folder of your Proteus software.
Note:
- Now open you Proteus software or restart it if it's already open.
- Proteus is not that smart so we have to restart it so that it would add new Library components in its database.
- In the Proteus software click on the components button and make a search for Solar Panel as shown in below figure:
- Now place this component in your Proteus software.
- If everything goes fine then you will get something as shown in below figure:
- Now double click this solar panel and its Properties panel will open up as shown in below figure:
- If you have worked on Solar Panel then must have the idea that output of solar panel depends on the intensity of sunlight.
- So, if its shiny bright day then solar panel normally give in the range of 15V to 19V.
- Similarly, if its night time then solar panels output ranges from 2V to 6V.
- While on a cloudy day it could vary between 8V to 12V.
- So, if you want to change the output of this Proteus' Solar Panel then you have to open this Properties Panel and then change the Voltage value.
- By default, it will give 12V as an output.
- I am working on adding some button so that you could change the output in running simulation but for now you have to stop the simulation in order to change it.
- Now let's place a voltmeter at the output of this solar panel and check its output.
- Here's the simple solar panel simulation in Proteus:
- Now you can see in above figure that our Solar Panel is giving 12V as an output.
- So, now let's open it's Properties Panel and change the voltage value to 16.5V.
- I have changed the value and here's our output:
- You can see in the above figure that now voltage has changed to 16.5V.
- Here's a video demonstration on How to download and install this Solar Panel Library for Proteus.
So, that was all about Solar Panel Library for Proteus. I hope you guys can now easily download and install it. If you still got in to any trouble then ask in comments and I will try my best to resolve them and also let me know about your feedback for this Library. Thanks for reading. Have a good day. :)
Infrared Sensor Library for Proteus
Hello friends, I hope you all are doing great. In today's tutorial, I am going to share a new
Infrared Sensor Library for Proteus. This IR sensor is not available in
Proteus and we are sharing this library for the first time. I hope it will help in your
Embedded Systems Projects particularly related to robotics and automation. So, if you want to work on this IR Sensor then I would suggest you to first design its simulation and then try your luck with hardware.
There are different types of Infrared Sensors & modules available in the market. Some of these modules have transmitter & receiver on separate chips and are mostly get activated when someone interrupts the light. The one we have designed has a transmitter & receiver on a single chip. The IR signal transmits from the IR transmitter and if it has some obstacle in front of it then it bounces back and received by the IR receiver. You should also have a look at this list of
New Proteus Libraries for Engineering Students. So, let's have a look at How to use this Infrared Sensor Library for Proteus:
Note:
- You should also have a look at:
Where To Buy? |
---|
No. | Components | Distributor | Link To Buy |
1 | Arduino Uno | Amazon | Buy Now |
Infrared Sensor Library for Proteus
- First of all, download the Library files of this IR Sensor by clicking the below button:
Infrared Sensor Library for Proteus
- After downloading this file extract it and you will find three Library files in it, named as:
- InfraredSensorsTEP.IDX
- InfraredSensorsTEP.LIB
- InfraredSensorsTEP.HEX
- Place all these three files in the Library folder of your Proteus software.
Note:
- Once you have added the files in the Library folder, then restart your Proteus software.
- In the components section, make a search for Infrared Sensor, as shown in below figure:
- Now place this IR Obstacle Sensor in your Proteus and if everything goes fine then you will get something as shown in below figure:
- As you can see in above figure that we have four pins on our Infrared sensor, which are:
- Vcc => You need to provide +5V to this pin.
- GND => It should be grounded.
- OUT => That's output pin and it will get HIGH when this sensor will find some obstacle in front and will remain LOW in normal condition.
- TestPin => As Proteus is a simulation software so we can't actually place something in front of this sensor. That's why I have used this TestPin. If this Pin is LOW, then sensor will remain normal and if it's HIGH then sensor will behave as it has something in front of it.
- Now double click this Infrared Sensor and its Properties Panel will open up.
- In the Program File section, browse to the file InfraredSensorTEP.HEX which you have already downloaded and placed in the Library folder of Proteus.
- Here's the screenshot of Properties Panel for this Infrared Sensor:
- I have encircled the Program File in above figure and you can see I have selected the InfraredSensorsTEP.HEX.
- So, now let's design a simple circuit and have a look at how to use this Infrared Sensor in Proteus.
- Here's the screenshot of Infrared Sensor Simulation in Proteus:
- So, now let's run our Proteus simulation and if everything goes fine then you will get results, as shown in the below figure:
- I will interface this sensor with different Microcontrollers e.g. Arduino, PIC Microcontroller etc. in my coming tutorial.
- As you can see in the above figure that when TestPin is LOW then OUT Pin is also LOW means there's no obstacle and when TestPin gets 1 then OUT Pin will go HIGH and that means we have some obstacle.
So, that's all for Infrared Sensor Library for Proteus. I hope it will help you guys in your engineering projects. Let me know if you have any suggestions. Take care & have fun !!! :)
Introduction to Arduino Uno
Hi Friends! Hope you are doing great. Today, I am going to give you a detailed Introduction to Arduino Uno. It is a microcontroller board developed by Arduino.cc and is based on Atmega328 Microcontroller. The first Arduino project was started in Interaction Design Institute Ivrea in 2003 by David Cuartielles and Massimo Banzi with the intention of providing a cheap and flexible way for students and professionals to learn embedded programming.
Arduino UNO is a very valuable addition in electronics that consists of a USB interface, 14 digital I/O pins(of which 6 Pins are used for PWM), 6 analog pins and an Atmega328 microcontroller. It also supports 3 communication protocols named Serial, I2C and SPI protocol. You should also have a look at this video presentation on Arduino UNO:
- Few main features of Arduino UNO are shown in the below figure:
Arduino UNO Features and Technical Specs |
No. |
Parameter Name |
Parameter Value |
1 |
Microcontroller |
Atmega328 |
2 |
Crystal Oscillator |
16MHz |
3 |
Operating Voltage |
5V |
4 |
Input Voltage |
5-12V |
5 |
Digital I/O Pins |
14 (D0 to D13) |
6 |
Analog I/O Pins |
6 (A0 to A5) |
7 |
PWM Pins |
6 (Pin # 3, 5, 6, 9, 10 and 11) |
8 |
Power Pins |
5V, 3.3V, Vin, GND |
9 |
Communication |
UART(1), SPI(1), I2C(1) |
10 |
Flash Memory |
32 KB (0.5KB is used by bootloader) |
11 |
SRAM |
2 KB |
12 |
EEPROM |
1 KB |
13 |
ICSP Header |
Yes |
14 |
Power sources |
DC Power Jack & USB Port |
I'll try to cover each and everything related to Arduino Uno, so you get a clear idea of what it does, its main features, working and everything you need to know. Let's get started.
Where To Buy? |
---|
No. | Components | Distributor | Link To Buy |
1 | Arduino Uno | Amazon | Buy Now |
Introduction to Arduino Uno
- Arduino Uno is a microcontroller board, developed by Arduino.cc, based on the Atmega328 microcontroller and is marked as the first Arduino board developed(UNO means "one" in Italian).
- The software used for writing, compiling & uploading code to Arduino boards is called Arduino IDE (Integrated Development Environment), which is free to download from Arduino Official Site.
- It has an operating voltage of 5V while the input voltage may vary from 7V to 12V.
- Arduino UNO has a maximum current rating of 40mA, so the load shouldn't exceed this current rating or you may harm the board.
- It comes with a crystal oscillator of 16MHz, which is its operating frequency.
- Arduino Uno Pinout consists of 14 digital pins starting from D0 to D13.
- It also has 6 analog pins starting from A0 to A5.
- It also has 1 Reset Pin, which is used to reset the board programmatically. In order to reset the board, we need to make this pin LOW.
- It also has 6 Power Pins, which provide different voltage levels.
- Out of 14 digital pins, 6 pins are used for generating PWM pulses of 8-Bit resolution. PWM pins in Arduino UNO are D3, D5, D6, D9, D10 and D11.
- Arduino UNO comes with 3 types of memories associated with it, named:
- Flash Memory: 32KB
- SRAM: 2KB
- EEPROM: 1KB
- Arduino UNO supports 3 types of communication protocols, used for interfacing with third-party peripherals, named:
- Serial Protocol
- I2C Protocol
- SPI Protocol
- You can download the Arduino UNO datasheet by clicking the below button:
Download Arduino UNO Datasheet
- Apart from USB, a battery or AC to DC adopter can also be used to power the board.
Features of Arduino Uno Board
- Arduino Uno comes with a USB interface i.e. USB port is added on the board to develop serial communication with the computer.
- Atmega328 microcontroller is placed on the board that comes with a number of features like timers, counters, interrupts, PWM, CPU, I/O pins and based on a 16MHz clock that helps in producing more frequency and number of instructions per cycle.
- It is an open-source platform where anyone can modify and optimize the board based on the number of instructions and tasks they want to achieve.
- This board comes with a built-in regulation feature that keeps the voltage under control when the device is connected to the external device.
- A reset pin is present in the board that resets the whole board and takes the running program in the initial stage. This pin is useful when the board hangs up in the middle of the running program; pushing this pin will clear everything up in the program and starts the program right from the beginning.
- There are 14 I/O digital and 6 analog pins incorporated in the board that allows the external connection with any circuit with the board. These pins provide flexibility and ease of use to the external devices that can be connected through these pins. There is no hard and fast interface required to connect the devices to the board. Simply plug the external device into the pins of the board that are laid out on the board in the form of the header.
- The 6 analog pins are marked as A0 to A5 and come with a resolution of 10bits. These pins measure from 0 to 5V, however, they can be configured to the high range using analogReference() function and AREF pin.
- Only 5 V is required to turn the board on, which can be achieved directly using a USB port or external adopter, however, it can support an external power source up to 12 V which can be regulated and limit to 5 V or 3.3 V based on the requirement of the project.
Arduino Uno Pinout
Arduino Uno is based on an AVR microcontroller called Atmega328. This controller comes with 2KB SRAM, 32KB of flash memory, 1KB of EEPROM. Arduino Board comes with 14 digital pins and 6 analog pins. ON-chip ADC is used to sample these pins. A 16 MHz frequency crystal oscillator is equipped on the board. The following figure shows the pinout of the Arduino Uno Board.
Arduino UNO Pin Description
There are several I/O digital and analog pins placed on the board which operates at 5V. These pins come with standard operating ratings ranging between 20mA to 40mA. Internal pull-up resistors are used in the board that limits the current exceeding the given operating conditions. However, too much increase in current makes these resisters useless and damages the device.
- LED. Arduino Uno comes with a built-in LED which is connected through pin 13. Providing HIGH value to the pin will turn it ON and LOW will turn it OFF.
- Vin. It is the input voltage provided to the Arduino Board. It is different than 5 V supplied through a USB port. This pin is used to supply voltage. If a voltage is provided through a power jack, it can be accessed through this pin.
- 5V. This board comes with the ability to provide voltage regulation. 5V pin is used to provide output regulated voltage. The board is powered up using three ways i.e. USB, Vin pin of the board or DC power jack.
- USB supports voltage around 5V while Vin and Power Jack support a voltage ranges between 7V to 20V. It is recommended to operate the board on 5V. It is important to note that, if a voltage is supplied through 5V or 3.3V pins, they result in bypassing the voltage regulator that can damage the board if the voltage surpasses its limit.
- GND. These are ground pins. More than one ground pins are provided on the board which can be used as per requirement.
- Reset. This pin is incorporated on the board which resets the program running on the board. Instead of physical reset on the board, IDE comes with a feature of resetting the board through programming.
- IOREF. This pin is very useful for providing voltage reference to the board. A shield is used to read the voltage across this pin which then selects the proper power source.
- PWM. PWM is provided by 3,5,6,9,10, 11pins. These pins are configured to provided 8-bit output PWM.
- SPI. It is known as Serial Peripheral Interface. Four pins 10(SS), 11(MOSI), 12(MISO), 13(SCK) provide SPI communication with the help of the SPI library.
- AREF. It is called Analog Reference. This pin is used for providing a reference voltage to the analog inputs.
- TWI. It is called Two-wire Interface. TWI communication is accessed through Wire Library. A4 and A5 pins are used for this purpose.
- Serial Communication. Serial communication is carried out through two pins called Pin 0 (Rx) and Pin 1 (Tx).
- Rx pin is used to receive data while Tx pin is used to transmit data.
- External Interrupts. Pin 2 and 3 are used for providing external interrupts. An interrupt is called by providing LOW or changing value.
Communication and Programming
Arduino Uno comes with the ability of interfacing with other Arduino boards, microcontrollers and computers. The Atmega328 placed on the board provides serial communication using pins like Rx and Tx.
The Atmega16U2 incorporated on the board provides a pathway for serial communication using USB com drivers. A serial monitor is provided on the IDE software which is used to send or receive text data from the board. If LEDs placed on the Rx and Tx pins will flash, they indicate the transmission of data.
Arduino Uno is programmed using Arduino Software which is a cross-platform application called IDE written in Java. The AVR microcontroller Atmega328 laid out on the base comes with built-in bootloader that sets you free from using a separate burner to upload the program on the board.
Applications of Arduino UNO
Arduino Uno comes with a wide range of applications. A larger number of people are using Arduino boards for developing sensors and instruments that are used in scientific research. Following are some main applications of the board.
- Embedded System
- Security and Defense System
- Digital Electronics and Robotics
- Parking Lot Counter
- Weighing Machines
- Traffic Light Count Down Timer
- Medical Instrument
- Emergency Light for Railways
- Home Automation
- Industrial Automation
There are a lot of other microcontrollers available in the market that are more powerful and cheap as compared to the Arduino board. So, why you prefer Arduino Uno?
Actually, Arduino comes with a big community that is developing and sharing knowledge with a wide range of audiences. Quick support is available pertaining to the technical aspects of any electronic project. When you decide Arduino board over other controllers, you don't need to arrange extra peripherals and devices as most of the functions are readily available on the board that makes your project economical in nature and free from a lot of technical expertise.
That's all for today. I hope you have got a lot of information regarding the Arduino Uno board. However, if you are unsure or have any questions you can approach me in the comment section below. I'd love to help you according to the best of my knowledge. Keep your feedback and suggestions coming; they help us provide you quality work that resonates with your needs and requirements. Thanks for reading the article.
Smoke Detector with Arduino & MQ2 Sensor
Hello everyone, I hope you all are doing great. In today's tutorial, we are gonna have a look at How to design a
Smoke Detector with Arduino. Its quite a simple project but if you are working on any security project then you must add this feature in it. You should also download this
Gas Sensor Library for Proteus, and design its simulation.
I will use gas sensor MQ2 for this project. I have purchased MQ2 Gas Sensor module as its quite easy to interface with Arduino. Arduino board I'm using is Arduino UNO. I have also designed an
LPG Gas Leak Detect using Arduino using this MQ2 Sensor. So, let's get started with How to design Smoke Detector with Arduino & MQ2 Sensor.
Smoke Detector with Arduino & MQ2 Sensor
- First of all, we need to connect some jumper wires between Arduino and MQ2 smoke sensor shield.
- Here's the image of our Gas sensor and you can see, it has four pins in total.
- This gas sensor has four pins in total, which are:
- Vcc: We need to provide +5V.
- GND: We need to ground it.
- D0: Digital Output.
- A0: Analog Output.
- So now you will need four male to female jumper wires and connect them as shown in below figure:
- Sensor's pins are labelled on the back side and I have connected these four pins as follows:
- White Wire: Vcc of Sensor connected with +5V of Arduino.
- Black Wire: GND of Sensor connected with GND of Arduino.
- Grey Wire: D0 of Sensor connected with Pin # 8 of Arduino.
- Orange Wire: A0 of Sensor connected with A0 of Arduino.
- So, now let's design our code in Arduino software in which we will detect whether there's smoke around or not.
- I'm gonna use the analog output of our sensor and will first display the analog value in my Serial Monitor.
- I have used the below code, so copy it and upload in your Arduino board:
int Input = A0;
int SensorVal = 0;
void setup() {
Serial.begin(9600);
pinMode(Input, INPUT);
Serial.println("Interfacing of Smoke Sensor with Arduino");
Serial. println("Design by www.TheEngineeringProjects.com");
Serial.println();
}
void loop() {
SensorVal = analogRead(Input);
Serial.println(SensorVal);
delay(500);
}
- Now open the Serial Monitor of Arduino to check the analog values coming from our sensor.
- If everything goes fine then you will get something like this in your Serial Monitor:
- You can see we are getting the values in range of 420 to 450.
- You should read How to do Arduino Serial Communication, if you don't know how to get data serially.
- Now let's place a burning cigarette near it for smoke. (Cigarettes are injurious to health :P )
- When the sensor will sense smoke in its surroundings then its value will start to increase and in my case it reached to around 650.
- So, let's place a check in our Arduino coding to detect whether there's smoke or not.
- So add below code in your Arduino software and upload it to your Arduino board.
int Input = A0;
int SensorVal = 0;
int Check = 0;
void setup() {
Serial.begin(9600);
pinMode(Input, INPUT);
Serial.println("Interfacing of Smoke Sensor with Arduino");
Serial. println("Design by www.TheEngineeringProjects.com");
Serial.println();
}
void loop() {
SensorVal = analogRead(Input);
if((SensorVal > 500) && (Check == 1))
{
Serial.println("Smoke Detected . . .");
Check = 0;
}
if((SensorVal < 500) && (Check == 0))
{
Serial.println("All Clear . . .");
Check = 1;
}
//Serial.println(SensorVal);
delay(500);
}
- After uploading the code to Arduino, open your Serial Monitor.
- If everything goes fine then you will get something as shown in below figure:
- Now let me bring the cigarette close to get some smoke. (Cigarettes are injurious to health :P )
- You will get the warning as soon as it will detect smoke as shown in below figure:
- We got the detection of smoke in our Serial Terminal.
So, that's how we can easily design a Smoke Detector with Arduino & MQ2 Sensor. I think now you can quite easily design this smoke detector project at home. I hope you will enjoy it. Will meet you guys in next tutorial. Till then take care and have fun !!! :)
5 Tips for Extending Your SCADA System
Hello everyone, I hope you all are doing great. In today's tutorial, I am going to share 5 Tips for Extending Your SCADA System. What do you do if your existing SCADA system isn’t doing the job you need? Obviously, you need to extend it, but doing so can be a frustrating and costly exercise. How do you manage budget, increase efficiency and provide the functionality you need? Of course, it all depends on your specific implementation, but some general tips to keep in mind might relieve some stress.
Look at The Big Picture Again
When you find your SCADA system can’t provide the data or control you need, the first instinct is to quickly patch the missing functions, but over the long haul this can be a costly and inefficient process leading to a tangled web of sensors, RTUs and controls. Take the time to analyze your entire system. If there are flaws or limitations in one area, there may be more in another related area. Step back and look at the whole system and what needs you have. It’s likely you can find several areas that need work and hit them all at once instead of doing multiple projects.
Plan for The Future
There’s two main reasons you will need to extend your SCADA system: something was missed or the system has grown. When you look at your latest extension try to forecast what needs you will have later on. Will your RTUs need to be moved from dedicated communication lines to LAN connections? If so, spending a little extra to get RTUs that handle both and can be switched over once the LAN is in place will head off complete replacements later.
Do you need more RTUs or can you handle the sensors through existing ones? What about when the system grows, will that force you to replace the RTUs so you can handle more sensors? Think through your future expansion and make sure you aren’t setting yourself up for another major upgrade in just a few years.
Remember Your Data
Is your data all handled inside the SCADA system? Can you do external data analysis on historical data? If not, you probably need to
extend your existing SCADA system to push data to external databases or data warehouses. It might even be necessary to interface with applications outside the system, or ones you develop internally for some customized part of your business.
Consider connections to the internet and cloud services, as well as security measures that protect the sensor and control loops from unauthorized access. Your data may be fine if it is available through some external application, but management of your system should be tightly controlled and monitored.
Hear Your Alarms
With the steadily increasing availability personal communication devices, smartphones, tablets, laptops and more, it becomes easier to contact people with alerts rather than having them at the control center. Assess your current alerting systems and make sure they meet your current and future needs. It may be necessary to add more communication software or hardware in order to reliably contact on-call personnel when needed.
While it is a great cost savings to not need to staff a control center 24/7, it’s not acceptable to miss an important alert because a phone battery is dead or the volume is set to mute. Make sure your alerting system takes this into account.
Control Your Controls
While it is a good idea to look to the future and to assess the entire system when you upgrade, it’s also wise not to go overboard. A simple metric for things like controls and sensors is to ask “under what circumstances will I use this?” Collecting information that does not influence what actions you take is not very valuable. Installing controls that perform actions which you would not do no matter what data came in from the sensors is also not useful.
Be sure you reign in your additions to the system and only add controls that will be used and sensors that gather actionable information. Adding more noise to your system with redundant or superfluous information can cause information overload. Your users may not know what information is important and what actions to take. Your actual monitoring needs are probably quite extensive, don’t increase them unnecessarily.
Conclusion
Your needs for an extension on your SCADA system may seem very urgent, but don’t be stampeded into an unwise, unneeded, or unhelpful change. Always take the time to think about your change and its impact. Rushing into changes on a complex system can result in a whole series of changes as you find the problems you missed in the original planning.
Remember the adage, if you don’t have the time to do it right, where will you find the time to do it over? And another, failing to plan is planning to fail. Always take the necessary time to plan. It’s an investment in your future.
Was this article helpful and informative? Leave us a comment with your thoughts in the section below.
How to Control DC Motor with Raspberry Pi 3
Hello friends, I hope you all are doing great. In today's tutorial, I am going to show you How to Control DC Motor with Raspberry Pi 3. We will control both the speed and direction of DC Motor. I hope you have read the previous tutorial on How to Create a GUI in Raspberry Pi 3 as we are gonna create a small GUI in this tutorial as well and then we are gonna control our DC Motor with Buttons on GUI.
In order to control the DC Motor, we have to use some drivers in between our Microcontroller and DC Motor. This driver's functionality is to control a 12V DC Motor with a 5V signal from a microcontroller. In today's tutorial, we are gonna use L298 Motor Driver. So, let's get started with How to Control DC Motor with Raspberry Pi 3:
How to Control DC Motor with Raspberry Pi 3
- I have divided this tutorial into four parts, which are:
- Designing of 5V Power Supply.
- L298 Motor Driver Circuit Designing.
- Direction Control of Dc Motor with Raspberry Pi 3.
- Speed Control of DC Motor with Raspberry Pi 3.
- You can download this python File for Controlling of DC Motor with Raspberry Pi 3, by clicking the below button:
Download Python File
- So, let's first design our 5V Power Supply:
1. Designing of 5V Power Supply
- First of all, we need to design a power supply using Voltage Regulator 7805, which will step down our voltage from 12V to 5V.
- We need 12V for our DC Motor and 5V is also required for L298 Motor Driver.
- I am using a 12V adapter so I need to step down this voltage to 5V.
- You can use 5V from Raspberry Pi as well if you don't wanna design this power supply, although it's quite simple.
- For example, if you are designing some robot then you can't place your Laptop on it. In such cases we need to design 5V power supply for our Pi.
- Here's the list of components that are going to be used for this power supply:
- 7805.
- 100uF Capacitor.
- 1000uF Capacitor.
- 1k ohm Resistance.
- 2 Pin Socket.
- Male Header Pins.
- You can see in above figure that we have used 12V Battery and then used 7805 to get 5V at the output.
- Here's the real circuit which I have designed on wero board:
- So, now we have all three voltage levels, which are:
- 12V: White wire.
- 5V: Gray Wire.
- GND ( 0V ): Red Wire.
- The next thing we need to do is, we need to design the Motor driver circuit using L298 Motor Driver:
L298 Motor Driver Circuit
- L298 is an excellent motor driver, you can control two DC Motors with one L298 driver.
- I have used L298 Motor Driver Shield, you can read more about this shield on L298 Motor Driver Library for Proteus.
- Here's the circuit, which I have designed for controlling my DC Motor with Raspberry Pi 3:
- You can quite easily design this circuit as you just need to connect simple jumper wires.
- Here's my real setup with L298 Motor Driver & Raspberry Pi 3:
- So, now we are done with our connections and you can see in above figures that we are using these three pins of Raspberry Pi 3:
- Pin # 12: Connected to Enable A.
- Pin # 16: Connected to Input 1.
- Pin # 18: Connected to Input 2.
- The fourth wire is GND, you have to connect the GND of Raspberry Pi 3 with your power supply GND.
- +12V & 5V are provided to the L298 motor driver from our power supply.
- Now let's design our code in python, first, we will control the direction of DC Motor and after that, we will control its speed.
Direction Control of DC Motor with Raspberry Pi 3
- First of all, I am gonna place three Buttons on my GUI and then I will control the direction of my DC Motor with these buttons.
- I have already explained the code in bits in my previous tutorial LEd Blinking with Raspberry Pi 3, so I will not explain it all again but will only cover the new code.
- So, here's our first part of code, where I have done the basic configuration of our pins and GUI:
# ************************************************************************** #
# **** **** #
# *********** Code Designed by www.TheEngineeringProjects.com ************** #
# **** **** #
# ************** How to Control DC Motor in Raspberry Pi 3 ***************** #
# **** **** #
# ************************************************************************** #
# Importing Libraries
import RPi.GPIO as GPIO
import time
from tkinter import *
import tkinter.font
# Libraries Imported successfully
# Raspberry Pi 3 Pin Settings
PWMPin = 12 # PWM Pin connected to ENA.
Motor1 = 16 # Connected to Input 1.
Motor2 = 18 # Connected to Input 2.
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) # We are accessing GPIOs according to their physical location
GPIO.setup(PWMPin, GPIO.OUT) # We have set our pin mode to output
GPIO.setup(Motor1, GPIO.OUT)
GPIO.setup(Motor2, GPIO.OUT)
GPIO.output(PWMPin, GPIO.LOW) # When it will start then all Pins will be LOW.
GPIO.output(Motor1, GPIO.LOW)
GPIO.output(Motor2, GPIO.LOW)
PwmValue = GPIO.PWM(PWMPin, 2000) # We have set our PWM frequency to 2000.
PwmValue.start(100) # That's the maximum value 100 %.
# Raspberry Pi 3 Pin Settings Completed
# tkinter GUI basic settings
Gui = Tk()
Gui.title("DC Motor Control with Pi 3")
Gui.config(background= "#0080FF")
Gui.minsize(800,300)
Font1 = tkinter.font.Font(family = 'Helvetica', size = 18, weight = 'bold')
# tkinter simple GUI created
- The above code is quite easy to understand, you have seen that I have made the PWM value to maximum as I don't want to change the speed, I just want to control its directions.
- So, now let's add the buttons and Labels on our GUI, here's the code:
Text1 = Label(Gui,text='Motor Status:', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 50, pady = 50)
Text1.grid(row=0,column=0)
Text2 = Label(Gui,text='Stop', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 0)
Text2.grid(row=0,column=1)
Text1 = Label(Gui,text=' ', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 150, pady = 50)
Text1.grid(row=0,column=2)
Button1 = Button(Gui, text='Clockwise', font = Font1, command = MotorClockwise, bg='bisque2', height = 1, width = 10)
Button1.grid(row=1,column=0)
Button2 = Button(Gui, text=' Motor Stop', font = Font1, command = MotorStop, bg='bisque2', height = 1, width = 10)
Button2.grid(row=1,column=1)
Button2 = Button(Gui, text='AntiClockwise', font = Font1, command = MotorAntiClockwise, bg='bisque2', padx = 50, height = 1, width = 10)
Button2.grid(row=1,column=2)
Text3 = Label(Gui,text='www.TheEngineeringProjects.com', font = Font1, bg = '#0080FF', fg='#FFFFFF', padx = 50, pady = 50)
Text3.grid(row=2,columnspan=2)
Gui.mainloop()
- I have used three Texts in first row, the third text is just used for padding. It's easy that way. :P
- I have placed three buttons in the second row and in the last row we have our site's link.
- Here's the screenshot of this GUI:
- Now, finally, we need to add the functions for these buttons.
- Here's the code for these functions and we need to place that code above our GUI code.
def MotorClockwise():
GPIO.output(Motor1, GPIO.LOW) # Motor will move in clockwise direction.
GPIO.output(Motor2, GPIO.HIGH)
def MotorAntiClockwise():
GPIO.output(Motor1, GPIO.HIGH) # Motor will move in anti-clockwise direction.
GPIO.output(Motor2, GPIO.LOW)
def MotorStop():
GPIO.output(Motor1, GPIO.LOW) # Motor will stop.
GPIO.output(Motor2, GPIO.LOW)
- We have three functions here and simply by toggling the pins of our DC Motor, I have changed it direction.
- In order to stop the DC Motor, I have simply made both the pins LOW.
- Now run your code and if everything goes fine then you will motor will follow your command.
- Here's the screenshot of my system in running form:
- Here's our complete code for DC Motor Direction Control with Raspberry Pi 3, in one piece. :P
# ************************************************************************** #
# **** **** #
# *********** Code Designed by www.TheEngineeringProjects.com ************** #
# **** **** #
# ************** How to Control DC Motor in Raspberry Pi 3 ***************** #
# **** **** #
# ************************************************************************** #
# Importing Libraries
import RPi.GPIO as GPIO
import time
from tkinter import *
import tkinter.font
# Libraries Imported successfully
# Raspberry Pi 3 Pin Settings
PWMPin = 12 # PWM Pin connected to ENA.
Motor1 = 16 # Connected to Input 1.
Motor2 = 18 # Connected to Input 2.
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) # We are accessing GPIOs according to their physical location
GPIO.setup(PWMPin, GPIO.OUT) # We have set our pin mode to output
GPIO.setup(Motor1, GPIO.OUT)
GPIO.setup(Motor2, GPIO.OUT)
GPIO.output(PWMPin, GPIO.LOW) # When it will start then all Pins will be LOW.
GPIO.output(Motor1, GPIO.LOW)
GPIO.output(Motor2, GPIO.LOW)
PwmValue = GPIO.PWM(PWMPin, 2000) # We have set our PWM frequency to 2000.
PwmValue.start(100) # That's the maximum value 100 %.
# Raspberry Pi 3 Pin Settings Completed
# tkinter GUI basic settings
Gui = Tk()
Gui.title("DC Motor Control with Pi 3")
Gui.config(background= "#0080FF")
Gui.minsize(800,300)
Font1 = tkinter.font.Font(family = 'Helvetica', size = 18, weight = 'bold')
# tkinter simple GUI created
def MotorClockwise():
GPIO.output(Motor1, GPIO.LOW) # Motor will move in clockwise direction.
GPIO.output(Motor2, GPIO.HIGH)
def MotorAntiClockwise():
GPIO.output(Motor1, GPIO.HIGH) # Motor will move in anti-clockwise direction.
GPIO.output(Motor2, GPIO.LOW)
def MotorStop():
GPIO.output(Motor1, GPIO.LOW) # Motor will stop.
GPIO.output(Motor2, GPIO.LOW)
Text1 = Label(Gui,text='Motor Status:', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 50, pady = 50)
Text1.grid(row=0,column=0)
Text2 = Label(Gui,text='Stop', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 0)
Text2.grid(row=0,column=1)
Text1 = Label(Gui,text=' ', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 150, pady = 50)
Text1.grid(row=0,column=2)
Button1 = Button(Gui, text='Clockwise', font = Font1, command = MotorClockwise, bg='bisque2', height = 1, width = 10)
Button1.grid(row=1,column=0)
Button2 = Button(Gui, text=' Motor Stop', font = Font1, command = MotorStop, bg='bisque2', height = 1, width = 10)
Button2.grid(row=1,column=1)
Button2 = Button(Gui, text='AntiClockwise', font = Font1, command = MotorAntiClockwise, bg='bisque2', padx = 50, height = 1, width = 10)
Button2.grid(row=1,column=2)
Text3 = Label(Gui,text='www.TheEngineeringProjects.com', font = Font1, bg = '#0080FF', fg='#FFFFFF', padx = 50, pady = 50)
Text3.grid(row=2,columnspan=3)
Gui.mainloop()
- Now let's have a look at How to Control the Speed of our DC Motor with Raspberry Pi 3.
DC Motor Speed Control with Raspberry Pi 3
- I'm gonna add a slider in our GUI and with the help of this slider we are gonna change the value of PWM which in turn will change the speed our DC Motor.
- Here's the code for the slider which you need to place below our last Text.
Scale1 = Scale(Gui, from_=0, to=100, orient = HORIZONTAL, resolution = 1, command = ChangePWM)
Scale1.grid(row=2,column=2)
- Now run your GUI and you will get something as shown in below figure:
- Here's the code for the function which will execute when we change the slider value.
def ChangePWM(self):
PwmValue.ChangeDutyCycle(Scale1.get())
- Now when you will run your simulation and change the value of this slider you will feel a clear change in your DC Motor speed.
- I will also create a video which will give you better understanding of this project.
- Here's our final combined code which will control both speed & direction of our DC Motor.
# ************************************************************************** #
# **** **** #
# *********** Code Designed by www.TheEngineeringProjects.com ************** #
# **** **** #
# ************** How to Control DC Motor in Raspberry Pi 3 ***************** #
# **** **** #
# ************************************************************************** #
# Importing Libraries
import RPi.GPIO as GPIO
import time
from tkinter import *
import tkinter.font
# Libraries Imported successfully
# Raspberry Pi 3 Pin Settings
PWMPin = 12 # PWM Pin connected to ENA.
Motor1 = 16 # Connected to Input 1.
Motor2 = 18 # Connected to Input 2.
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) # We are accessing GPIOs according to their physical location
GPIO.setup(PWMPin, GPIO.OUT) # We have set our pin mode to output
GPIO.setup(Motor1, GPIO.OUT)
GPIO.setup(Motor2, GPIO.OUT)
GPIO.output(PWMPin, GPIO.LOW) # When it will start then all Pins will be LOW.
GPIO.output(Motor1, GPIO.LOW)
GPIO.output(Motor2, GPIO.LOW)
PwmValue = GPIO.PWM(PWMPin, 2000) # We have set our PWM frequency to 2000.
PwmValue.start(100) # That's the maximum value 100 %.
# Raspberry Pi 3 Pin Settings Completed
# tkinter GUI basic settings
Gui = Tk()
Gui.title("DC Motor Control with Pi 3")
Gui.config(background= "#0080FF")
Gui.minsize(800,300)
Font1 = tkinter.font.Font(family = 'Helvetica', size = 18, weight = 'bold')
# tkinter simple GUI created
def MotorClockwise():
GPIO.output(Motor1, GPIO.LOW) # Motor will move in clockwise direction.
GPIO.output(Motor2, GPIO.HIGH)
def MotorAntiClockwise():
GPIO.output(Motor1, GPIO.HIGH) # Motor will move in anti-clockwise direction.
GPIO.output(Motor2, GPIO.LOW)
def MotorStop():
GPIO.output(Motor1, GPIO.LOW) # Motor will stop.
GPIO.output(Motor2, GPIO.LOW)
def ChangePWM(self):
PwmValue.ChangeDutyCycle(Scale1.get())
Text1 = Label(Gui,text='Motor Status:', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 50, pady = 50)
Text1.grid(row=0,column=0)
Text2 = Label(Gui,text='Stop', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 0)
Text2.grid(row=0,column=1)
Text1 = Label(Gui,text=' ', font = Font1, fg='#FFFFFF', bg = '#0080FF', padx = 150, pady = 50)
Text1.grid(row=0,column=2)
Button1 = Button(Gui, text='Clockwise', font = Font1, command = MotorClockwise, bg='bisque2', height = 1, width = 10)
Button1.grid(row=1,column=0)
Button2 = Button(Gui, text=' Motor Stop', font = Font1, command = MotorStop, bg='bisque2', height = 1, width = 10)
Button2.grid(row=1,column=1)
Button2 = Button(Gui, text='AntiClockwise', font = Font1, command = MotorAntiClockwise, bg='bisque2', padx = 50, height = 1, width = 10)
Button2.grid(row=1,column=2)
Text3 = Label(Gui,text='www.TheEngineeringProjects.com', font = Font1, bg = '#0080FF', fg='#FFFFFF', padx = 50, pady = 50)
Text3.grid(row=2,columnspan=2)
Scale1 = Scale(Gui, from_=0, to=100, orient = HORIZONTAL, resolution = 1, command = ChangePWM)
Scale1.grid(row=2,column=2)
Gui.mainloop()
So, that was all for today. I hope you have enjoyed today's tutorial. Let me know if you have any questions. Have a good day. :)