首页 文章

Arduino Serial.write to Processing返回0?

提问于
浏览
1

我目前有一个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 回答

  • 1

    在这一行中,

    if(serialCount> 2){

    为 . . 改变

    if(serialCount> = 4){

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

    温度;

相关问题