Author Archives: admin

About admin

Admin is an Industrial Automation Engineer with 7+ years of field experience & much interested in Electronics. Apart from this, photography is passion & hobby.

Seven segment display interface with Arduino (Without library)

A seven-segment display is a form of electronic display device for displaying decimal numerals that is an alternative to the more complex dot matrix displays. In this tutorial you will learn about seven segment display interface with Arduino, its possibilities & Arduino code. Seven-segment displays may use a liquid crystal display (LCD), a light-emitting diode (LED) for each segment, an electrochromic display, or other light-generating or controlling techniques such as cold cathode gas discharge (Panaplex), vacuum fluorescent (VFD), incandescent filaments (Numitron), and others.

In a simple LED package, typically all of the cathodes (negative terminals) or all of the anodes (positive terminals) of the segment LEDs are connected and brought out to a common pin; this is referred to as a “common cathode” or “common anode” device. Hence a 7 segment plus decimal point package will only require nine pins, though commercial products typically contain more pins, and/or spaces where pins would go, in order to match standard IC sockets.

Characters on seven segment display

The segments of a 7-segment display are referred to by the letters A to G, where the optional decimal point (an “eighth segment”, referred to as DP) is used for the display of non-integer numbers.

You can display 0-9 decimals on seven segment display. The most common patterns used for each of these is:

To display hexadecimals, you have to turn on segments to represent A, B, C & D. Same can be displayed as;

So, using seven segment display you can easily display hexadecimal numbers from 0 to F. To represent same, you can refer following table:

Digit Display gfedcba abcdefg a b c d e f g
0 0 0x3F 0x7E on on on on on on  
1 1 0x06 0x30   on on        
2 2 0x5B 0x6D on on   on on   on
3 3 0x4F 0x79 on on on on     on
4 4 0x66 0x33   on on     on on
5 5 0x6D 0x5B on   on on   on on
6 6 0x7D 0x5F on   on on on on on
7 7 0x07 0x70 on on on        
8 8 0x7F 0x7F on on on on on on on
9 9 0x6F 0x7B on on on on   on on
A A 0x77 0x77 on on on   on on on
b b 0x7C 0x1F     on on on on on
C C 0x39 0x4E on     on on on  
d d 0x5E 0x3D   on on on on   on
E E 0x79 0x4F on     on on on on
F F 0x71 0x47 on       on on on

Apart from hexadecimals, there are few characters which are being used to display on seven segment display which are as below;

Case A B C D E F G H I J K L M N O P Q R S T U V W X Y
Upper A   C   E F G H I J   L     O P     S   U        
Lower   b c d       h i         n o   q r   t u       y

Few short messages giving some status information (e.g. “no dISC” on a CD player) are also usually represented on seven segment displays. In the case of such messages it is not necessary for every letter to be unambiguous, merely for the words as a whole to be readable. For example:

There are few decoder ICs available in market (like CD4511) which has BCD as input (4 pins) & seven segment pins as output. First we will see how to connect a seven segment display with Arduino without any external IC.

Seven segment display pinout

7 segment pinout

As you can see, all segment LEDs are connected with common pin & separate pinout pins for each LED. Above diagram is common cathode seven segment display, if it is common anode then LED polarity will be reversed compared to common cathode.

Seven segment display interface with Arduino

Seven segment display interface with Arduino

In above connection diagram, common cathode type seven segment is used to interface with Arduino. If you have common anode type seven segment display, you have to connect 

Usually, the display may run without any current limiting resistors. So it is advised to use for protection against high current & display segments burnout. Usually for a commonly used red color seven segment display, each LED segment can draw around 15 mA to illuminated properly, so for 5 volt digital logic circuit, the value of the current limiting resistor would be about 200Ω (5v – 2v) / 15mA, or 220Ω to the nearest preferred value. SO resistor value may vary as per seven segment display technical specifications. You can test each segment LED of your seven segment by applying +1.5V to 5V on each pin and common pin to ground.

Arduino code for seven segment display test without library

You can download above code from here.

