You are reading the article How To Use Pushbuttons With Raspberry Pi Gpio Pins updated in December 2023 on the website Tai-facebook.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How To Use Pushbuttons With Raspberry Pi Gpio Pins
If you’ve ever used an LED with a Raspberry Pi, then you probably know how GPIO outputs work. Code makes electricity flow through General Purpose Input / Output (GPIO) pins, passes through the LEDs, and lights things up. But have you ever tried doing the reverse? With pushbuttons, you can do the exact opposite. This tutorial shows you how to turn a GPIO pin into an input pin, listening to every button press you make!
How Pushbuttons WorkA pushbutton is a type of switch. It has two separate conductive pins that prevent a complete circuit by being separate from each other. When you press on a pushbutton, you’re actually pushing the two pins together, completing the circuit. But if you let go, there’s a spring-like mechanism that separates the pins again.
4-Pin PushbuttonsThe typical pushbutton in sensor kits has four pins, with each pin separated from the others. A moving plate of metal sits right below the button area, which goes down and connects all the other pins when the pushbutton is pressed downward.
A 4-pin pushbutton has four pins below the button.
You’ll find two plates inside a 4-pin pushbutton. Each is connected to two external pins. Both plates are kept separate from each other and can only be connected by pressing on a third plate – the metal plate underneath the button.
Pinout of a 4-pin pushbutton. A switch connects the two pin pairs together.
In a way, there are always two pins connected in a pushbutton. When you press the 4-pin pushbutton, you connect all four pins together.
Using Pushbuttons with Raspberry Pi GPIO PinsThis time, we are making the Raspberry Pi GPIO pins detect a button press from a pushbutton. When electricity passes through it, the Raspberry Pi will print out a message telling you that it’s working.
Things You’ll Need
Pushbutton (4-pin)
Resistor (one between 100Ω and 1000Ω should work)
Jumper wires
Voltmeter (optional)
Raspberry Pi
Monitor and keyboard (or SSH)
How to Use Pushbuttons
Open your choice of code editor and paste the following code:
import
RPi.GPIO
as
GPIOfrom
time
import
sleep GPIO.setwarnings
(
False
)
GPIO.setmode
(
GPIO.BOARD
)
GPIO.setup
(
7
,
GPIO.IN
,
pull_up_down=
GPIO.PUD_DOWN
)
while
True
:if
GPIO.input
(
7
)
==
GPIO.HIGH
:(
"Pin 7 is HIGH!"
)
elif
GPIO.input
(
7
)
==
GPIO.LOW
:(
"Pin 7 is LOW..."
)
sleep(
0.15
)
Save as “rpi-pushbutton.py” (or any name you want as long as the file extension is the same).
Build the circuit. On one pin of the pushbutton, wire it up to pin 7 and a resistor in parallel. Attach a jumper wire to a GND pin (pins 6, 7, 14, 20, 25, 30, 34, or 39) at the other side of this resistor, then attach another jumper wire to a 3.3V pin (pins 1 or 17) on a separate pushbutton pin.
Left: Schematic diagram of pushbutton circuit. Right: Live pushbutton on breadboard. Jumper wire color designations: red = 3.3V, brown = pin 7, and black = GND.
Tip: to find the right pin number, hold your Raspberry Pi in a way that the GPIO pins sit in the upper-right corner. The top-left pin is pin 1, and to the right of it is pin 2. Below pin 1 is pin 3, to the right is pin 4, and so on.
Pinout of the Raspberry Pi
Power up your Raspberry Pi and open the terminal. Use cd to move to the Python script’s directory, then enter python3 chúng tôi If you used a different filename, use that instead of “rpi-pushbutton.”
You should see a new line of text saying Pin 7 is LOW... every 0.15 seconds on the terminal. If you press the button, the new line will be Pin 7 is HIGH!.
If you switch the GND and 3.3V pins, with 3.3V on the resistor and GND on the other side of the pushbutton, you’ll reverse the pushbutton’s logic. It will output Pin 7 is HIGH! all the time and become Pin 7 is LOW when you press the button.
Left: A pull-down resistor is made by connecting a GND (black) pin 7 (brown). Right: Connecting 3.3V (red) to pin 7 (brown) makes a pull-up resistor instead.
Hardware on PushbuttonsPushbuttons use two kinds of resistors: pull-up and pull-down. The one with 3.3V connected to the resistor is a pull-up resistor. It pulls the voltage upward. Meanwhile, pull-down resistors pull voltage down by having a GND pin connected to them.
You can still use a pushbutton without a resistor, but doing that leaves your GPIO pin on float. A floating GPIO pin receives no direct electric charge, so it looks for charges over its surroundings. If there’s a strong electromagnetic field near it, for example, it will just measure that instead.
Pin 7 (brown) becomes a floating pin when 3.3V (red) is separated from it.
That’s why you need a reference point. If you hook the GPIO pin to 0V (GND) by default, then it will measure 0V while the button is unpressed. But if you don’t, the GPIO pin’s value can be anywhere – even negative volts!
Floating pins can do some interesting things, though. If you leave a pin floating, it can sense the voltage difference in the air, measuring even the effect of having your finger move near the pin itself. It’s like an electromagnetic presence sensor or something.
It’s too bad you can’t just do that on the Raspberry Pi, though. For that to be useful, you’ll need analog pins, and the Raspberry Pi doesn’t have them.
Code for PushbuttonsKnowing that, you should understand that pin 7 senses whether 3.3V or 0V passes through it. If it senses 3.3V, then it reports itself as HIGH. But if it senses 0V, then it’s LOW.
Let’s divide the code into three parts: import commands, setup commands, and looped commands.
Import CommandsWe are using two import commands:
import
RPi.GPIO
as
GPIOfrom
time
import
sleepimport chúng tôi as GPIO imports the chúng tôi module, which lets you do stuff with your Raspberry Pi’s GPIO pins. By adding in as GPIO at the end, you’re telling Python to say that typing GPIO is equivalent to typing RPi.GPIO. You can even replace it with other strings, and the code should still work as long as you format it properly.
On the other hand, from time import sleep imports only a part of Python’s time module. It lets you use the sleep() function.
Setup CommandsWe are working with the three commands from the chúng tôi module on the setup commands to fix some settings.
GPIO.setwarnings
(
False
)
GPIO.setmode
(
GPIO.BOARD
)
GPIO.setup
(
7
,
GPIO.IN
,
pull_up_down=
GPIO.PUD_DOWN
)
The chúng tôi module normally shows a message that warns you about using the GPIO pins as soon as you start up the Python script. GPIO.setwarnings(False) prevents that from happening.
GPIO.setmode(GPIO.BOARD) is another command from the chúng tôi module. It tells Python that you’re using the “BOARD” pinout. There are two kinds of pinout in RPi.GPIO: BOARD and BCM. BOARD lets you pick pins by using the pin numbers. BCM (short for “Broadcom”) lets you pick pins with their individual Broadcom SOC Channel. BOARD is much easier to use, as it’s always the same no matter what kind of Raspberry Pi board you use. The BCM pinout can change depending on which model you use.
Looped CommandsEmbedded systems normally just use a few lines of code and loop them indefinitely. Different programming languages use different ways to do it. But the concept is the same: they use some sort of a loop. For Python, that’s while True:.
while
True
:if
GPIO.input
(
7
)
==
GPIO.HIGH
:(
"Pin 7 is HIGH!"
)
elif
GPIO.input
(
7
)
==
GPIO.LOW
:(
"Pin 7 is LOW..."
)
sleep(
0.15
)
while True: lets you loop code indefinitely. Everything you place in it will run forever as long as there’s electricity on the board.
print("Pin 7 is HIGH!") is inside an if statement. All it does is print out Pin 7 is HIGH! on the console. You can replace that with any string, number, or variable that contains those.
Next is elif GPIO.input(7) == GPIO.LOW:. It’s basically the same as if GPIO.input(7) == GPIO.HIGH: except for the first part: it uses elif instead of if. The code elif stands for Else If. What it says is that if all the other code above it returns false, then Python should run this else-if statement.
Lastly, sleep(0.15) pauses the code for 0.15 seconds. Why pause the code at all? It’s mostly for performance issues. The Raspberry Pi will send output code so fast that it’s going to make your GUI lag a bit. It’s even more pronounced if you’re using your Raspberry Pi via SSH. There’s going to be a noticeable delay that will just get worse over time. Pausing the code slows it down to avoid performance issues.
Frequently Asked Questions Is it safe to hot-swap pins on the Raspberry Pi?Hot-swapping, or replacing the Raspberry Pi’s pins while powered on, is generally a bad idea. It’s always safer to remove it from the power supply before switching.
What makes 4-pin pushbuttons better than 3-pin pushbuttons?Utility-wise, they’re basically the same. But having four pins lets you wire the 4-pin pushbutton to another pushbutton in a series circuit.
Can I turn any pin on the Raspberry Pi as an input pin?The Raspberry Pi may have 40 pins, but only 27 of them are GPIO. You can only program GPIO pins into input and output pins. Most IDEs won’t let you reprogram a non-GPIO pin into an input pin.
All photos and screenshots by Terenz Jomar Dela Cruz
Terenz Jomar Dela Cruz
Terenz is a hobbyist roboticist trying to build the most awesome robot the world has ever seen. He could have done that already if he wasn't so busy burning through LEDs as a second hobby.
Subscribe to our newsletter!
Our latest tutorials delivered straight to your inbox
Sign up for all newsletters.
By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.
You're reading How To Use Pushbuttons With Raspberry Pi Gpio Pins
Using A Raspberry Pi With A Cloud Storage Service
Barracuda Networks is known for its network products, including Spam, Virus and Firewall appliances. In February 2013, the company launched its cloud storage service, chúng tôi with several unique features including 256-bit AES encryption and support for multiple platforms such as Linux, Windows, Mac, and even the Raspberry Pi.
Having a cloud storage service that caters to Linux users is great (especially with the upcoming closure of Ubuntu One), but having one that works also on the Raspberry Pi is fantastic!
The first step is to download the chúng tôi client for Raspberry Pi using wget:
sudo
apt-get install
wget
You will now have a file called “Copy.tgz” in your home directory. You can unpack the file using:
tar
zxvf chúng tôi will create a folder called “copy,” and in it there will be three sub-folders: “armv6h,” “x86,” and “x86_64.” The first one contains the Copy client binaries for the Raspberry Pi, the second contains the Copy client for 32-bit Linux on a PC, and the third the same client but for 64-bit Linux PCs.
We will use the Raspberry Pi binaries; however, using the chúng tôi client is essentially the same on Linux PCs. There are two tools provided by Barracuda Networks: “CopyCmd” and “CopyConsole.” The first is a general utility which allows you to perform certain specific actions like retrieving a file or getting the public link for a file. The second is the command line version of the Copy app which syncs a local folder with the cloud storage.
CopyCmdTo download a file from chúng tôi use:
To see a list of the other commands supported by CopyCmd, just run the binary without any parameters to see the built-in help information.
CopyConsoleThe sync app runs in the background and is started like this:
One thing worth noting is that if you have lots of files stored on chúng tôi and you activate the sync agent, then all of the data you have stored on the service will be downloaded to your Pi. Since many users probably use their Raspberry Pi with a 4GB or 8GB SD card, there is the danger of the storage filling up quickly.
You can also run the program in the foreground by omitting the “-daemon” parameter.
CopyAgentGary Sims
Gary has been a technical writer, author and blogger since 2003. He is an expert in open source systems (including Linux), system administration, system security and networking protocols. He also knows several programming languages, as he was previously a software engineer for 10 years. He has a Bachelor of Science in business information systems from a UK University.
Subscribe to our newsletter!
Our latest tutorials delivered straight to your inbox
Sign up for all newsletters.
By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.
Arduino Vs Raspberry Pi: Which Is The Better Diy Platform?
Table of Contents
Performance and SpecificationsIf you’re thinking about a PC replacement board, we’ll answer you now: a Raspberry Pi is the only option (at least compared to an Arduino). With the newest Raspberry Pi 4 and 4B offering between 1GB and 8GB of RAM and a quad-core, 1.5GHz ARM v8 processor, you’ve got a lot of power in a very small board.
Even the smaller Pi models (the Zero and Zero W boards) offer significant power for their size, with a 1GHz ARM CPU, 512MB RAM, GPIO headers for expansions, and integrated WiFi and Bluetooth support.
Like the Pi, there are various Arduino models, with the Arduino Uno offering a very small 2KB SRAM and 16MHz microcontroller for very specific projects. At the other end of the scale is the Arduino Portena H7, with a dual-core Cortex M7+M4 ARM microcontroller, between 8MB and 64MB RAM, and integrated Bluetooth and WiFi.
Speed and performance are a win for the Pi, but the Arduino doesn’t need to run all the complex applications that a Raspberry Pi (with a full Linux distro) has to. The only fair comparison might be with a Raspberry Pi Pico, the hobbyist microcontroller board with a dual-core ARM Cortex M0+ processor and 264KB RAM.
FunctionalityAs we’ve touched upon already, the Raspberry Pi is a very powerful computer for its size. While earlier models (from the original Pi to the Raspberry Pi 3) were arguably quite slow, the newest models (the Raspberry Pi 4 and 4B) offer huge performance enhancements.
This makes it possible for you to replace your working PC with a Raspberry Pi. It isn’t ideal for gaming (except for retro gaming) or video encoding, but it’s a fully functional server or PC. It can also be integrated into any number of projects, whether it’s building a weather station or as the nerve center of a robotics build.
The Arduino doesn’t have the same functionality in some ways, but it’s targeting a different audience. If you’re a proficient coder, you can program your Arduino to perform any task you like. It could become a remote controlled car, a home alarm, a communications system—all are possible with the right equipment connected to it.
You might choose an Arduino for size or power requirements, but if you need performance and functionality, the Raspberry Pi is the overall winner.
UsabilityAlthough the Arduino and Raspberry Pi are boards with a lot of potential, that doesn’t mean that they’re exceptionally hard to use. Both boards have their origins in education, with the Pi created to help schools and parents reintroduce the 80s-style curiosity that encouraged children to learn to code.
As a microcontroller board, the Arduino is a beginner coder’s dream. The Arduino website itself offers tutorials and example code to help you create new projects. While the Raspberry Pi allows users to do many things at once, the Arduino focuses on a single purpose, created and coded by its user.
Unfortunately, Arduino uses C++ as the main language for its code. This isn’t the easiest language to learn or use, unlike the beginner-friendly Python which the Raspberry Pi supports in full (along with other major programming languages).
If programming isn’t for you, then you don’t need to program with the Raspberry Pi, either. Installing Raspberry Pi OS or another Linux distro will give you a full operating system, including a graphical user interface that allows you to run standard software such as Google Chrome or LibreOffice.
The same can’t be said for the Arduino, unfortunately. If you’re prepared to accept the tougher learning curve, however, it can be the centerpiece of a great new project build, but a Raspberry Pi will get you there quicker.
CostPower and usability are one thing, but cost is important, especially for a hobbyist project with a modest budget. Thankfully, both the Arduino and Raspberry Pi are extremely cheap to purchase and use.
At the bottom end of the Raspberry Pi model range is the Raspberry Pi Pico. At just $4, this tiny controller is the programmable nerve center of a hobbyist project. Unlike the Arduino, it supports C and MicroPython (Python for microcontrollers), making it an easier-to-use system.
For full performance, however, the Pi 4 Model B costs between $35 (for 2GB RAM) and $75 (for 8GB), depending on the retailer. You can also grab the smaller, less powerful Zero W for $10. Other boards (such as the older Pi, 2, 3, and 3B) are priced similarly, with discounts available due to their age and lower specifications.
Thankfully, Arduino boards are cost-friendly, too. There are many Arduino boards available, but some of the most common, like the Arduino Uno, cost around $20-30. Other boards (such as the Pro Mini) can cost as low as $10, with the Mega costing $60, and the Portena H7 costing $99.99.
As an open-source board, the Arduino also has a number of clones at similar price ranges. With the Raspberry Pi Pico costing just $4, however, the Raspberry Pi’s microcontroller is still the best value for money, but this will depend on the performance and power requirements of your particular project.
Arduino vs Raspberry Pi: Which Is Best For You?How To Use Alexa With Samsung Tv
There are two ways to use Alexa with your Samsung smart TV. If you have a newer model, your Samsung smart TV will have Alexa built in. But if you have an older Samsung smart TV, you must connect an external Alexa-enabled device to control the TV. This tutorial covers both ways to use Alexa with Samsung TV.
Tip: read on if you’re looking to learn how to set up a smart TV.
How to Connect Alexa-Enabled Amazon Echo Devices to Samsung TVFollow the steps below to connect an Amazon Echo device to your Samsung smart TV. We have divided the steps into different sections for clarity.
1. Set Up Samsung SmartThings App
Download and open the Samsung SmartThings app on your Android or iPhone.
Grant the necessary permissions when asked.
Tap on the “Devices” tab at the bottom and press the Add Device {+) button.
Log in to your Samsung account. Make sure it is the same account used to register your Samsung TV.
Scroll down in the list of devices and tap on “TV” followed by “Samsung.”
Follow the on-screen instructions to set up the TV in the SmartThings app. Make sure your phone and TV are connected to the same Wi-Fi network. If your TV isn’t connecting to Wi-Fi, read this tutorial to learn how to fix it.
Once your Samsung smart TV has been added successfully to the SmartThings app, follow the steps below to connect the Echo device and Samsung Smart TV.
2. Connect Samsung Smart TV to Echo DeviceTip: learn how to fix common Amazon Echo problems.
Assuming that your
Echo device has already been set up
on your smartphone, open the Amazon Alexa app on your Android or iPhone.
Tap on the “Devices” tab. Scroll down to the bottom and tap on “Your Smart Home Skills.”
Tap on “Enable Smart Home Skills.”
Tap on the search icon at the top and enter “smartthings,” then tap on the SmartThings result.
Press the “Enable to use” button, then tap on “Authorize” to give Alexa permission to access your devices.
Tip: learn how to create an Alexa skill without coding experience.
Log in to your Samsung account if asked. The SmartThings account will then be linked to the Alexa app. Tap on “Next.”
The Alexa app will start searching for your Samsung TV. Make sure the TV is on. Once the app finds the TV, tap on “Set Up Device.”
You will be asked to add the device to a group, like your bedroom or living room. Select the preferred group and tap on “Add to group,” or press the “Skip” button if you don’t want to add it to a group.
Your Samsung TV has been successfully added to the Alexa app, and you can control the TV with an Alexa-enabled device.
3. Select Alexa Device to Control Samsung TVIf your Echo device is unable to control your Samsung smart TV, you must choose the Alexa device to link to the Samsung TV in the Alexa app.
Open the Alexa app and tap on the “Devices” tab at the bottom.
Tap on the room where you added the TV, followed by “Samsung TV.” Alternatively, if you didn’t add it to a room, tap on “All Devices” at the top followed by your TV.
Press the “Linked Alexa Devices” option and choose your Alexa device, then tap on “Manage/Link Device.”
If all goes well, a confirmation screen will appear. Tap on “Continue” or follow the steps below to change the name of the TV.
Good to know: Follow this helpful guide to learn how to transfer files from your Android to a smart TV.
4. Change the Name of the Samsung TV in the Alexa AppThe Alexa app will take the default name of your TV, and it can be rather long. If you want to refer to your Samsung TV by an easier name, follow these steps:
Open the Alexa app on your phone.
Tap on the “Devices” tab and go to your TV, listed either inside a group or under “All Devices.”
Tap on the “Edit Name” option under the TV name. Enter a name and press anywhere on the screen to save it.
How to Control a Samsung Smart TV with an Alexa-Enabled DeviceAfter you have linked your Samsung TV and Amazon accounts, you can control them using the following commands. Unfortunately, you can only use basic commands to control Samsung TVs with an Alexa-enabled device.
Alexa, turn on/off [TV name].
Alexa, turn up the volume on [TV name].
Alexa, switch input to HDMI on [TV name].
Alexa, pause the [TV name].
Alexa, play the [TV name].
Tip: learn how to use SamsungDex on yoru smart TV.
How to Use Built-in Alexa on a Samsung Smart TVAs mentioned above, newer Samsung smart TVs ship with Alexa built in. On some Samsung TVs, you have to use the Alexa button on the remote to talk to Alexa. However, some TVs also have a built-in Alexa app so that you can talk to Alexa without even using the remote. The built-in Alexa in both of these scenarios offers numerous commands.
For example, you can ask Alexa to open apps on your TV, search for movies and shows, play music, control the volume, control your smart home devices, check the weather, change the channel, etc.
Frequently Asked Questions Is there a monthly fee to use Alexa with Samsung smart TV?No, you can use Alexa for free to control your Samsung TV and don’t even need amazon Prime. However, data charges will apply, as Alexa uses Wi-Fi.
Can you use Alexa with a non-smart Samsung TV?You cannot use Alexa to control your non-smart Samsung TV directly. But it’s possible if you connect any external streaming device to the TV using its HDMI port.
How can I troubleshoot the situation when Alexa doesn’t work with my Samsung smart TV?If Alexa is unable to control your Samsung smart TV, you should restart both the TV and the Alexa-enabled device. If that doesn’t fix the issue, then try re-pairing the device to the Samsung TV. Additionally, you should make sure both devices are connected to the same Wi-Fi network.
All images and screenshots by Mehvish Mushtaq.
Mehvish Mushtaq
Mehvish is a tech lover from Kashmir. With a degree in computer engineering, she’s always been happy to help anyone who finds technology challenging. She’s been writing about technology for over six years, and her favorite topics include how-to guides, explainers, tips and tricks for Android, iOS/iPadOS, Windows, social media, and web apps.
Subscribe to our newsletter!
Our latest tutorials delivered straight to your inbox
Sign up for all newsletters.
By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.
How To Use Excel Hacks With Keyboard Shortcuts?
Excel Hacks (Table of Contents)
Start Your Free Excel Course
Excel functions, formula, charts, formatting creating excel dashboard & others
Introduction to Excel Hacks How to Use Excel Hacks?Here we discuss the list of most of Microsoft Excel’s significant shortcut buttons and main combinations with examples.
You can download this Excel Hacks Template here – Excel Hacks Template
Example #1 – Use of Important Keyboard Shortcuts1. Selection of Data
2. Column Width Size Adjustment
3. Insertion of Date or Time or Comments in Excel
In some scenarios, we need to enter today’s date & time; instead of looking into the calendar or time at the bottom, we can use the below-mentioned shortcut key.
For date: CTRL + ; or For time: SHIFT + CTRL + ;
4. Addition of a New Line in a Cell
Suppose you are entering address details, and you need to add multiple lines of data in the same cell; for that, you need to enter short cut key “Alt + Enter”, it will move the cursor down so that you can enter or type the text in the next line.
5. Addition or insertion of multiple columns or rows
6. Autosum the Selected Data Range
Suppose I have a numeric data range, so I want to do a sum up for that data range. To perform this task faster, you need to select the data range.
After pressing the “ALT key and Enter”, it will give the range’s total value.
7 Addition of Cell Border
Here we want to add a cell border across the data range.
After pressing on “Ctrl + Shift + &”, cell borders are automatically added.
8. Number Formatting
You can select a date range if you want a dollar sign displayed before each number.
9. Make a Copy of your Worksheet in the Same Workbook
Suppose you have a quarterly report in sheet 1 of a workbook, so you need to re-create it from scratch for the next quarter’s sales data, which is very difficult and time-consuming; you can use the “Move or Copy” option under the worksheet.
10. Freeze the Top Row
11. Addition of Filter for a Data Range
Suppose you want to filter data in a worksheet.
Example #2 – Usage of Important Formulas1. To Count Blank Cells in the Data Range with the help of the COUNTBLANK Formula
Here in the below-mentioned example, I want to count a blank cell in the data range (A2 to A7).
2. To Count Only Text Value in the Data Range with the help of COUNTA Formula
In the below-mentioned example, I want to count only a cell containing text values in the data range (A12 To A17); I can use the combination of the count formula, i.e., the COUNTA formula will count everything, including text & numeric value.
After using the COUNT formula, it will count only the numbers, i.e., = COUNTA (A2:A7)-COUNT (A2:A7). The difference between these two will result in an output value of 2.
3. To know the Formula Text or which formula you have used
If you know which formula is present in a cell, you can check it out with the help of the =FORMULATEXT(cell reference) formula. Here I have used cell A8 (as a cell reference).
After using the formula, the output is shown below.
4. To Pullout Only Decimal Values with the help of MOD & INT Function
I have a cell value of 98.23 in cell “A2” I want only the decimal portion in cell “B2”; to get this, I can use the formula MOD & INT function.
After using the formula, the output is shown below.
Things to RememberWith the help of the symbols or arithmetic operators explained in the above examples in user or predefined Excel formulas, you can quickly perform various required calculations between numbers, cells, entire rows, and columns or ranges of cells.
Recommended ArticlesThis is a guide to Excel Hacks. Here we discuss How to Use Excel Hacks with Excel shortcut keys, practical examples, and a downloadable Excel template. You can also go through our other suggested articles –
How To Use Excel Vba Instrrev With Examples?
VBA InStrRev Function
Knowing the occurrence of a string in another string can be very handy while working with day to day data. Obviously, we can do it manually by calculating the occurrence of the string in another string but that would the task very hefty. So to make it easier we have a function in VBA which is known as INSTRREV which is used to find the occurrence.
As explained above, INSTRREV in Excel VBA is used to find an occurrence of a string in another string. This function finds the first occurrence of a string in the target string and returns the value. Now we have to remember that as it gives the occurrence of the string so the returned value is numeric. Also as it is a comparison function so like other functions in VBA there are three basic comparisons methods.
Watch our Demo Courses and Videos
Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.
Syntax of InStrRev in Excel VBAThe syntax for VBA InStrRev function in excel is as follows:
Now let us break down the syntax and learn about it, String is the main string from where we want to find the occurrence of a substring, Start is the numeric occurrence we provide to the string. If no start parameter is provided the function starts looking a string from the end of it. And compare is the comparison method we provide to the function. There are three types of comparison for this function:
To use Option Compare which is (-1). It is also known as VbUseCompareOption.
To use Binary Compare which is (0). It is also known as VbBinaryCompare.
To use Text Compare which is (1). It is also known as VbTextCompare.
Again if none of the compare options is provided then the function automatically considers it as a binary compare.
Now let us use this function in a few examples and look at how to use this function.
How to Use Excel VBA InStrRev?Now let us try with some examples on VBA InStrRev in Excel.
You can download this VBA InStrRev Excel Template here – VBA InStrRev Excel Template
Example #1 – VBA InStrRevStep 2: Once we enter the VB editor we can see in the header section, there is an option of insert. Insert a new module from that option as shown below.
Step 3: Now let us start our subprocedure in the module as shown below.
Code:
Sub
Sample()End Sub
Step 4: Now declare a variable as an integer which will hold the output value of the function for us.
Code:
Sub
Sample()Dim
AAs Integer
End Sub
Step 5: Now in the variable use the INSTRREV function to find the occurrence of “ “ in the string “ I am a Good Boy” as follows.
Code:
Sub
Sample()Dim
AAs Integer
A = InStrRev(" I am a Good Boy", " ")End Sub
Step 6: Now display the value stored in variable A using the msgbox function.
Code:
Sub
Sample()Dim
AAs Integer
A = InStrRev(" I am a Good Boy", " ") MsgBox AEnd Sub
Step 7: Let us execute the above code to get the following result.
We get the result as 13 because we did not provide the start position to the function so it automatically calculated the occurrence from the end and so the result. It is found that “ “ is on the 13th position of the string when we search it from the end.
Example #2 – VBA InStrRevIn the above example, we did not provide any start position to the string. Let us provide this time in this example. Let us find out from the second position where does the “ “ occurs in the string.
Step 1: Insert a new module from that option as shown below.
Step 2: Let us again define a subprocedure for our second example.
Sub
Sample1()End Sub
Step 3: Declare another integer variable for the example.
Code:
Sub
Sample1()Dim
AAs Integer
End Sub
Step 4: Now in Variable A let us find the occurrence of the “ “ from the second position using the INSTRREV function as follows.
Code:
Sub
Sample1()Dim
AAs Integer
A = InStrRev(" I am a Good Boy", " ", 2)End Sub
Step 5: Now use msgbox function to display the value stored in A.
Code:
Sub
Sample1()Dim
AAs Integer
A = InStrRev(" I am a Good Boy", " ", 2) MsgBox AEnd Sub
Step 6: Now run the above code to find out the below result as shown below,
We get 1 as a result as we count 2 we get I and after one position we get the occurrence of “ “.
Example #3 – VBA InStrRevIn this example let us use the compare methods. We have a string “ India is the Best” and let us find the string “E” using both text and binary compare methods.
Step 1: In the same module 1, write another subprocedure for example 3.
Code:
Sub
Sample2()End Sub
Code:
Sub
Sample2()Dim
A, BAs Integer
End Sub
Step 3: In variable A let us use the INSTRREV function with the text comparison as follows.
Code:
Sub
Sample2()Dim
A, BAs Integer
A = InStrRev("India is the Best", "E", , vbTextCompare)End Sub
Step 4: Now display the value stored in A using the msgbox function.
Code:
Sub
Sample2()Dim
A, BAs Integer
A = InStrRev("India is the Best", "E", , vbTextCompare) MsgBox AEnd Sub
Step 5: In variable B let’s use the binary comparison for the same string as follows.
Code:
Sub
Sample2()Dim
A, BAs Integer
A = InStrRev("India is the Best", "E", , vbTextCompare) MsgBox A B = InStrRev("India is the Best", "E", , vbBinaryCompare) MsgBox BEnd Sub
Step 6: Execute the above code to find the first result stored in variable A which is as follows.
Step 7: Press OK to see the result stored in variable B.
We get 0 as the result for binary compare because in our string “e” is present not “E”. In binary values both of these are different. So if a value is not found in the string we get a result as 0.
Things to Remember
The value returned by this function is numeric.
If the substring is not found the value returned is 0.
Start position is optional. If it is not provided, by default function search the occurrence from the end of the string.
The comparison methods are also optional.
Recommended ArticlesThis is a guide to VBA InStrRev. Here we discuss how to use Excel VBA InStrRev along with practical examples and downloadable excel template. You can also go through our other suggested articles –
Update the detailed information about How To Use Pushbuttons With Raspberry Pi Gpio Pins on the Tai-facebook.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!