raspberry pi通过c ++从arduino读取串行数据

时间:2016-04-26 20:36:35

标签: c++ arduino serial-port usb raspberry-pi2

我试图通过C ++从我的覆盆子pi上的arduino中读取串行数据。 当我尝试运行我的代码时,第一个值得到的读取正常,但在第二个值上,我得到0到25​​5之间的各种奇怪数字。 我在我的macbook上尝试了代码并且工作正常。

我在覆盆子pi 2b上运行我的代码+ arduino通过usb连接。

Arduino代码:

unsigned char pots[2];

void setup() {
  Serial.begin(9600);

}

void loop() {
  pots[0] = analogRead(0) / 8 | 128;
  pots[1] = analogRead(1) / 8;


  Serial.write(pots,2);  
  delay(1);
}

C ++代码:

FILE *file;
unsigned char doorspoelChar;
const char *devicename="/dev/cu.usbmodem1421";

int potParams[2];


int main()
{
  file=fopen(devicename,"r");

  if(file==NULL){
    printf("Unable to open device %s\n",devicename);
    exit(1);
  }

  do{

    do{
      fread(&doorspoelChar,1,1,file);
    } while (doorspoelChar < 128);


    potParams[0] = doorspoelChar & 127;
    fread(&doorspoelChar,1,1,file);

    potParams[1] = doorspoelChar ;
    fread(&doorspoelChar,1,1,file);

    std::cout << potParams[0] << " " << potParams[1] << "\n";

  }while(1);

}

0 个答案:

没有答案