0

我试图通过在微控制器中写入寄存器值来控制电机的速度。

unsigned long PrintHex32( uint32_t data) // prints 32-bit data in hex with leading zeroes
{
  uint32_t data2 = data << 8;
  char tmp[16];
  uint16_t LSB = data2 & 0xffff;
  uint16_t MSB = data2 >> 16;
  unsigned long ppsval2 = sprintf(tmp, "0x%.4X%.4X%", MSB, LSB);
  Serial.println(tmp);
  Serial.println("***************");
  return tmp;
}
void NoRamp() {
  Serial.println("No Ramp");
  unsigned long ppsVal = (VMAX * FS * uS);
  unsigned long   ppsVal3 = PrintHex32(ppsVal);
  Serial.println(ppsVal);
  Serial.println(ppsVal3);
  Serial.println("$$$$$$");

  //********* NO Ramp **********////////
  sendData(0xA0, 0x00000000); //RAMP Mode
  //  sendData(0xA4, 0x03E80000); //VMAX-5rps/5hz
  //  sendData(0xA4, 0x00c80000);
  sendData(0xA4, ppsVal3); //VMAX-1rps/1hz

}

最后我需要在十六进制转换后发送数据格式sendData(0xA4, 0x00c80000)

但目前,我得到了我的打印输出:

No Ramp
0x00C80000
***************
51200
0
$$$$$$

嗯,我在哪里犯了错误?任何人都可以请给我一点头!谢谢大佬!!

PS:如果有人需要知道,senddata 方法也采用以下参数!

unsigned long sendData(unsigned long address, unsigned long datagram)

编辑: 我想我能理解要问的正确问题吗?

unsigned long PrintHex32( uint32_t data) // prints 32-bit data in hex with leading zeroes
{
  uint32_t data2 = data << 8;
  //char tmp[16];
  uint16_t LSB = data2 & 0xffff;
  uint16_t MSB = data2 >> 16;
   unsigned long  val = xxxx(uint16_t LSB) + uint16_t MSB(YYY);
  //sprintf(tmp, "0x%.4X%.4X%", MSB, LSB);
  return val ;
}

如果您可以看到我使用uint16_t LSBuint16_t MSB将我的输入 data2 转换为十六进制。如何将这两个值保存为一个unsigned long val。然后我可以返回那个变量。我认为使用 sprintf 方法是错误的,因为它只显示字符表示?如果我错了,请纠正我?

4

1 回答 1

0

编辑中的 xxxx 应该是 2^16 aka 65536:

#include <cassert>
using namespace std;

int main(int argc, char * argv[]) {

unsigned int data2 = 12345678;
uint16_t LSB = data2 & 0xffff;
uint16_t MSB = data2 >> 16;
unsigned long  val = (1<<16) * MSB + LSB;
unsigned long  val2 = 65536 * MSB + LSB;
assert(val == data2);
assert(val2 == data2);
}
于 2019-07-23T06:31:39.290 回答