//-----------------------------------------------------------------
// Author: RSP @KMUTNB
// Date: 2023-02-09
//-----------------------------------------------------------------
// Don't forget to include libraries
#include <Adafruit_NeoPixel.h>
#include <LiquidCrystal_I2C.h>
#define BTN_PIN (6)
#define AIN_PIN (A0)
#define PWM_PIN (9)
#define NEOPIXEL_PIN (5)
#define ECHO_PIN (2)
#define TRIG_PIN (4)
#define I2C_ADDR (0x27)
Adafruit_NeoPixel pixels( 8, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
LiquidCrystal_I2C lcd( I2C_ADDR, 16, 2 );
void setup() {
Serial.begin(115200);
Serial.println( F("Arduino Nano Demo...") );
Serial.println( F("- Analog input reading (potentiometer)") );
Serial.println( F("- PWM LED dimming") );
Serial.println( F("- Push button") );
Serial.println( F("- LCD16x2 I2C display module") );
Serial.println( F("- 8-pixel NeoPixel RGB ring") );
pinMode( BTN_PIN, INPUT_PULLUP );
pinMode( TRIG_PIN, OUTPUT );
pinMode( ECHO_PIN, INPUT );
pinMode( PWM_PIN, OUTPUT );
digitalWrite( TRIG_PIN, LOW );
digitalWrite( PWM_PIN, LOW );
pixels.begin(); // Initialize Neopixel ring
pixels.clear(); // Clear Neopixel ring
lcd.init(); // Initialize LCD display
lcd.backlight(); // Turn on LCD backlight
Wire.setClock(400000);
}
void loop() {
static uint8_t disp_mode = 0;
// 1) Detect a button press to toggle LCD display mode
if (digitalRead(BTN_PIN) == LOW) {
while (!digitalRead(BTN_PIN)) {
delay(5);
}
disp_mode = (disp_mode + 1) % 2;
}
// 2) Send a Trigger pulse
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(20);
digitalWrite(TRIG_PIN, LOW);
// Measure a pulse width
uint32_t duration_us = pulseIn(ECHO_PIN, HIGH, 25000 /*timeout*/ );
uint32_t distance_cm = (duration_us / 2) * 343 / 1000;
// 3) Read a value from the analog input pin
int adc_value = analogRead( AIN_PIN );
// 4) Update the duty cycle of PWM
int pwm_value = adc_value / 4;
analogWrite( PWM_PIN, pwm_value );
// 5) Update the colors of NeoPixels
String indicator = "";
for (int i = 0; i < 8; i++) {
uint8_t level = (pwm_value + 16) / 32;
uint8_t onoff = (i < level);
indicator += onoff ? '>' : ' ';
pixels.setPixelColor(i, onoff ?
pixels.Color(200, 0, 0) :
pixels.Color(0, 0, 0) );
}
pixels.show();
// 6) Update the LCD display
if (disp_mode) {
char lcd_buf1[16], lcd_buf2[16];
sprintf( lcd_buf1, "ADC: %04d (10b)", adc_value );
sprintf( lcd_buf2, "LED: |%s", indicator.c_str() );
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(lcd_buf1);
lcd.setCursor(0, 1);
lcd.print(lcd_buf2);
}
else {
String str1, str2;
str1 = " PW[us]: ";
str1 += duration_us;
str2 = "Dist.[cm]: ";
str2 += distance_cm / 10;
str2 += '.';
str2 += distance_cm % 10;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print( str1.c_str() );
lcd.setCursor(0, 1);
lcd.print( str2.c_str() );
}
delay(200);
}
//-----------------------------------------------------------------