int ledMark = 2; // The first LED corresponds to digital pin 2 on the board int num = 5; // Number of LEDs
voidsetup() { for (int i = ledMark; i < ledMark + num; i++) { pinMode(i, OUTPUT); // Set digital pins 2 to 6 as output mode } }
voidloop() { for (int i = ledMark; i < ledMark + num; i++) { digitalWrite(i, HIGH); // Set the corresponding digital pin to HIGH, turning on the LED gradually from the positive direction delay(200); // Delay 200ms digitalWrite(i, LOW); delay(100); } for (int i = ledMark + num - 2; i > ledMark; i--) { // Note that the last LED does not need to be turned on again digitalWrite(i, HIGH); // Set the corresponding digital pin to HIGH, turning on the LED gradually from the reverse direction delay(200); // Delay 200ms digitalWrite(i, LOW); delay(100); } }
The 1602 LCD screen displays the team name and distance measurement results (in centimeters). The servo motor will rotate at an angle based on the distance measurement results; the larger the distance, the greater the rotation angle. When unable to measure the distance (set to be greater than 50cm), the screen will display ‘Too far,’ and the servo motor will return to its original position.
#include<LiquidCrystal.h> #include<Servo.h> #define PIN_SERVO 10 Servo myservo; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define TrigPin A0 #define EchoPin A1 // Pin setting of ultrasonic sensor int count = 0; long duration; // PULSE WIDTH
voidsetup() { lcd.begin(16, 2); // Set up the LCD's number of columns and rows Serial.begin(115200); // Set Serial communication pinMode(TrigPin, OUTPUT); // Set pin mode pinMode(EchoPin, INPUT); digitalWrite(TrigPin, LOW); // Initialize pin delay(1); myservo.attach(PIN_SERVO); myservo.write(0); // Initialize the servo position }
voidloop() { lcd.clear(); // Clear screen information lcd.print("Team Pineapple"); // Output team name on the first line lcd.setCursor(0, 1); // Set the cursor to column 0, line 1 lcd.print("Distance:"); // Output distance information on the second line
delay(300); long IntervalTime = 0; // Define a time variable digitalWrite(TrigPin, HIGH); // Set high level delayMicroseconds(15); // Delay 15us digitalWrite(TrigPin, LOW); // Set low level IntervalTime = pulseIn(EchoPin, HIGH); // Sample the width of the feedback high level using the built-in function, in microseconds float S = IntervalTime / 58.00; // Calculate distance in centimeters using floating-point arithmetic if (S > 50) { lcd.print("Too far"); // If the distance is greater than 50cm, print "Too far" myservo.write(0); // If the distance is greater than 50cm, reset the servo angle } else { lcd.print(S); // If the distance is within 50cm, print the distance in centimeters myservo.write(S * 10); // If the distance is within 50cm, rotate the servo angle ten times the distance } S = 0; IntervalTime = 0; // Reset corresponding values delay(500); // Delay interval determines the sampling frequency }