#define TRIG_PIN 4 #define ECHO_PIN long duration; float cm, inches; #include #ifdef __AVR__ #include // Required for 16 MHz Adafruit Trinket #endif // Which pin on the Arduino is connected to the NeoPixels? #define PIN 3 // On Trinket or Gemma, suggest changing this to 1 // How many NeoPixels are attached to the Arduino? #define NUMPIXELS 3 // Popular NeoPixel ring size // When setting up the NeoPixel library, we tell it how many pixels, // and which pin to use to send signals. Note that for older NeoPixel // strips you might need to change the third parameter -- see the // strandtest example for more information on possible values. Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); #define DELAYVAL 500 // Time (in milliseconds) to pause between pixels void setup() { Serial.begin(115200); // ESP32 usually uses higher baud pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) } void loop() { // Clean trigger digitalWrite(TRIG_PIN, LOW); delayMicroseconds(5); // Send pulse digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Read echo duration = pulseIn(ECHO_PIN, HIGH); // Convert to distance cm = (duration / 2.0) / 29.1; inches = (duration / 2.0) / 74.0; pixels.clear(); // LED control if (cm < 18) { pixels.setPixelColor(0, pixels.Color(0,255, 0)); pixels.show(); // Send the updated pixel colors to the hardware. } else { pixels.setPixelColor(0, pixels.Color(255,0, 0)); pixels.show(); } // Print Serial.print(inches); Serial.print(" in, "); Serial.print(cm); Serial.print(" cm"); Serial.println(); delay(50); }