使用Processing IDE将数据发送到串行端口(调试正常但运行不正常)

时间:2016-05-10 03:15:18

标签: text arduino processing

我正在尝试在PC上的文本文件中读取一系列数字,然后通过串口将它们发送到我的Arduino板。数字用逗号和短划线分开,所以我执行两个循环。将数字发送到串行端口应该点亮Arduino板上的等效LED。问题是,只有第一次循环中的第一次迭代才会在运行模式下点亮等效的LED,尽管它在调试模式下也是如此。其他迭代和其他循环运行完美。毫无疑问,硬件100%没有任何问题。任何帮助将不胜感激。 这是代码:

 
import processing.serial.*;
import java.io.*;
int mySwitch=0;
int counter1=0;
int counter2=0;
String [] subtext;
String[] Lines;
Serial myPort;

void setup()
{
//Create a switch that will control the frequency of text file reads.
//When mySwitch=1, the program is setup to read the text file.
//This is turned off when mySwitch = 0
 mySwitch=1;

 //Open the serial port for communication with the Arduino
 //Make sure the COM port is correct
 myPort = new Serial(this, "COM36", 9600);
 myPort.bufferUntil('\n');
 }

void draw()
 {
 if (mySwitch>0)
   {
 /*The readData function can be found later in the code.
 This is the call to read a CSV file on the computer hard-drive. */
 readData("Y:/MyTextFile.txt");

 /*The following switch prevents continuous reading of the text file, until
 we are ready to read the file again. */
 mySwitch=0;
   }
 /*Only send new data. This IF statement will allow new data to be sent to
 the arduino. */

  while(counter1<Lines.length)
   {
 subtext = splitTokens(Lines[counter1],","); 
 counter2=0;
 while(counter2<subtext.length)
     {
 /* Write the next number to the Serial port and send it to the Arduino 
 There will be a delay of half a second before the command is
 sent to turn the LED off : myPort.write('0'); */
 myPort.write(subtext[counter2]);
 counter2++;
      } 
 delay(2000);
 myPort.write('0');
 delay(2000);
 counter1++;
    }
 //If the text file has run out of numbers, then read the text file again in       5 seconds.
delay(5000);
mySwitch=1;
} 

/* The following function will read from a CSV or TXT file */
void readData(String myFileName)
{
 File file=new File(myFileName);
 BufferedReader br=null;

 try
  {
 br=new BufferedReader(new FileReader(file));
 String text=null;

 /* keep reading each line until you get to the end of the file */
while((text=br.readLine())!=null)
    {
 /* Spilt each line up into bits and pieces using a comma as a separator */
 Lines = splitTokens(text,"-");
    }
  }catch(FileNotFoundException e){
 e.printStackTrace();
 }catch(IOException e){
 e.printStackTrace();
 }finally{
 try {
 if (br != null){
 br.close();
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }

0 个答案:

没有答案