An Arduino UNO example that measures the time a pushbutton is pressed. Has the possibility to use these durations to trigger different actions.
Dietrich_3 153 Junior Poster
/* LCD_I2C_button_timing.ino
Measure the time a button is pressed in milliseconds,
show duration using a LCD 16x2 (I2C) Liquid Crystal display.
Connnect a pushbutton (can be module) between GND and pin 7,
keep this pin high using its internal pullup resistor
Different durations can be used to trigger different actions.
The display has 4 pins on the left section
(top to bottom)
1 ground
2 +5V
3 signal SDA to arduino pin SDA or A4
4 signal SCL to arduino pin SCL or A5
VegasEat 16sep2026
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // 0x27 or maybe 0x3F
// use board's builtin LED = LED_BUILTIN
int led_pin = 13;
int button_pin = 7;
unsigned long duration;
// gets value from millis() when the switch is pressed
unsigned long startTime;
void setup() {
// a pushbutton is connected to pin 7, this pin is set HIGH
// using its internal pullup resistor, button-press will make it LOW
pinMode(button_pin, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
lcd.init();
// must turn on backlight
lcd.backlight();
// show some text
// column = 0, row = 0 by default
lcd.print("Button pressed:");
}
void loop() {
// check if button is pressed
if (digitalRead(button_pin) == LOW) {
startTime = millis();
// turn on the LED
digitalWrite(LED_BUILTIN, HIGH);
// wait while the button is still pressed
while (digitalRead(button_pin) == LOW)
;
duration = millis() - startTime;
// set the cursor to (column=0, row=1):
lcd.setCursor(0, 1);
lcd.print(duration);
lcd.print(" millisec");
}
// turn off the LED
digitalWrite(LED_BUILTIN, LOW);
} Edited by Dietrich_3
Dietrich_3 153 Junior Poster
In my honest opinion, OLED is so much easier to use than LCD display technology, for just a few bucks more!
Here is an example with lots of pertinent comments added by myself. Have fun!
/* OLED_animate.ino
Arduino + OLED display combo is one of the cleanest ways to show text, sensor data, or
graphics on your projects. The most common module is the 0.96" 12864 SSD1306 I2C OLED,
which uses only four wires and works on both 3.3V and 5V.
Test some text sizes, shapes and animation
with good help from 'Copilot'
Has 4 pins (l to r):
1 GND
2 VCC +5V
3 SCL I2C clock line to UNO pin A5
4 SDA I2C data line to UNO pin A4
sometimes GND and +5V are reversed, should be marked
Typical I2C address: 0x3C (sometimes 0x3D)
Install via Arduino IDE Library Manager:
Adafruit SSD1306
Adafruit GFX for graphics
If port is not found unplug/replug USB
tested with Arduino Nano ESP32
VegasEat 17sep2026
*/
#include <Wire.h>
// use Adafruit_GFX.h first
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_ADDR 0x3C
// create instance/object
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);
void setup() {
Wire.begin();
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
for (;;)
; // Freeze/wait if OLED not found
}
display.clearDisplay();
// size 1 allows 21 characters/line (6 pixels/char, 8 lines)
// size 2 allows 10 characters/line (12 pixels/char, 4 lines)
// size 3 allows 7 characters/line (2 lines full)
// any excees wraps to the next lines
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
// x, y coordinates in pixels
display.setCursor(0, 0);
// check lines with this...
display.println("123456789012345678901234567890");
// displays numeric values too
display.println(3.14);
// show it
display.display();
delay(3200);
display.clearDisplay();
// some example shapes ...
// create rectangle x, y, w, h, color
// x, y coordinates of ULC values in pixels
display.drawRect(10, 10, 108, 44, SSD1306_WHITE);
// create a circle x, y, radius, color
// x, y coordinates of center values in pixels
display.fillCircle(64, 32, 10, SSD1306_WHITE);
display.display();
delay(2200);
}
void loop() {
// animation moving a small circle
static int x = 0;
display.clearDisplay();
// create a circle x, y, radius, color
// x, y coordinates of center
display.fillCircle(x, 32, 5, SSD1306_WHITE);
// update
display.display();
x++;
// start x over if right edge is hit
if (x > SCREEN_WIDTH) x = 0;
// small delay to animate smoothly
delay(20);
} Dietrich_3 153 Junior Poster
Most sensor assortments for the Arduino contain a DHT11 tmeperature and humidity sensor. This example will test it out, showing the results on an OLED display. Just about any Arduino UNO version will do, even the tiny Nano ESP32. The line Serial.println(humidity); was used for testing.
/* DHT_OLED_adafruit.ino
Display temperature and humidity on an OLED display.
Using the DHT11 Temperature and Humidity Sensor
(3pin circuit board module with blue perforated box)
temperature/humidity sensor type DHT11:
Temperature range: -20 to 60C (+/-1C),
Relative humidity: 5 to 95% (+/-5%),
Supply voltage: 3.3V or 5V
has a built-in 10 K ohm pull up resistor
Resolution 16bit
Read the markings on the module board (l to r)
1 GND
2 Data to a UNO digital pin
3 VCC
Install the DHT.h header file using the library manager
(Tools tab) search for dht11 and select the "DHT sensor
library" from Adafruit. Install the latest version and
also use "install all".
Display the data on an OLED display panel:
The 128x64 pixel OLED display uses an SSD1306 driver.
White Color 0.96 Inch Oled Display Module 128*64 I2C
Display has 4 pins (l to r):
1 VCC
2 GND
3 SCL I2C clock line to UNO pin A5
4 SDA I2C data line to UNO pin A4
For the possible graphics routines:
Install the "Adafruit GFX" library (install all)
For the OLED display panel:
Install the "Adafruit SSD1306" library
optional ...
degree_symbol = " \xC2\xB0"
Vegasat 18sep2026
*/
#include "DHT.h"
#define DHTPIN 2 // use Arduino digital IO pin 2
#define DHTTYPE DHT11
// class instance is TH (name is up to you)
DHT TH(DHTPIN, DHTTYPE);
// needed to use the I2C bus
#include <Wire.h>
// if you want to use graphics too
//#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width in pixels
#define SCREEN_HEIGHT 64 // OLED display height in pixels
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO: A4(SDA), A5(SCL)
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
// define an object (class instance)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
Serial.begin(9600);
TH.begin();
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop/wait forever
}
}
// main loop
void loop() {
// build the buffer
displayTempHumid();
// actually display what is in the buffer
display.display();
// DHT11 requires a delay > 1 sec
delay(1500);
}
void displayTempHumid() {
float tempC = TH.readTemperature();
// the Adafruit DHT.h does the conversion C to F
float tempF = TH.readTemperature(true);
float humidity = TH.readHumidity();
// clear the buffer
display.clearDisplay();
// set the color, always use white with monochrome displays
display.setTextColor(WHITE);
// set text font size
display.setTextSize(2);
// set the cursor coordinates
// x = 0, line y =0
display.setCursor(0, 0);
display.print(humidity);
display.print(" %RH");
Serial.println(humidity);
// x = 0, line y = 10
display.setCursor(0, 20);
display.print(tempC);
display.print(" C");
// x = 0, line y = 20
display.setCursor(0, 40);
display.print(tempF);
display.print(" F");
} Edited by Dietrich_3
Dietrich_3 153 Junior Poster
The HC-SR501 Motion Detector is included in many Arduino sensor kits. It is recognizable by its dome shaped white plastic Fresnel lens. It detects any infra red emitting moving object. Pets, humans yes, but no ghosts! The sensor pairs up very well with any Arduino UNO or Nano.
You must have heard the story about the person getting into a dark room, frantically waving arms, only to find out that the room had an ordinary light switch.
/* MotionDetector_HC-SR501.ino
This small sensor is included in many sensor assortments, recognizable
by its dome shaped white plastic Fresnel lens. The board has a built-in
integrated circuit that handles all the logic and timing. The unit
draws very little idle current (0.05 mA)
The SR501 PIR detects infrared changes and interprets the motion.
The device requires a one minute warm-up time after power is connected.
It will detect motion inside a 110 degree cone with a range of
3 to 7 meters. Any motion turns the sensor signal +3.3V HIGH.
The module has two orange trim pots, the right side trim pot adjusts the
viewing distance. Full clockwise is 3 meters, full counter-clockwise
is 7 meters. The left trim pot adjusts the time delay. Full clockwise
is a 5 minute delay. Full counter-clockwise sets the delay to 3 seconds.
There is also a yellow jumper on the far right side. Jumper to the front
starts the time delay immediately upon motion detection, then blocks
any further detection. Jumper to the rear will start the time delay
every time motion is detected. Play with that to get most comfortable.
On the back side are three pins (left to right. front pin side up):
1 +5VCC
2 signal (to an Arduino digital IO pin)
3 GND
Some PIR modules have wires included.
Suggested wire colors GND(brown), signal(orange), +5V(red)
VegasEat 18sep2026
*/
int ledPin = 13; // LED_BUILTIN is LED on Pin 13 of Arduino
int pirPin = 7; // HC-S501 signal to an Arduino digital IO pin
int pirStatus; // will be 0V LOW or +3.3V HIGH
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(pirPin, INPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
pirStatus = digitalRead(pirPin);
// LED turns on whenever motion is detected
digitalWrite(ledPin, pirStatus);
// also...
// you can make noise with an 'active buzzer' or
// a use a relay module to turn on a light
} Annie warner 8 Light Poster
Absolutely! Arduino is a great way to turn a computer from something that only processes information into something that can actually interact with the physical world. I especially like how beginner-friendly it is. Being able to start with simple sensors and gradually move into motors, automation and more makes it a fun project for learning.
Dietrich_3 commented: I agree, it is fun! +4
Dietrich_3 153 Junior Poster
The HC-SR04 Distance Sensor looks like a pair of eyes. It does not use light, it uses sonar, more correctly Ultra Sound to measure distances. Each 'eye' contains a membrane speaker/microphone. One is a transmitter called 'Trigger' and the other a receiver called 'Echo'. The Trigger sends out a pulse of 40 kHz ultra sound (beyond human hearing), whose echo comes back to the Echo receiver. A set of ICs times the duration, which relates to the distance. The Arduino does the calculation based on the speed of sound. The result is fairly accurate within a range of 2 to 400 cm.
/* OLED_HC-SR04_distance.ino
HC-SR04 distance sensor connections:
Vcc pin to +5V
Trigger pin to an Arduino digital IO pin
Echo pin to an Arduino digital IO pin
GND pin to GND
Most commonly send a 10 microsecond 40 kHz pulse to the HC-SR04
trigger pin.
The Echo pin receives the echo of this pulse, the duration timing
relates to the distance travelled. Only the return trip is used,
so half the total time:
distance = (echo_pulse_time/2) * speed of sound
If the speed of sound is given in cm/microsecond, then the distance
will be in cm.
At 20C the speed of sound is 343m/sec or 0.0343 cm/microsec
distance_cm = (500/2)*0.0343
Use a box with smooth walls in front of sensor, check
distance (membrane location) with a ruler to see if it matches.
The 128x64 pixel OLED display uses an SSD1306 driver.
White Color 0.96 Inch Oled Display Module 128*64 I2C
Serial bus (from Walmart ca. $18).
Has 4 pins (l to r):
1 GND
2 VCC +5V
3 SCL I2C clock line to UNO pin A5
4 SDA I2C data line to UNO pin A4
In case you haven't done it yet...
For any graphics routines:
Install the "Adafruit GFX" library
For the OLED display panel:
Install the "Adafruit SSD1306" library
"install all" installs both
Vegaseat 19sep2026
*/
// needed to use the I2C bus for the OLED display
#include <Wire.h>
// use OLED library header
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width in pixels
#define SCREEN_HEIGHT 64 // OLED display height in pixels
// The pins for I2C are defined by the Wire-library.
// On an Arduino UNO/Nano: A4(SDA), A5(SCL)
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
// define an object (class instance)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define trigPin 12 // UNO digital IO pin 12
#define echoPin 11 // UNO digital IO pin 11
float duration, distance_cm, distance_inch;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// SSD1306_SWITCHCAPVCC = generate display voltage of 3.3V internally
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // stop, loop/wait forever
}
}
void loop() {
// get the sensor values
displayDistance();
// show them
display.display();
}
void displayDistance() {
// initiate trigger pin LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// send a 10 microsecond long 40 kHz ultra sound pulse
// via the HC-SR04 trigger pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// then measure the response time for the echo
duration = pulseIn(echoPin, HIGH);
// calculate distance...
// divide by 2 since sonar had to go forth ad back
// speed of sound is 0.0343 cm/microsecond in 20 degC air
distance_cm = (duration / 2) * 0.0343;
// there are 2.54 cm per inch
float distance_inch = distance_cm / 2.54;
// set the color, use white with monochrome displays
display.setTextColor(WHITE);
// set text/font size
// size 2 are 10 char, about 18 pixels high
display.setTextSize(2);
// clear the buffer
display.clearDisplay();
// sensor range is specified as 2 to 400 cm
if (distance_cm >= 400 || distance_cm <= 2) {
display.setCursor(0, 0);
display.print("Range?");
} else {
// set the cursor coordinates
// x = 0, y = 0 ULC
display.setCursor(0, 0);
// round to 1 decimal
display.print(distance_cm, 1);
display.print(" cm");
// uses 20 pixels/line to display characters well
display.setCursor(0,20);
display.print(distance_inch, 1);
display.print(" inch");
}
// update display 1000 ms = 1 sec apart
delay(1000);
} Dietrich_3 153 Junior Poster
The Arduino UNO has a good number of C++ based functions available through its Arduino IDE. Just check
https://docs.arduino.cc/language-reference/ if you are curious.
The older UNO R3 is a little limited in memory, but the UNO R4 has removed that concern, so you can write much longer C++ code.
The Arduino engineers in Italy have not sat still, they went to bed with Qualcomm and basically added a Qualcomm Dragonwing QRB2210 chip running Debian Linux on the Arduino R4 WiFi board and increased memory drastically to several Giga Bytes. A full version of Python3 is also on board. The two systems can 'talk' to each other. They call the whole thing an 'Arduino UNO Q', the price is an affordable $55. I have mine on order to evaluate.
The best of two worlds, you can still use C++ for the R4, but also Python to handle data generated.
Edited by Dietrich_3
Dietrich_3 153 Junior Poster
In the distance measurement with ultra sound there is a bobo in the remarks, I meant to say:
At 20C the speed of sound is 0.0343 cm/microsec, duration in microsec
distance_cm = (duration/2)*0.0343
This way the dimensions come out correctly, a rule of Physics!
Edited by Dietrich_3
Dietrich_3 153 Junior Poster
If you play around with Arduino computer interface boards, you most likely have also invested a few bucks in a sensor assortment. On a number of these tiny sensor boards the bottom half looks much the same. The blue plastic box with a small screw is a potentiometer that adjusts the threshold voltage to the 8 pin integrated circuit next to it. That IC is a comparator whose output flips LOW to HIGH at the threshold set. There is a tiny red LED turning on when HIGH just below the potentiometer. If you are lucky, you have one of those eyeglass repair screwdrivers needed for the adjustment.
The top half of the sensor board shows the actual sensing element. Some are easy to figure out. If it look like a microphone in a round metal container, then it will sense sound. A shiny black thing with two wires is most likely a temperature sensor. Another has a black plastic body with shiny metal through its center, that is a finger touch sensor. A dome shaped black item with 2 wires will be the flame sensor. A black rectangular plastic thing with 3 wires could be a Hall effect sensor that measures the strength and polarity of a magnetic field near it.
These sensors are quite sophisticated for a mere 50 cents a piece. The best place to get information (with pictures) is:
https://arduinomodules.info/
Dietrich_3 153 Junior Poster
One of the items in the sensor assortment was a gated laser diode. So right now I am shooting those red laser beams, familiar from the James Bond movies, through my office. Hoping to avoid them through proper gymnastics.
The Arduino UNO can impose some kind of Morse code onto the beam.
Edited by Dietrich_3
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.