Libraries make easy

Were it not for the exsiting librarys (LiquidCrystal and NewPing), I would spend one more day porting my MCS-51 code on LCD1602 and HY-SR05 to Arduino!

#include <LiquidCrystal.h>
#include <NewPing.h>

// NewPing setup of pins and maximum distance.
#define TRIGGER_PIN  7  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     6  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

// initialize the library with the numbers of the interface pins
// rs, rw, enable, d4, d5, d6 d7
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

#define STR_BLANKS   "        "
#define STR_TIME     "Time(us):"
#define STR_DISTANCE "Dist(cm):"

void setup() {  
  lcd.begin(16, 2);
//  lcd.cursor();
//  lcd.blink();
  lcd.setCursor(0, 0);
  lcd.write(STR_TIME);
  lcd.setCursor(0, 1);
  lcd.write(STR_DISTANCE);
}

void loop() {
  char str_pingTime[6], str_distCm[6];
  
  delay(200);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping();  // Send ping, get ping time in microseconds (uS).
  
  lcd.setCursor(strlen(STR_TIME),0);
  lcd.write(STR_BLANKS);
  lcd.setCursor(strlen(STR_DISTANCE), 1);
  lcd.write(STR_BLANKS);

  lcd.setCursor(strlen(STR_TIME) ,0);
  itoa(uS, str_pingTime, 10);
  lcd.write(str_pingTime);

   lcd.setCursor(strlen(STR_DISTANCE) , 1);
   itoa(sonar.convert_cm(uS), str_distCm, 10);
   lcd.write(str_distCm);
}

发表评论

电子邮件地址不会被公开。