试图让OLED显示来自使用Arduino Nano的超声波距离传感器的输入



我很难从超声波测距仪获取输入以在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!");
}

我不能尝试这个,但我的猜测是你必须通过使用String()将超能传感器的范围转换为字符串,然后你可以在 OLED 显示屏上绘制它。如果在循环函数之外声明变量,也可以在 draw 函数中使用它们。

long RangeInInches;
long RangeInCentimeters;
void loop() { 
...
RangeInCentimeters = ...
Serial.print(RangeInCentimeters);
}
void draw() {
...
u8g.print(String(RangeInCentimeters));
}

最新更新