首页 > 解决方案 > 如何使代码与 ESP32 板兼容?

问题描述

我正在尝试让 GY-US-42 超声波传感器在 ESP32 上工作。但是,我在编译时不断收到错误消息。对于 Arduino Board 来说,这不是问题,但对于 ESP32。

我的代码:

#include "Wire.h"
//The Arduino Wire library uses the 7-bit version of the address, so the code example uses 0x70 instead of the 8-bit 0xE0
#define SensorAddress byte(0x70)
//The sensors ranging command has a value of 0x51
#define RangeCommand byte(0x51)
//These are the two commands that need to be sent in sequence to change the sensor address
#define ChangeAddressCommand1 byte(0xAA)
#define ChangeAddressCommand2 byte(0xA5)
void setup() {
 Serial.begin(115200); //Open serial connection at 9600 baud

 Wire.begin(); 
// changeAddress(SensorAddress,0x40,0);
}
void loop(){
 takeRangeReading(); //Tell the sensor to perform a ranging cycle
 delay(50); //Wait for sensor to finish
  word range = requestRange(); //Get the range from the sensor
  Serial.print("Range: "); Serial.println(range); //Print to the user

}

//Commands the sensor to take a range reading
void takeRangeReading(){
  Wire.beginTransmission(SensorAddress); //Start addressing
  Wire.write(RangeCommand); //send range command
  Wire.endTransmission(); //Stop and do something else now
}
//Returns the last range that the sensor determined in its last ranging cycle in centimeters. Returns 0 if there is no communication.
word requestRange(){
  Wire.requestFrom(SensorAddress, byte(2));
  if(Wire.available() >= 2){ //Sensor responded with the two bytes
  byte HighByte = Wire.read(); //Read the high byte back
  byte LowByte = Wire.read(); //Read the low byte back
  word range = word(HighByte, LowByte); //Make a 16-bit word out of the two bytes for the range
  return range;
}
else {
  return word(0); //Else nothing was received, return 0
}
}

错误:

sketch/GY-US42_I2C.ino.cpp.o:(.literal._Z12requestRangev+0x0): undefined reference to `makeWord(unsigned short)'
sketch/GY-US42_I2C.ino.cpp.o: In function `requestRange()':
/Users/Arduino/GY-US42_I2C/GY-US42_I2C.ino:42: undefined reference to `makeWord(unsigned short)'
collect2: error: ld returned 1 exit status

标签: arduino

解决方案


用于将word()变量或文字转换为 16 位字,它不会像您那样将两个字节添加到 16 位字中word(HighByte, LowByte),即使在 Arduino 中编译,我也很惊讶。

要获得range价值,您可以这样做:

int range = HighByte * 256 + LowByte;

或者:

int range = ((int)HighByte) << 8 | LowByte; //cast HighByte to int, then shift left by 8 bits.

但是由于返回的是 int 而不是 byte(您可以在此处Wire.read()查看其函数原型定义),因此您的代码实际上可以这样编写:

int reading = Wire.read();  //read the first data
reading = reading << 8;     // shift reading left by 8 bits, equivalent to reading * 256
reading |= Wire.read();     // reading = reading | Wire.read()

顺便说一句,当您使用 时#define,您不需要专门将 const 值转换为特定的数据类型,编译器会负责优化和正确的数据类型,所以:

#define SensorAddress byte(0x70)

通过这样定义就可以了:

#define SensorAddress 0x70

您也不需要使用byte(2)or强制转换 const 值return word(0)。在后一种情况下,您的函数原型已经期望返回数据类型为word.


推荐阅读