Concept:
For this assignment, I decided to implement the things that I have already learned in regards to the ultrasonic sensor and add the button. I wanted to see how far I can go with my knowledge.
Implementation:
The implementation was pretty easy, as I have used the previous assignment as an example. I just added the button and changed the code and voila!
End result:
Code:
//Intro to IM - Stefania Petre // Define LED pins int ledPin[3] = {8}; // Define Ultrasonic sensor pins const int trigPin = 2; // or any other unused digital pin const int echoPin = 3; // or any other unused digital pin const int buttonPin = 13; int buttonState = HIGH; int lastButtonState = HIGH; long lastDebounceTime = 0; long debounceDelay = 50; int pushCounter = 0; int numberOfLED = 3; void setup() { pinMode(buttonPin, INPUT); digitalWrite(buttonPin, HIGH); // Activate internal pull-up resistor // Set up LED pins for (int i = 0; i < numberOfLED; i++) { pinMode(ledPin[i], OUTPUT); } // Set up Ultrasonic sensor pins pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT } void loop() { int reading = digitalRead(buttonPin); // Check if the button state has changed if (reading != lastButtonState) { // Reset the debounce timer lastDebounceTime = millis(); } // Check if the debounce delay has passed if ((millis() - lastDebounceTime) > debounceDelay) { // If the button state has changed, update the button state if (reading != buttonState) { buttonState = reading; // If the button state is LOW (pressed), increment pushCounter if (buttonState == LOW) { pushCounter++; } } } // Update the last button state lastButtonState = reading; // Turn off LED for (int i = 0; i < numberOfLED; i++) { digitalWrite(ledPin[i], LOW); } // Perform Ultrasonic sensor reading long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration * 0.0343) / 2; // Calculate distance in cm // Perform actions based on distance measured if (distance < 30) { // Turn on LED digitalWrite(ledPin[0], HIGH); // Delay before next iteration delay(100); // Adjust as needed }
Comments:
Even though I got it to work, I still would have liked it to change colors depending on the distance from the sensor. I will try to implement that next time!