我在将一些C++代码转换为Arduino时遇到了麻烦.任何帮助,将不胜感激.
编辑
我已成功完成上述操作.然而,现在唯一的问题是Arduino代码我已经准确,正确地读取电压但没有其他寄存器.我也可以写油门了.如果我调用不同数量的Serial.println()语句,其他寄存器上的读数会发生变化,在某些情况下,电压寄存器也会停止工作.这在我的代码中可以找到
Serial.print("Voltage: );
Run Code Online (Sandbox Code Playgroud)
如果我打印出所有这些寄存器,答案就会改变.我无法弄清楚为什么会这样.
/* DEFINITIONS */
#include <math.h>
/* FLOATS */
uint8_t command[5];
uint8_t response[3];
/* INTEGERS */
byte deviceId = 0x17;
double throttleOut = 0;
double voltage = 0;
double rippleVoltage = 0;
double current = 0;
double power = 0;
double throttle = 0;
double pwm = 0;
double rpm = 0;
double temp = 0;
double becVoltage = 0;
double safeState = 0;
double linkLiveEnabled = 0;
double eStopStatus = 0;
double rawNTC = 0;
/* SETUP */
void setup() {
Serial1.begin(115200);
Serial.begin(115200);
}
void loop() {
flushPort();
ReadWriteRegister(128, 1000, true);//_throttleOut is 0[0%] to 65535[100%]
voltage = ReadWriteRegister(0, 0, false) / 2042.0 / 0.05;
rippleVoltage = ReadWriteRegister(1, 0, false) / 2042 / 0.25;
current = ReadWriteRegister(2, 0, false) / 204200 * 50;
power = voltage * current;
throttle = (ReadWriteRegister(3, 0, false) / 2042.0 / 1.0);
pwm = ReadWriteRegister(4, 0, false) / 2042.0 / 3.996735;
rpm = ReadWriteRegister(5, 0, false) / 2042.0 / 4.89796E-5;
int poleCount = 20;//Motor pole count
rpm = rpm / (poleCount / 2);
temp = ReadWriteRegister(6, 0, false) / 2042.0 * 30.0;
becVoltage = ReadWriteRegister(7, 0, false) / 2042 / 0.25;
safeState = ReadWriteRegister(26, 0, false);
linkLiveEnabled = ReadWriteRegister(25, 0, false);
eStopStatus = ReadWriteRegister(27, 0, false) == 0 ? false : true;
rawNTC = ReadWriteRegister(9, 0, false) / 2042.0 / 0.01567091;
rawNTC = 1.0 / (log(rawNTC * 10200.0 / (255.0 - rawNTC) / 10000.0 ) / 3455.0 + 1.0 / 298.0) - 273.0;
Serial.print("Voltage: ");
Serial.println(voltage);
Serial.print("Current: ");
Serial.println(current);
}
void flushPort() {
command[0] = command[1] = command[2] = command[3] = command[4] = 0;
Serial1.write(command, 5);
while (Serial1.available() > 0) {
Serial1.read();
}
}
double ReadWriteRegister(int reg, int value, bool writeMode) {
// Send read command
command[0] = (byte)(0x80 | deviceId);
command[1] = (byte)reg;
command[2] = (byte)((value >> 8) & 0xFF);
command[3] = (byte)(value & 0xFF);
command[4] = (byte)(0 - command[0] - command[1] - command[2] - command[3]);
Serial1.write(command, 5);
// Read response
if(Serial1.available() == 3) {
response[0] = (byte)Serial1.read();
response[1] = (byte)Serial1.read();
response[2] = (byte)Serial1.read();
}
if ((byte)(response[0] + response[1] + response[2]) == 0)
{
return (double)((response[0] << 8) + (response[1]));
}
else
{
Serial.println("Error communicating with device!");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑2
一些usb逻辑分析仪拍摄的照片.[
] [[
] [[
] [[
] [[
] [[
] [[
]并且所有的数据包都在这一个:[
]也许这会有助于超时等.这是我所拥有的所有信息:.
没有办法ReadWriteRegister行得通。在115200处,每个字符的发送或接收大约需要87us。那时,Arduino可以执行大约100行代码!
看看这个片段:
Serial1.write(command, 5);
// Read response
if(Serial1.available() == 3) {
Run Code Online (Sandbox Code Playgroud)
该write函数仅将命令放入输出缓冲区并开始发送第一个字符。它在所有字符传输完毕之前返回。这将需要 500us!
然后,您查看是否收到了 3 个字符的响应。但是命令还没有传输完毕,你肯定没有等258us(3乘以86us)。如果设备需要时间来执行您的命令,甚至可能需要更长的时间。
您必须做两件事:等待发送命令,并等待收到响应。尝试这个:
Serial1.write(command, 5);
Serial1.flush(); // wait for command to go out
// Wait for response to come back
while (Serial1.available() < 3)
; // waitin'....
// Read response
response[0] = (byte)Serial1.read();
response[1] = (byte)Serial1.read();
response[2] = (byte)Serial1.read();
Run Code Online (Sandbox Code Playgroud)
这称为“阻塞”,因为在您等待响应时 Arduino 不会执行任何其他操作。
但是,如果丢失了一个字符,如果第二个字符未正确发送/接收(这种情况发生),您的程序可能会“挂起”在那里,等待第四个字符。所以你应该在 while 循环中设置 500us 超时:
// Wait for response
uint32_t startTime = micros();
while ((Serial1.available() < 3) && (micros() - startTime < 500UL))
; // waitin'...
Run Code Online (Sandbox Code Playgroud)
...或更长时间,如果您知道设备的响应速度。然后您可以确定是否确实收到了回复:
/* DEFINITIONS */
#include <math.h>
/* INTEGERS */
byte deviceId = 0x17;
uint8_t command[5];
uint8_t response[3];
/* FLOATS */
double throttleOut = 0.0;
double voltage = 0.0;
double rippleVoltage = 0.0;
double current = 0.0;
double power = 0.0;
double throttle = 0.0;
double pwm = 0.0;
double rpm = 0.0;
double temp = 0.0;
double becVoltage = 0.0;
uint8_t safeState = 0;
uint8_t linkLiveEnabled = 0;
bool eStopStatus = 0;
double rawNTC = 0.0;
/* SETUP */
void setup() {
Serial1.begin(115200);
Serial.begin(115200);
Serial.println( F("---------------------------") );
// According to the spec, you can synchronize with the device by writing
// five zeroes. Although I suspect this is mostly for the SPI and I2c
// interfaces (not TTL-level RS-232), it won't hurt to do it here.
Serial1.write( command, 5 );
delay( 250 ); // ms
while (Serial1.available())
Serial1.read(); // throw away
// Set the throttle just once
ReadWriteRegister(128, 1000);//_throttleOut is 0[0%] to 65535[100%]
}
// For 12-bit A/D conversions, the range is 0..4096. Values at
// the top and bottom are usually useless, so the value is limited
// to 6..4090 and then shifted down to 0..4084. The middle of this
// range will be the "1.0" value: 2042. Depending on what is being
// measured, you still need to scale the result.
const double ADC_FACTOR = 2042.0;
void loop() {
uint32_t scanTime = millis(); // mark time now so we can delay later
voltage = ReadWriteRegister( 0, 0 ) / ADC_FACTOR * 20.0;
rippleVoltage = ReadWriteRegister( 1, 0 ) / ADC_FACTOR * 4.0;
current = ReadWriteRegister( 2, 0 ) / ADC_FACTOR * 50.0;
power = voltage * current;
throttle = ReadWriteRegister( 3, 0 ) / ADC_FACTOR * 1.0;
pwm = ReadWriteRegister( 4, 0 ) / ADC_FACTOR * 0.2502;
rpm = ReadWriteRegister( 5, 0 ) / ADC_FACTOR * 20416.66;
const int poleCount = 20;//Motor pole count
rpm = rpm / (poleCount / 2);
temp = ReadWriteRegister( 6, 0 ) / ADC_FACTOR * 30.0;
becVoltage = ReadWriteRegister( 7, 0 ) / ADC_FACTOR * 4.0;
safeState = ReadWriteRegister( 26, 0 );
linkLiveEnabled = ReadWriteRegister( 25, 0 );
eStopStatus = ReadWriteRegister( 27, 0 );
rawNTC = ReadWriteRegister( 9, 0 ) / ADC_FACTOR * 63.1825;
const double R0 = 1000.0;
const double R2 = 10200.0;
const double B = 3455.0;
rawNTC = 1.0 / (log(rawNTC * R2 / (255.0 - rawNTC) / R0 ) / B + 1.0 / 298.0) - 273.0;
Serial.print( F("Voltage: ") );
Serial.println(voltage);
Serial.print( F("Current: ") );
Serial.println(current);
Serial.print( F("Throttle: ") );
Serial.println(throttle);
Serial.print( F("RPM: ") );
Serial.println(rpm);
// These prints do not actually send the characters, they only queue
// them up to be sent gradually, at 115200. The characters will be
// pulled from the output queue by a TX interrupt, and given to the
// UART one at a time.
//
// To prevent these interrupts from possibly interfering with any other
// timing, and to pace your program, we will wait *now* for all the
// characters to be sent to the Serial Monitor.
Serial.flush();
// Let's pace things a little bit more for testing: delay here until
// it's time to scan again.
const uint32_t SCAN_INTERVAL = 1000UL; // ms
while (millis() - scanTime < SCAN_INTERVAL)
; // waitin'
}
int16_t ReadWriteRegister(int reg, int value) {
// Flush input, as suggested by Gee Bee
while (Serial1.available() > 0)
Serial1.read();
// Send command (register number determines whether it is read or write)
command[0] = (byte)(0x80 | deviceId);
command[1] = (byte)reg;
command[2] = (byte)((value >> 8) & 0xFF);
command[3] = (byte)(value & 0xFF);
command[4] = (byte)(0 - command[0] - command[1] - command[2] - command[3]);
Serial1.write(command, 5);
// The command bytes are only queued for transmission, they have not
// actually gone out. You can either wait for command to go out
// with a `Serial1.flush()` *OR* add the transmission time to the
// timeout value below. However, if anything else has queued bytes
// to be sent and didn't wait for them to go out, the calculated
// timeout would be wrong. It is safer to flush now and guarantee
// that *all* bytes have been sent: anything sent earlier (I don't
// see anything else, but you may change that later) *plus*
// these 5 command bytes.
Serial1.flush();
// Now wait for response to come back, for a certain number of us
// The TIMEOUT could be as short as 3 character times @ the Serial1
// baudrate: 3 * (10 bits/char) / 115200bps = 261us. This is if
// the device responds immediately. Gee Bee says 20ms, which would
// be 20000UL. There's nothing in the spec, but 1ms seems generous
// for reading the raw NTC value, which may require an ADC conversion.
// Even the Arduino can do that in 100us. Try longer if you get
// timeout warnings.
const uint32_t TIMEOUT = 2000UL;
uint32_t startTime = micros();
while ((Serial1.available() < 3) && (micros() - startTime < TIMEOUT))
; // waitin'...
int16_t result;
if (Serial1.available() >= 3) {
response[0] = (byte)Serial1.read();
response[1] = (byte)Serial1.read();
response[2] = (byte)Serial1.read();
// Verify the checksum
if (response[0] + response[1] + response[2] != 0) {
Serial.print( reg );
Serial.println( F(" Checksum error!") );
Serial.flush(); // optional, use it for now to stay synchronous
}
// Cast to 16 bits *first*, then shift and add
result = (((int16_t) response[0]) << 8) + (int16_t) response[1];
} else {
// Must have timed out, because there aren't enough characters
Serial.print( reg );
Serial.println( F(" Timed out!") );
Serial.flush(); // optional, use it for now to stay synchronous
result = 0;
}
return result; // You must always return something
}
Run Code Online (Sandbox Code Playgroud)
评论:
double加法之外会导致您丢失前 8 位。按上述计算应该给出正确答案。ReadWriteRegister。该函数可以告诉您是否超时或校验和是否错误。这也意味着可能需要更长的超时。目前尚不清楚您的设备是否等待长达 480 毫秒才能获取最新值,或者是否连续缓存它们并立即响应从 ESC 接收到的最后一个值。 然而,写入在长达 480ms 的时间内不会反映在读取值中,因为 ESC 需要时间接收命令然后发送新值。请参阅ESC Castle Link 协议。ReadWriteRegister函数返回一个16位整数,这样效率会更高。比较浮点数从来都不是一件好事。顺便说一句,在 8 位 Arduino 上double只是单一的。floatReadWriteRegister函数不需要writemode参数,因为寄存器编号决定您是在写入还是读取设备。throttle值仅在设置中执行。您的逻辑分析仪截图似乎显示了 ESC 的“扫描”。它正在尝试每个设备 ID,其中一些设备会回复非零电压。另外,它似乎运行在 9600,而不是115200。这是来自不同的设置吗?
无论如何,它证实了控制器规范所说的内容:写入 5 个字节,读取 3 个字节。校验和值符合预期。但是,它的运行速度比您的程序慢 10 倍,因此它没有提供太多有关超时的新信息。这可能意味着设备响应之前有一个小的延迟,可能约为 1 位时间,或大约 100us。
您阅读过控制器规格吗?您应该将程序与规范进行比较,以确保您了解控制器的工作原理。
我将上面的程序修改为:
setup(写入 5 个零字节并等待 250 毫秒),double(参见safeState、linkLiveStatus和eStopStatus),reg发生错误时输出数字。如果您想在这一领域取得成功,您必须学会阅读规范并将其要求转化为符合的代码。您开始使用的程序在最坏的情况下是不合规的,或者在最好的情况下具有误导性。我对“INTEGERS”和“FLOATS”的评论感到特别好笑,但这些部分包含相反的内容。
也许这是修复别人代码的教训?它确实有很多你会遇到的问题。如果我每次说的话都能得到五分钱的话:
......我会成为一个非常富有的人。:)
(更新结束)
这也符合您描述的症状:因为您没有等待传输完成,所以第一次读取0字节(read将返回-1或0xFF字节)。
在您多次调用此例程(并将多个命令排队到输出缓冲区中)后,500us 过去了,第一个命令终于被发送。设备通过开始发送 3 个字符进行响应。87us后,Arduino终于收到第一个字符。它会被你的一项陈述读取read,但谁知道是哪一项呢?它将是随机的,基于经过的时间。
更多命令被发送,单个字符被这些语句之一接收和读取,直到 64 字节命令或 Serial.println 字符排队。然后write命令OR Serial.print会阻塞,直到输出有空间容纳最新命令。(这解决了您问题的标题。)
当最终传输足够的命令字节或调试消息字符时,Serial1.write或Serial.print返回。与此同时,接收到的字符将进入输入缓冲区。(这就是它们存储的地方,直到您调用read。)
此时,read连续三个语句将实际获取设备发送的字符。但由于之前字符的随机消耗,它可能是一个响应的最后一个字符,后面是下一个响应的前两个字符。您与 3 字节响应“不同步”。
要与设备保持“同步”,您必须等待发送完成(使用 )flush,并等待响应返回(使用 )while。