我很难从超声波测距仪获取输入以在 Oled 显示器上显示距离。我正在使用 Arduino Nano。我可以让显示器打印 Hello World,同时我可以在 Arduino IDE 串行监视器上查看测距仪的所有输入。我使用的是 1.3 英寸 oled 显示屏和 3 针超声波测距仪。它具有 vcc、接地和信号引脚。我尝试了许多不同的组合来尝试使其显示,但没有任何效果。这是我目前所拥有的,至少可以使两个设备同时工作。对于显示器和传感器,制造商提供了代码以使其在 Arduino Nano 上独立工作。对于我的代码造成的所有混淆,我深表歉意。
#include <U8glib.h>
#include "Arduino.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0); // for 0.96” and 1.3”
class Ultrasonic
{
public:
Ultrasonic(int pin);
void DistanceMeasure(void);
long microsecondsToCentimeters(void);
long microsecondsToInches(void);
private:
int _pin; //pin number of Arduino that is connected with SIG pin of Ultrasonic Ranger.
long duration; // the Pulse time received;
};
Ultrasonic::Ultrasonic(int pin)
{
_pin = pin;
}
/*Begin the detection and get the pulse back signal*/
void Ultrasonic::DistanceMeasure(void)
{
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
delayMicroseconds(2);
digitalWrite(_pin, HIGH);
delayMicroseconds(5);
digitalWrite(_pin,LOW);
pinMode(_pin,INPUT);
duration = pulseIn(_pin,HIGH);
}
/*The measured distance from the range 0 to 400 Centimeters*/
long Ultrasonic::microsecondsToCentimeters(void)
{
return duration/29/2;
}
/*The measured distance from the range 0 to 157 Inches*/
long Ultrasonic::microsecondsToInches(void)
{
return duration/74/2;
}
Ultrasonic ultrasonic(7);
void setup(void)
{
Serial.begin(9600);
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);
}
}
void loop(){
{
long RangeInInches;
long RangeInCentimeters;
ultrasonic.DistanceMeasure(); // get the current signal time;
RangeInInches = ultrasonic.microsecondsToInches(); //convert the time to inches;
RangeInCentimeters = ultrasonic.microsecondsToCentimeters(); //convert the time to centimeters
Serial.println("The distance to obstacles in front is: ");
Serial.print(RangeInInches);//0~157 inches
Serial.println(" inch");
Serial.print(RangeInCentimeters);//0~400cm
Serial.println(" cm");
delay(100);
}
{
// picture loop
u8g.firstPage();
do {
draw();
} while( u8g.nextPage() );
// rebuild the picture after some delay
delay(50);
}
}
void draw(void) {
u8g.setFont(u8g_font_unifont);
u8g.setPrintPos(5, 20);
u8g.print("Hello World!");
}