阵列数据读取失败



我正在从一个";扭矩扳手";使用";USB主机屏蔽2.0";和Arduino UNO。我正在从我的";扭矩扳手";数据正在数组中接收。但当我在";对于";循环内部Void loop()我接收到不正确的数据。我附上了两张输出图片的正确和不正确数据。

基本上,我从扭矩扳手中读取数据,并使用Nrf24l01发送到接收器。我收到的数据不正确。

我的问题是:-为什么我在外面读不正确的数据"对于";环

  1. 内部的正确数据";对于";循环:在此处输入图像描述
  2. 外部数据不正确";对于";循环:在此处输入图像描述
#include <SPI.h> // for SPI communication
#include <nRF24L01.h>
#include <RF24.h>
#include <cdcacm.h>
#include <usbhub.h>
//#include "pgmstrings.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

RF24 radio(7, 8); // CE, CSN
const byte address[6] = {'R','x','A','A','A','B'}; // the address the the module
class ACMAsyncOper : public CDCAsyncOper
{
public:
uint8_t OnInit(ACM *pacm);
};
uint8_t ACMAsyncOper::OnInit(ACM *pacm)
{
uint8_t rcode;
// Set DTR = 1 RTS=1
rcode = pacm->SetControlLineState(3);
if (rcode)
{
ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
return rcode;
}
LINE_CODING  lc;
lc.dwDTERate  = 9600;
lc.bCharFormat  = 0;
lc.bParityType  = 0;
lc.bDataBits  = 8;
rcode = pacm->SetLineCoding(&lc);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
return rcode;
}
USB     Usb;
//USBHub     Hub(&Usb);
ACMAsyncOper  AsyncOper;
ACM           Acm(&Usb, &AsyncOper);


void setup() {
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MAX);
radio.stopListening(); 
#if !defined(__MIPSEL__)
while (!Serial); 
#endif
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("USB Not Connected");
delay( 200 ); 

}
void loop() {


Usb.Task();

if( Acm.isReady()) {
uint8_t rcode;
/* reading the keyboard */
if(Serial.available()) {
uint8_t data= Serial.read();
/* sending to the phone */
rcode = Acm.SndData(1, &data);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
}
delay(10);
uint8_t  buf[64];
uint16_t rcvd = 64;
char text[64];

rcode = Acm.RcvData(&rcvd, buf);
if (rcode && rcode != hrNAK)
ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
if ( rcvd ) { 

for(uint16_t i=0; i < rcvd; i++ ) 
{ 
// Serial.print((char)buf[i]);  // correct Data read from torque wrench
text[i] = (char)buf[i];
}

Serial.println(text);  // reading wrong data here

//radio.write(&text, sizeof(text));   
//Serial.println(text);               
}
delay(10);
}

}

字符数组必须以null结尾才能算作C字符串。在for循环之后,添加text[rcvd] = '';此外,您的rcvd固定为64。它需要比数组大小小一个,才能容纳null终止符。

最新更新