Arduino Ultrasonic Sensor - Distance Testing





Arduino Sketch


#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);  // I2C / TWI
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;

void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication

if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
    u8g.setColorIndex(255);     // white
  }
  else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) {
    u8g.setColorIndex(3);         // max intensity
  }
  else if ( u8g.getMode() == U8G_MODE_BW ) {
    u8g.setColorIndex(1);         // pixel on
  }
  else if ( u8g.getMode() == U8G_MODE_HICOLOR ) {
    u8g.setHiColorByRGB(255,255,255);
  }

 
 
  pinMode(8, OUTPUT);
}

void draw(void) {
   enum {BufSize=9}; // If a is short use a smaller number, eg 5 or 6
   char buf[BufSize];
 
   snprintf (buf, BufSize, "%d cm",distance );
   // graphic commands to redraw the complete screen should be placed here 
   u8g.setFont(u8g_font_unifont);
   //u8g.setFont(u8g_font_osb21);
   u8g.drawStr( 0, 22, "Distance");

   u8g.setFont(u8g_font_fub25);
   u8g.drawStr( 0 , 59 , buf);
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculating the distance
distance= duration*0.034/2;

// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);

// picture loop
  u8g.firstPage(); 
  do {
    draw();
  } while( u8g.nextPage() );
 
}

ความคิดเห็น