Above code is for basic understanding seven segment display’s working operation by Arduino. Basically, it is just particular segment pin HIGH & LOW, but it may be more complex if you have more than one displays (that is different topic of seven segment display multiplexing and same will be posted on #beatyourbit in future). The code is to display 0-9 counts at interval of 1 second. The output will look like,

Thus, It may be little bit long but also without any library you can simply use seven segment display. Similar code you can write by directly writing on GPIO ports (Pure AVR method). Find below code with similar output as above:

You can download above code from here.

Understanding above code:

ATmega328p has total 3 No. of GPIO ports namely Port B, Port C & Port D. Port C is an analog port as it has total six pins which are usually used as A0 to A6 in Arduino. Port B & Port D are digital ports & each port has 7 pins hence total 14 digital pins (D0 to D13). here in above code we have used port addressing, the basic method of AVR programming.

I hope you will learn to use single seven segment display by this tutorial & it will be helpful to display some counts or characters in your DIY stuff. In future you can use external seven segment decoders ICs to run such seven segment displays using minimum pins and also multiplexing of multiple seven segment displays; such tutorials will be uploaded soon on #BeatYourBit website. If you like this tutorial, share it with your friends & any Arduino newbie you know. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Like/Follow @beatyourbit on FacebookTwitterInstagram & Telegram for latest updates.

HC-SR501 PIR motion sensor interface with Arduino

What is PIR sensor?

A passive infrared sensor (PIR sensor) is an electronic sensor that measures infrared (IR) light radiating from objects in its field of view. They are most often used in PIR-based motion detectors. HC-SR501 PIR sensors are commonly used in security alarms and automatic lighting applications. PIR sensors detect general movement, but do not give information on who or what moved. For that purpose, an active IR sensor is required. PIR sensors are commonly called simply “PIR”, or sometimes “PID”, for “passive infrared detector”. The term passive refers to the fact that PIR devices do not radiate energy for detection purposes. They work entirely by detecting infrared radiation (radiant heat) emitted by or reflected from objects.

PIR sensor parts

For a DC current, the PIR Sensor works from 3.3v to 5v DC and gives a TTL output which is directly given to a microcontroller or to relay through a transistor. The PIR sensor consists of a pyroelectric sensor and a Fresnel lens. This curved lens concentrates infrared radiation toward a detector’s sensor. The sensor output is inverted by the transistor. Collector of the transistor is connected to the input pin forms the latch circuit which is set when PIR output goes high to indicate the presence of a warm body. Output of the latch pin operates the relay driving circuit formed by transistors arranged in emitter follower mode.

How PIR sensor works?

HC-SR501 PIR sensor can detect changes in the amount of infrared radiation impinging upon it, which varies depending on the temperature and surface characteristics of the objects in front of the sensor. PIR Operation

When an object, such as a person, passes in front of the background, such as a wall, the temperature at that point in the sensor’s field of view will rise from room temperature to body temperature, and then back again. The sensor converts the resulting change in the incoming infrared radiation into a change in the output voltage, and this triggers the detection. Objects of similar temperature but different surface characteristics may also have a different infrared emission pattern, and thus moving them with respect to the background may trigger the detector as well.

PIR Module interface with Arduino

PIR Motion Arduino Interface

Compared to other sensors, this one is much easy to interface & use.

Arduino Code

You can download the above code from here.

Upload above code in your Arduino and check the motion detection output on Arduino LED on Pin 13 or serial monitor of Arduino IDE.

I hope you will learn to use PIR motion sensor by this tutorial & it will be helpful to add live object detection in your DIY stuff. In further of this tutorial, you can add some logical conditions in code to turn ON buzzer or send SMS/Email notification for human/animal detection; Notification to receive in phone, microcontroller, computer, cloud database i.e. Arduino based security system. In future such projects will be uploaded in #BeatYourBit website. If you like this tutorial, share it with your friends & any Arduino newbie you know. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Like/Follow @beatyourbit on FacebookTwitterInstagram & Telegram for latest updates.

MT8870 DTMF Decoder Module

MT8870 DTMF decoder module interface with Arduino

Dual-tone multi-frequency signaling (DTMF) is a telecom signaling system using the voice-frequency band over telephone lines between telephone and other comn. devices and switching centers. DTMF was first developed in the Bell System in the United States, and became known under the trademark Touch-Tone for use in push-button telephones supplied to telephone customers, starting in 1963. DTMF is standardized as ITU-T Recommendation Q.23. It is also known in the UK as MF4. The Touch-Tone system using a telephone keypad gradually replaced the use of rotary dial and has become the industry standard for landline and mobile service. Other multi-frequency systems are used for internal signaling within the telephone network.

Multi-frequency signaling (MF) is a group of signaling methods that use a mixture of two pure tone (pure sine wave) sounds. Various MF signaling protocols were devised by the Bell System and CCITT. The earliest of these were for in-band signaling between switching centers, where long-distance telephone operators used a 16-digit keypad to input the next portion of the destination telephone number in order to contact the next downstream long-distance telephone operator. This semi-automated signaling and switching proved successful in both speed and cost effectiveness. Based on this prior success with using MF by specialists to establish long-distance telephone calls, dual-tone multi-frequency signaling was developed for end-user signaling without the assistance of operators.

The DTMF system uses a set of eight audio frequencies transmitted in pairs to represent 16 signals, represented by the ten digits, the letters A to D, and the symbols # and *. As the signals are audible tones in the voice frequency range, they can be transmitted through electrical repeaters and amplifiers, and over radio and microwave links, thus eliminating the need for intermediate operators on long-distance circuits.

The DTMF telephone keypad is laid out as a matrix of push buttons in which each row represents the low frequency component and each column represents the high frequency component of the DTMF signal. The commonly used keypad has four rows and three columns, but a fourth column is present for some applications. Pressing a key sends a combination of the row and column frequencies. For example, the 1 key produces a superimposition of a 697 Hz low tone and a 1209 Hz high tone. Initial push-button designs employed levers, enabling each button to activate one row and one column contact. The tones are decoded by the switching center to determine the keys pressed by the user.

DTMF keypad frequencies (with sound clips)
  1209 Hz 1336 Hz 1477 Hz 1633 Hz
697 Hz 1 2 3 A
770 Hz 4 5 6 B
852 Hz 7 8 9 C
941 Hz * 0 # D

DTMF was originally decoded by tuned filter banks. By the end of the 20th century, digital signal processing became the predominant technology for decoding. DTMF decoding algorithms typically use the Goertzel algorithm. As DTMF signaling is often transmitted in-band with voice or other audio signals present simultaneously, the DTMF signal definition includes strict limits for timing (minimum duration and inter-digit spacing), frequency deviations, harmonics, and amplitude relation of the two components with respect to each other (twist).

The MT8870D/MT8870D-1 is a complete DTMF receiver integrating both the band-split filter and digital decoder functions. The filter section uses switched capacitor techniques for high and low group filters; the decoder uses digital counting techniques to detect and decode all 16 DTMF tone pairs into a 4-bit code. External component count is minimized by on chip provision of a differential input amplifier, clock oscillator and latched three-state bus interface. SSI202 and M957 are alternatives for MT8870 but they are no longer in production.

Features of MT8870D IC :

  • Complete DTMF Receiver
  • Low power consumption
  • Internal gain setting amplifier
  • Adjustable guard time
  • Central office quality
  • Power-down mode
  • Inhibit mode
  • Backward compatible with MT8870C/MT8870C-1

Applications of MT8870D :

  • Receiver system for British Telecom (BT) or CEPT Spec (MT8870D-1)
  • Paging systems
  • Repeater systems/mobile radio
  • Credit card systems
  • Remote control
  • Personal computers
  • Telephone answering machine
Digit    TOE       INH       ESt       Q4       Q3       Q2       Q1   
   ANY       L       X       H       Z       Z       Z       Z   
   1       H       X       H       0       0       0       1   
   2       H       X       H       0       0       1       0   
   3       H       X       H       0       0       1       1   
   4       H       X       H       0       1       0       0   
   5       H       X       H       0       1       0       1   
   6       H       X       H       0       1       1       0   
   7       H       X       H       0       1       1       1   
   8       H       X       H       1       0       0       0   
   9       H       X       H       1       0       0       1   
   0       H       X       H       1       0       1       0   
   *       H       X       H       1       0       1       1   
   #       H       X       H       1       1       0       0   
   A       H       L       H       1       1       0       1   
   B       H       L       H       1       1       1       0   
   C       H       L       H       1       1       1       1   
   D       H       L       H       0       0       0       0   
   A       H       H       L    Undetected, the output code will remain the same as the previous detected code
   B       H       H       L   
   C       H       H       L   
   D       H       H       L   

Functional Decode Table
(L=Logic Low, H=Logic High, Z=High Impedance, X = Don’t care)

More detail about MT8870 IC is available in datasheet, click here to download it.

MT8870 DTMF Decoder module schematic

MT8870 DTMF Module Schematic

Features of MT8870 DTMF Decoder Module :

  • Power Input: +5VDC (+4.5V to +5.5V)
  • Onboard 3.5 mm jack input
  • MT8870 Based Frequency Decoder
  • 5 Channel Interface
  • Detects 0-9, A-D, *, #
  • LED indication for binary output state
  • 2.54” Pin pitch
  • Board Dimension: 37 x 25 x 12 mm (l x w x h)

MT8870 Module interface with Arduino

MT8870 Module interface with Arduino

Configuration is as simple as shown in above diagram. To give DTMF input, you can connect AUX cable from MT8870 module 3.5 mm jack to your phone’s 3.5 mm jack.

Arduino code for MT8870 module

You can download above sketch from here.

For DTMF signal input to the module, you have to connect MT8870 module and your phone using 3.5mm audio jack AUX cable.

MT8870 Phone Connection

Now open the dial pad of you phone, press 0 to 9, * & # numbers and you will see the output LEDs on module will change their state & you will observe in serial module that which key is pressed.

DTMF Serial Output

I hope you will learn to use MT8870 DTMF decoder module by this tutorial & it will be helpful to add GSM control in your DIY stuff. In further of this tutorial, you can add some logical conditions in code to turn on-off Arduino GPIO by particular DTMF tone received and same can be designed as device control using phone. In future such projects will be uploaded in #BeatYourBit website. If you like this tutorial, share it with your friends & any Arduino newbie you know. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Like/Follow @beatyourbit on FacebookTwitterInstagram & Telegram for latest updates.

GY-30 BH1750 Ambient light sensor module interface with Arduino

BH1750 is an ambient light sensor & it’s module design is known as GY-30. Ambient light is the light which is already present in a scene, without any additional lighting is added. It usually refers to natural light & also mean artificial lights such as normal room lights. For photography, ambient light is most important as camera lens requires it to generate the image from the scene. An ambient light sensor is a component in smartphones, notebooks, other mobile devices, gadgets, automotive displays and LCD TVs. It is a photo-detector that is used to sense the amount of ambient light present, and appropriately dim the device’s screen to match it. This avoids having the screen be too bright when the user’s pupils are adapted for vision in a dark room, or too dim when the device is used outdoors in the daytime. Dimming the screen on a mobile device also prolongs the lifetime of the battery. The standard international unit for the illuminance of ambient light is the lux. The typical performance of an ambient light sensor is from less than 50 lux in dim light to over 10,000 lux at noon.

This is a BH1750 light intensity sensor breakout board/module with a built-in 16 bit AD converter which can directly give digital signal (on I2C) as output, hence no need for complicated calculations in controlling unit. It consumes a very low amount of current. This photo diode contains a PN junction. When light falls on it, electron-hole pairs are created in the depletion region. Due to the internal photoelectric effect, electricity is produced in the photo-diode. This produced electricity is proportional to the intensity of light. This electricity is changed into a voltage by the Op-amp. With the BH1750 light sensor intensity can be directly measured by the lux-meter, without making calculations because the sensor directly output in Lux (Lx).

Block diagram of BH1750

BH1750 Internal architecture

  • PD : Photo diode with approximately human eye response.
  • AMP : Integration-OPAMP for converting from PD current to Voltage.
  • ADC : AD converter for obtainment Digital 16-bit data.
  • Logic + I2C Interface : Ambient Light Calculation and I2C BUS Interface. It is including below register.
    Data Register : This is for registration of Ambient Light Data. Initial Value is “0000_0000_0000_0000″.
    Measurement Time Register : This is for registration of measurement time. Initial Value is “0100_0101″.
  • OSC : Internal Oscillator (typ. 320 kHz ). It is CLK for internal logic.

BH1750 Specifications

  • Sensor : BH1750FVI (Compact surface mount package 1.6 x 1.6 x 0.55 mm)
  • Power Supply : 3.3V – 5V 
  • Current consumption : 0.12mA
  • Measurement Range : 0 – 65535 lx (Lux)
  • Built-in 16 bit analog (Illuminance) to digital converter
  • Module Size (L x W) : Approx. 3.26 cm x 1.51 cm
  • I2C bus Interface ( f / s Mode Support, Slave Address : “0100011” )
  • No calibration required.
  • Measurement resolution : 1 lux
  • IR radiation has very less effect on the measurements
  • 50Hz/60Hz Light noise rejection function
  • Operating temperature range : – 40°C to 85°C
  • Spectral responsibility is approximately human eye response
  • Light source dependency is little. (ex. Incandescent Lamp. Fluorescent Lamp. Halogen Lamp. White LED. Sun Light)
  • Small measurement variation (+/- 15%)

GY-30 BH1750 Pin-out

BH1750 Pinout

Interface with Arduino

BH1750 interface with Arduino

Arduino Code: To get Lux values on serial monitor

You have to installed required library to use this module’s output values easily in code. In Arduino IDE Menu, go to Sketch > Include Library > Manage libraries and search BH1750. You’ll get multiple libraries in list, we will use BH1750FVI by PeterEmbedded.

First, we will test the module and see the output values on Arduino IDE serial monitor, to ensure the connection & module functionality. Select your Arduino boards & port in Arduino IDE, Upload following code:

After uploading this code, you will see ambient light readings in Lux unit on serial monitor of Arduino IDE at every 1 seconds.

BH1750 Serial Monitor Output

In further, you can refer 16×2 LCD interface tutorial & 128×64 Monochrome OLED tutorial to display Lux readings on LCDs to make it more attractive & user friendly. You can also make Photometer/Lightmeter using this module for photography purpose.

I hope you will learn to use BH1750/BH1750FVI module from this tutorial & it will be helpful to add ambient light intensity measurement in your DIY stuff. You can add this module various projects using where you need to control brightness of background LEDs or ambient light measurement is necessary, in future such projects will be uploaded in #BeatYourBit website. If you like this tutorial, share it with your friends & any Arduino newbie you know. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Like/Follow @beatyourbit on FacebookTwitterInstagram & Telegram for latest updates.


128×64 SSD1306 OLED interface with Arduino (SPI)

Visual interface plays an important role in any embedded or electronics design. It unveils the seamless capabilities of your design by providing visual monitoring. In market, there are varieties of displays are available as per requirement. In earlier tutorial we learned how to interface 16×2 LCD with Arduino. Here in this, we will learn about OLED & it’s interface with Arduino.

OLED-organic light-emitting diode is a type of display which is used in devices such as television screens, computer monitors, portable systems such as smartphones, handheld game consoles, smart bands and PDAs. In OLED, the emissive electroluminescent layer is a film of organic compound that emits light in response to an electric current. This organic layer is situated between two electrodes; typically, at least one of these electrodes is transparent.

An OLED display works without a backlight because it emits visible light. Thus, it can display deep black levels and can be thinner and lighter than a liquid crystal display (LCD). In low ambient light conditions (such as a dark room), an OLED screen can achieve a higher contrast ratio than an LCD, regardless of whether the LCD uses cold cathode fluorescent lamps or an LED backlight. OLED displays are made in the same way as LCDs, but after TFT (for active matrix displays), addressable grid (for passive matrix displays) or ITO segment (for segment displays) formation, the display is coated with hole injection, transport and blocking layers, as well with electroluminescent material after the 2 first layers, after which ITO or metal may be applied again as a cathode and later the entire stack of materials is encapsulated. OLEDs have large fields of view, about 170 degrees. The TFT layer, addressable grid or ITO segments serve as or are connected to the anode, which may be made of ITO or metal. OLEDs can be made flexible and transparent, with transparent displays being used in smartphones with optical fingerprint scanners and flexible displays being used in foldable smartphones

Most common OLED available in market:

Here we will see 128×64 SSD1306 Monochrome OLED (SPI) interface with Arduino. It has 128×64 pixels & SSD1306 driver. It has >160° visual angle, operates on 3.3V ~ 6V & usually available in blue, white & dual color (some upper portion with different color). This OLED has SPI pins & it is mentioned below:

Sr. Pin Name Also known as Function
1 GND Ground   Ground pin of OLED
2 Vdd 5V, 3v3, Vcc   Power pin (3.3V to 5V)
3 SCK D0, CLK, SCL   Works as clock pin, It is used for both SPI & I2C
4 SDA MOSI, D1   Data pin of OLED, It is used for both SPI & I2C
5 RES RESET, RST   To reset OLED, part of SPI configuration
6 DC A0   Data Command pin, part of SPI configuration
7 CS Chip Select   Useful when we have multiple SPI module on same controller

Connection with Arduino

Arduino Pin OLED Pin
3.3V Vdd, Vcc, 3v3
Ground GND
11 DC, A0
12 CS, Chip Select


To getting started with this OLED, you will need libraries for it, here are two libraries recommended:

While using this OLED for the first time, it is recommended to test OLED & connections using examples in Arduino IDE. Go to File > Examples > Adafruit SSD1306 and select  ssd1306_128x64_spi example Upload the example and you can see line, drawing, text, scroll, invert display & snowflakes animation properly; if it is working fine means your connection & OLED both are fine.

Understand functions of this library

The library has various function for different output like start display, clear display, invert display, write text at particular location, show image & custom icons etc.

  • Start display & clear display:

OLED is like a writing pad, you have to inform it to display what you prepared. display.display() function is necessary after you cook something in program which is going to be display in next sequence.

If you write something again in same sketch to display, it will overwrite if you don’t clear the previous thing you displayed. display.clearDisplay() is required for the same.

  • Display a text string:

To display text or text string, you can use above lines, set x & y axis accordingly.

  • Display a value (character variable):

To display any character variable, for example temperature reading or any value, you can use above lines.

  • Draw some symbols like triangle, rectangle, circle:

Use any of the above functions to draw the element you want.

  • To invert color of whole display:

Using display.invertDisplay(true); function you can invert the display color (Black to white & vice versa), it will keep all image/text in inverse color until your code executes  display.invertDisplay(false);. 

Display image on OLED

To display an image on OLED display, the bitmap data must be stored in the program memory in form of PROMGMEM directive. In easy words, we have to instruct the OLED display what to do with each pixel by passing it a sequence or values from an array as shown above. This array will contain the bitmap data of the image. For this, you have to convert your B & W images into monochrome bitmap format with 128×64 pixels dimension. After that, open Image2cpp tool by Jasper van Loenen. This tool converts an image into a bit map values and load them into the array. Upload your 128×64 monochrome bitmap image there, check preview, review settings & check following setting;

Select code output format as ‘Arduino Code’ as shown in image, click ‘Generate code’ button. You will get a character set in window below ‘Generate code’ button. Copy it,  and paste in this code as character array;

Image display code

Select your Arduino board & port in Arduino IDE, upload the sketch & bingooo..!!! You will see the image on OLED display.

You can merge above mentioned functions and combine image with text & shapes. You can download following examples for better understanding.

Demo examples:

Here is one demo of OLED & Arduino:


I hope you will learn to drive your OLED display from this tutorial & it will be helpful to add visual enhancement in your DIY stuff. You can make various projects using such OLED where you need to display text/numbers & images, in future such projects will be uploaded in #BeatYourBit website. If you like this tutorial, share it with your friends & any Arduino newbie you know. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Like/Follow @beatyourbit on FacebookTwitterInstagram & Telegram for latest updates.

4×4 Matrix keypad interface with Arduino (8 Pin method)

Whenever we design any embedded project or gadget, user input is the most important feature to be designed. The user input may contain alphabetical & numerical keys, also some arrow keys for display navigation. You may find keypads in door locks, printers, microwaves, phones, etc. In the case of Arduino, you may find various input interfaces and matrix keypads are most famous among all. A matrix keypad is a set of keys arranged in a matrix pattern that enables more keys in limited pins. A matrix keypad is identified by the number of Column X Row, for ex: 4×4 & 4×3.


Usually, membrane matrix keypad is widely used in various devices, but key mounted PCB keypad is also used in many specific designs, and both of them are working on the same concept. Here you can see the pin-out of 4×4 matrix keypad:

Pin No. 1 2 3 4 5 6 7 8
Raw/Column R1 R2 R3 R4 C1 C2 C3 C4

As you can see, in 4 (Row) x 4 (Column) keypad, there is a total of 16 keys. All these membrane keys are connected to each other with a conductive trace layer below the layer of pad forming a 4×4 matrix grid. Generally, if you want to attach 16 keys, you may need 16 input pins + 1 Ground pin = 17 Pins. But in the case of a 4×4 matrix keypad, it takes only 8 pins. Let’s see the working principle of the 4×4 matrix keypad.

The working principle is as simple as its internal wiring. If you press a button, it will shorten its row with the joining column & the same will allow flowing current between them. For example, if you press ‘6’, R2 & C3 will get shorten. Meanwhile, the assigned microcontroller will be continuously scanning all these lines & will sense the button pressed state.

4×4 Matrix keypad connection with Arduino UNO

Connect the keypad with your Arduino board (We have taken UNO in our case) as shown in the above figure, you can use any digital pins from D2 to D13 (D0 & D1 are avoided as those pins are for onboard UART & advised to not use them for any other purpose than serial communication.

Next, to use this keypad with your Arduino board you will need library for the same. You can install the required library using the library manager in Arduino IDE. Open Arduino IDE, Sketch>Include Library>Manage Libraries and Library Manager will load.

In the Library manager, type ‘keypad’ and wait for the results. For this tutorial, we will use a library ‘Keypad by Mark Stanley, Alexander Brevig’. Select that library from the results and install it.


You can download this sketch from here.

After uploading the sketch to your Arduino board, you can see the output on IDE serial monitor for which key is pressed.

Code Explanation

As you can see in code, after including ‘Keypad.h’ library in the first line we have defined number of rows & columns. It is required because sometimes you may have to use 3×4 or 1×4 keypad too so you can set numbers as per requirement.

Next, a two-dimensional keymap array is defined as ‘hexakeys[ROWS][COLS]’. It contains the characters to be displayed when a particular key is pressed on the keypad.

Characters defined in the code are as per the keypad example we have taken. If you have different characters on your keypad then you can configure the same. For example: If you want to use this keypad as a calculator, you can define the array like this. 

After that, we have to create an object of the library ‘Keypad(makeKeymap(hexakeys), rowPins, colPins, ROWS, COLS )’ which contains five parameters.

makeKeymap(hexakeys) : This parameter is used to make the internal keymap equal to our user-defined keymap.

rowPins & colPins : These are the pins on Arduino where rows & columns of keypad connected.

ROWS & COLS : These are the number of rows & columns of our matrix keypad.

Once the above keypad object is created, we have to use a simple command getKey() to check which key is pressed.

This library contains some of the useful functions which are not mentioned/used in the above example code:

  • setHoldTime(unsigned int time) : This function sets the number of milliseconds the user will have to hold a button until the HOLD state is triggered.
  • setDebounceTime(unsigned int time) : This function sets the number of milliseconds the keypad will wait until it accepts a new keypress or keyEvent.
  • KeyState getState() : This function returns the present state of any of the keys. The four defined states are IDLE, PRESSED, RELEASED & HOLD.
  • char waitForKey() : This function is used to waits forever until someone presses a key. Using this function might be problematic as it blocks all other functions/code/loop until any key is pressed. It means no IO On-Off, no LCD screen updates, no interrupt routines etc.
  • addEventListener(keypadEvent) : This function triggers an event if the keypad is used. For ex: You can use this to blink any LED while any key is pressed.

I hope this tutorial will be helpful to add user input enhancement in your DIY stuff. You can make various projects using such keypad where you need to input text/numbers, in future such projects will be uploaded in #BeatYourBit website. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Subscribe BYB on FacebookTwitterInstagram & Telegram for latest updates.

HC-SR04 Ultrasonic module interface with Arduino

HC-SR04 as known as Ultrasonic sensor is non-contact range detection module used for distance measurement, radar & object displacement etc. It offers high accuracy, steady readings & easy interface pin-out to interface with various microcontroller boards as ultrasonic transceiver. Interfacing HC-SR04 with your Arduino and enhance object detection feature in your DIY project.HC-SR04

Features & Specifications

  • Power Supply :+5V DC
  • Quiescent Current : <2mA
  • Working Current: 15mA
  • Effectual Angle: <15°
  • Ranging Distance : 2 cm – 400 cm / 1″ ­ 13ft
  • Resolution : 0.3 cm
  • Measuring Angle: 30 degree
  • Trigger Input Pulse width: 10uS
  • Dimension: 45mm x 20mm x 15mm
  • Weight: approx. 10 g


HC-SR04 pinout

  • Vcc: +5V DC to power ON the module.
  • Trig: Trigger pin is an Input pin. This pin has to be kept high for 10µs to initialize measurement by sending ultrasonic wave.
  • Echo: Echo pin is an Output pin. This pin goes high for a period of time which will be equal to the time taken for the ultrasonic wave to return back to the sensor.
  • GND: Ground of the system.

As shown above the HC-SR04 Ultrasonic sensor there are 4 pins: Vcc, Trigger, Echo and Ground respectively. This sensor is most popular where measuring distance or sensing objects are required. The module has two components in the front which works as Ultrasonic transmitter and Receiver. The sensor works with the simple formula “Distance = Speed × Time”. The Ultrasonic transmitter transmits an ultrasonic wave, this wave travels in air and when it gets objected by any material it gets reflected back toward the sensor this reflected wave is observed by the Ultrasonic receiver module.

Connection with Arduino

Arduino  HC-SR04
Vcc  Vcc
D09 Trig
D10  Echo
Gnd  Gnd


You can download this code from here.

Open the code in Arduino IDE, upload it & get distance values on serial monitor screen. I hope this tutorial will be helpful for HC-SR04 interface in your Arduino projects. Further in this you can interface LCD to display distance & interface HC-05 bluetooth module to send distance values via bluetooth. Your feedback will be appreciated.

Subscribe BYB on FacebookTwitterInstagram & Telegram for latest updates.

16×2 LCD interface with Arduino

A liquid-crystal display (LCD) is a flat-panel display or other electronically modulated optical device that uses the light-modulating properties of liquid crystals. Liquid crystals do not emit light directly, instead using a back-light or reflector to produce images in color or monochrome. LCDs are available to display arbitrary images (as in a general-purpose computer display) or fixed images with low information content, which can be displayed or hidden, such as preset words, digits, and 7-segment displays, as in a digital clock. They use the same basic technology, except that arbitrary images are made up of a large number of small pixels, while other displays have larger elements. In this tutorial, we are using 16×2 character LCD display where 16 is characters per line & there are two lines. It means each 16×2 LCD can represent 32 characters, you can represent more characters by scrolling the text.


LCD-RearIn this LCD each character is displayed in 5×7 pixel matrix. This LCD has two registers, command & data. Like its name, Command register stores command sent to LCD & data register stores the data to be displayed on LCD. Basically the data is ASCII characters which is sent to be displayed on LCD. For more details about LCD, check here.


  • +Vcc: Supply voltage is 4.7V to 5.3V DC
  • GND: Ground (0V)
  • Contrast: Contrast adjustment of LCD, through variable resistor to +Vcc
  • RS: It means ‘Register Select’, Selects command register when low & command register when high
  • RW: It means ‘Read/Write’, Low to write the register and high to read from register
  • EN: It means ‘Enable’, sends data to data pins when a high to low pulse is given.
  • D0 to D7: 8 bit data pins
  • Back-light+ : Vcc (+5V) for LCD back-light
  • Back-light- : Ground (0V) for LCD back-light

Connection with Arduino UNO R3

There are two methods to interface 16×2 LCD with Arduino:

  1. Connect all pins of LCD to Arduino
  2. Use I2C module and connect to Arduino by two pins only

In first method, RS, R/W, EN and Data pins will be connected to Arduino;

As shown in above image, contrast pin is connected with pin 6 of Arduino hence contrast will be adjusted by value set in code. In the program ‘LiquidCrystal’ library so make sure you have same library installed in your Arduino IDE. (You can install libraries from Sketch>Include library>Manage libraries)

Code for direct connection method:

You can download above code from here.

In another method, an I2C module will be connected to LCD. By using I2C module only two pins SDA (Serial Data) & SCL (Serial Clock) will be used from Arduino so less wiring for this. LCD will receive commands from Arduino by I2C protocol

As shown in above image, I2C module is connected to LCD directly (For safer side, solder a female header strip on LCD and connect I2C on that so if somehow I2C module or LCD stops working then it can be easily replaced). You can connect multiple I2C device parallely on same pin. Actually A4 & A5 pins are SDA & SCL so same can be connected on A4 & A5 too(Check Arduino pinout first). There will be a jumper on I2C module which is used to turn on-off LCD backlight. You will find a potentiometer which is actually contrast set for LCD.

Code for I2C connection method:

You can download above code from here.

I2C module & its interface with LCD looks like this:

One more difference between both connection type is library. You need different library for I2C which is ‘LiquidCrystal_I2C’ and it is available here.

Before proceeding for I2C code download, you need to confirm I2C address. Each I2C module has an address which we need to mention in second line LiquidCrystal_I2C  lcd(0x3F, 16, 2); Here i’ve mentioned 0x3F because my I2C module has this address. To know your I2C module address you may need to run I2C scanner program in your Arduino and get I2C address on serial monitor like ths;

I2C scanner

Use this tutorial to know the address of your I2C device. Get I2C address, put in above code & eureka…!!!

After connecting LCD with Arduino you can display sensor & variable values, text messages & also can set values by interfacing keypad with Arduino. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Join on FacebookTwitterInstagram & Telegram for latest updates.

Temperature & humidity sensor DHT11 interface with Arduino

DHT11 is a cheap & easy option for temperature & humidity measurement for DIY projects & beginner experiments. It is likely suitable for domestic environment control, weather monitoring unit & gardening/farming monitoring stations. It uses a capacitive humidity sensor and a thermistor to measure the surrounding air, gives output as digital signal which can be connected to Arduino digital IO pin directly. The only drawback of DHT11 is slow response for updated values. You can download DHT11 datasheet from here.

Technical Specifications

  • Operating Voltage: 3V to 5.5V DC
  • Current consumption: Measurement 0.3mA, standby 60μ A
  • Accuracy: At 25℃, ± 2℃ & ± 5% RH
  • Sampling period: more than 2 seconds
  • Measurement Range: 20-95% RH & 0-50℃
  • Resolution: 8 Bit for temperature & 8 Bit for humidity
  • Response time: 6 to 15 seconds for humidity & 6 to 30 seconds for temperature.

The DHT11 measures relative humidity which means the amount of water vapor in air vs. the saturation point of water vapor in air. At the saturation point, water vapor starts to condense and accumulate on surfaces forming dew. The saturation point changes with air temperature. Cold air can hold less water vapor before it becomes saturated, and hot air can hold more water vapor before it becomes saturated.


DHT11 module available in market is having 3 pins, actually sensor is having 4 pins but module designed to connect with arduino easily by removing 1 pin which is not required (Few makers sell module with 4 wire). Connections shown in diagram is as below:

(Colors are mentioned for reference only, Refer pin numbers & connect wires carefully)

Test Code

You can download this code from here.

How this code works: As mentioned in code, pin no. 7 is defined as DHT11_PIN variable. In setup loop, baud rate is assigned at 9600 to read DHT11 values on serial monitor available in Arduino IDE software. Next loop is written to move DHT11 values in variable and print on serial monitor. Just copy the code and paste in Arduino IDE, set your Arduino board & COM Port, upload it, here you go with values on serial monitor. So, it is too easy to get temperature & humidity using DHT11 sensor. For further expansion, you can connect LCDs, OLEDs to display and can send data wireless using HC-05 Bluetooth sensor and many more wireless options.

I hope this tutorial will be helpful for basic temperature & humidity measurement. In future you can interface LCD and wireless interfaces with this type of sensors. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Subscribe BYB on FacebookTwitterInstagram & Telegram for latest updates.

HC-05 Serial Bluetooth Module interface with Arduino

HC‐05 bluetooth module is an easy to use Bluetooth SPP (Serial Port Protocol) module, designed for transparent wireless serial connection setup & can easily interface with Arduino. The HC-05 Bluetooth Module can be used in a Master or Slave configuration, making it a great solution for wireless communication, especially for Arduino. This serial port Bluetooth module is fully qualified Bluetooth V2.0+EDR (Enhanced Data Rate) 3 Mbps Modulation with complete 2.4 GHz radio transceiver and base-band. It uses CSR Bluecore 04External single chip Bluetooth system with CMOS technology and with AFH (Adaptive Frequency Hopping Feature).


The Bluetooth module HC-05 is a MASTER/SLAVE module. By default the factory setting is SLAVE. The Role of the module (Master or Slave) can be configured only by AT commands. The slave modules cannot initiate a connection to another Bluetooth device, but can accept connections. Master module can initiate a connection to other devices. The user can use it simply for a serial port replacement to establish connection between MCU and GPS, PC to your embedded project, etc. Refer Datasheet/User Manual & AT command’s list.


  • Typical ‐80 dBm sensitivity
  • Up to +4Bm RF transmit power
  • 3.3 to 5 V I/O and RoHS Compliant
  • PIO (Programmable Input/Output) control
  • UART interface with programmable baud rate
  • Inbuilt/Integrated antenna
  • Auto‐connect to the last device on power as default
  • Permit pairing device to connect as default
  • Auto‐pairing pin code: ”1234” as default (which can be changed)
  • CSR Bluetooth Chip Solution
  • Bluetooth Spec v2.0 EDR Compliant with V2.0.E.2 of specification for both 2Mbps and 3Mbps modulation modes
  • Full Speed Bluetooth Operation with Full Piconet Support and Scatternet Support
  • Support for 8Mbit External Flash On-board
  • Support for 802.11 Coexistence


HC05 Pin

State: It is status indicator pin. When the HC05 is not connected to or not paired with any other Bluetooth device, signal at this pin goes Low. During this state the on-board LED flashes continuously which indicates that the module is not paired with any device. When HC05 is paired or connected with any Bluetooth device, the pin status goes High. During this state, on-board LED blinks with a constant delay say for example 2 seconds delay which indicates that the module is paired.

RXD: Receive pin of UART interface for communication

TXD: Transmit pin of UART interface for communication

GND: Ground pin

Vcc: Supply voltage of 3.3V or 5VDC

Key (or EN): When this pin is high, the module is disabled & will not be connected with any module. When this pin is open or connected to ground or kept open, the module is enabled & it can be connected/communicate.

Apart from pins, you will find a small push button on HC05. When you press the button for 1 second, HC05 will enable AT command mode. During AT command mode you can change different parameters of HC05, but while changing parameters the HC05 shouldn’t be connected/paired with any device.

Arduino Connection

HC05 Arduino
Vcc 5V

Normally, people connects HC05 TXD & RXD to Arduino RX(D0) & TX(D1), but in that case if you want to upload any code using USB port then you have to remove connection from D0 & D1 otherwise you will get code upload error. To avoid this issue there is one best solution as library called ‘SoftwareSerial’. Using  SoftwareSerial library we can configure any two DIO as Tx & Rx. In above connection diagram, HC05 Tx & Rx are connected to Arduino pins D10 & D11 which to be assigned as Rx & Tx respectively.

Arduino Code

You can download above code from here.

Explanation of code:

#include : As you can see SoftwareSerial library is included, it is available in Arduino IDE

SoftwareSerial BTserial(10, 11); : anyname(RX, TX); i’ve give name BTserial, D10 pin as RX & D11 as Tx

char data; : variable where incoming data will be stored, for better execution data will be first stored in a variable then will be processed.

Serial.begin(9600); begin serial communication with Arduino IDE

Serial.println(“Beat Your Bit”); print custom message on serial monitor to confirm serial communication has been initiated

BTserial.begin(9600); begin serial communication using dedicated pins (D10 & D11)

BTserial.println(“Beat Your Bit”); transmit custom message on HC05 paired device to confirm serial communication with HC05 has been initiated

if (BTserial.available()) [if any data available from HC05 then]; [store received data in ‘data’ variable]
Serial.print(data); [print received data on serial monitor of Arduino IDE]
if (Serial.available()) [if any data available from serial monitor then]; [store received data in ‘data’ variable]
BTserial.print(data); [transmit received data on HC05]

As explained, this code exchanges data between HC05 and Arduino IDE serial monitor. We can see data received on serial monitor but to read the data received on HC05, we have to use an android app or any terminal application which can be connected with HC05 using Bluetooth. Here we are going to use android app to test Arduino-HC05 connection & data exchange. I used Arduino Bluetooth Control app which have many add on features & easy to use. It has serial terminal, arrow keys, buttons, slider, accelerometer & voice control features.

Connect circuit as shown in connection diagram, upload code and connect/pair HC05 with your smartphone. If you are using/pairing HC05 for first time then default pairing PIN may be 1234, you can change it later using AT commands. Open Arduino Bluetooth Control App & select paired HC05. Open terminal windows in app & serial monitor in Arduino IDE with mentioned baud-rate. Write any text in Arduino IDE serial monitor & press enter, you will receive same text in terminal window of Arduino Bluetooth Control app. Vice versa, write in app and send it to Arduino IDE serial monitor.

Change HC05 settings

You can change HC05 default settings like Bluetooth display name, pairing PIN, baud rate etc. As mentioned in Pin-out details, you have to put HC05 in AT command mode by pressing the push button while power up the module but make sure it is not connected with any other Bluetooth device.

How to put HC05 in AT command mode: 

1. Disconnect HC05 form power, Remove the +5V connection to HC05.
2. Press and hold the push button switch on HC05
3. Re-connect HC05 Vcc to +5V (while still pressing the button switch), HC05 on-board LED should turn ON.
4. Release the push button switch and the LED should be blinking at interval of two seconds. It indicates that your are now in AT command mode. Now open serial monitor & give AT commands from there.

Some useful AT commands:

AT : Simple feedback request. If communication is working fine then it will return “OK”

AT+VERSION : This returns the firmware version.
For Example:

AT+STATE : This returns the current state of the module.
For Example:

AT+ROLE : Valid values are 0~Slave, 1~Master, 2~Slave-Loop.
Return example:
(To change to Master Mode, enter AT+ROLE=1, returns “OK”)

AT+UART : It returns the baud rate used by the HC05 in communication mode. Default it will be 9600 mostly.
Return example:
(To change the baud rate to 19200 : AT+UART=19200,0,0. Returns “OK”)

AT+NAME : The command AT+NAME? only works in AT command mode. If HC05 is not responding on AT+NAME? then put HC05 in AT command mode as procedure mentioned in tutorial.
Return when AT+NAME? is given:
(To change name : AT+NAME=BeatYourBit, Returns “OK”)

You can find all AT commands list from here.

I hope you liked this tutorial, now you can add Bluetooth interface in your project & expand the features. Further you can display values on display, data exchange with another wireless modules like RF & WiFi. Give your feedback about this tutorial in Contact, Your feedback will be appreciated.

Subscribe BYB on FacebookTwitterInstagram & Telegram for latest updates.