从Processing发送两个数组到Arduino

时间:2018-05-30 14:17:21

标签: arduino processing

我正在尝试将多个变量(n个字符串和n个整数)从处理传递到我的Arduino。我在网上找到了this教程并设法发送了一个值。现在我有两个阵列需要由Arduino filesTypes[]filesSizes[]访问。 filesTypes[]由3个字符串长的字符串组成,而fileSizes[]是一个不同整数的数组。

这是我的处理代码:

import processing.serial.*;

Serial myPort;  // Create object from Serial class

String[] fileTypes;
int[] fileSizes;
String[][] lines;

void setup() 
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[1]; //change the 0 to a 1 or 2 etc. to         
match your port
  myPort = new Serial(this, portName, 9600);

  launch( sketchPath("") + "/test.bat");

}

void draw() {
  if (mousePressed == true) 
  {     //if we clicked in the window
     txtToStrg(); 
    myPort.write('1');         //send a 1
    txtToStrg();  
  } else 
  {                           //otherwise
  myPort.write('0');          //send a 0
  }   
}

void txtToStrg(){

  String[] lines = loadStrings("list.txt");
  fileTypes = new String[lines.length];
  fileSizes = new int[lines.length];

  for (int i = 0 ; i < lines.length; i++) {
    if(lines[i] != null) {
      String[] splitLine = split(lines[i], ' ');
      fileTypes[i] = splitLine[0];
      fileSizes[i] = int(splitLine[1]);
      println(fileTypes[i] + " = " + fileSizes[i]);
    }
  }
} 

这是我的Arduino代码:

 char val; // Data received from the serial port
 int ledPin = 4 ; // Set the pin to digital I/O 13

 void setup() {
   pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
   Serial.begin(9600); // Start serial communication at 9600 bps
 }

 void loop() {
   if (Serial.available()) 
   { // If data is available to read,
     val = Serial.read(); // read it and store it in val
   }
   if (val == '1') 
   { // If 1 was received
     digitalWrite(ledPin, HIGH); // turn the LED on
   } else {
     digitalWrite(ledPin, LOW); // otherwise turn it off
   Serial.print(val);
   }
   delay(10); // Wait 10 milliseconds for next reading
}

如果传递除了char之外的任何东西,它就会停止工作。

0 个答案:

没有答案