Arduino Serial.write to Processing返回0?

时间:2016-08-12 01:33:04

标签: events serialization arduino processing communication

我目前有一个Arduino程序通过串行事件传递加速度计值,以便处理完美。我试图在我的设置中添加一个温度计,但处理只是从读取引脚接收0。如果我在设置中读取串行打印,它确实可以打印到串行监视器,但是我无法在加速度计读数旁边发送正确的值。

Arduino代码:

int inByte = 0;

void setup() {  
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  establishContact();  // send a byte to establish contact until receiver responds
}

void loop() {

  if (Serial.available() > 0) {

    // get incoming byte:
    inByte = Serial.read();

    // send sensor values:
    Serial.write(analogRead(A3)); // X AXIS
    Serial.write(analogRead(A2)); // Y AXIS
    Serial.write(analogRead(A1)); // Z AXIS
    Serial.write(analogRead(A0)); // TEMPERATURE
  }
}

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.print('A');   // send a capital A
    delay(300);
  }
}

处理代码:

import processing.serial.*;

Serial myPort;                       
int[] serialInArray = new int[4];    
int serialCount = 0;                 
int xInput, yInput, zInput;
float temperature;
boolean firstContact = false;

void setup() {
  size(600, 600, P3D);
  pixelDensity(2);
  noStroke();
  background(0);
  printArray(Serial.list());
  String portName = Serial.list()[4];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
}

void serialEvent(Serial myPort) {
  // read a byte from the serial port:
  int inByte = myPort.read();
  // if this is the first byte received, and it's an A,
  // clear the serial buffer and note that you've
  // had first contact from the microcontroller. 
  // Otherwise, add the incoming byte to the array:
  if (firstContact == false) {
    if (inByte == 'A') { 
      myPort.clear();          // clear the serial port buffer
      firstContact = true;     // you've had first contact from the microcontroller
      myPort.write('A');       // ask for more
    }
  } else {
    // Add the latest byte from the serial port to array:
    serialInArray[serialCount] = inByte;
    serialCount++;

    // If we have 3 bytes:
    if (serialCount > 2 ) {

      zInput = serialInArray[0]-80;
      yInput = serialInArray[1]-80+69;
      xInput = serialInArray[2]-77;
      temperature = serialInArray[3]; // should return voltage reading (i.e 16ºc = 130);
      //println("x = " + xInput + ", y = " + yInput + ", z = " + zInput + ", Temp = " + serialInArray[3]);

      // Send a capital A to request new sensor readings:
      myPort.write('A');
      // Reset serialCount:
      serialCount = 0;
    }
  }
}

加速度计值打印完美,但温度只返回0.串行监视器中的Serial.print(analogRead(A0))给出了正确的值,因此温度计绝对有效。

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

在这一行中,

if(serialCount&gt; 2){

更改

if(serialCount&gt; = 4){

或尝试使用类型转换或更改整数的温度!

int temperature;