We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I'm trying to get my arduino to constantly read data from a text file. So far I managed to get it to read the text file upon a mouse click every time, using the "mousePressed()" function.
Problem: I am now trying to let it send data whenever the text file is APPENDED with new alphabets. Meaning to say only newly added data in the text file will be sent to Arduino. Can someone guide me on how to modify my code such that it constantly reads my text file, and sends newly added data?
`import processing.serial.*;
Serial comPort; int counter=0; // Helps to keep track of values sent. int numItems=0; //Keep track of the number of values in text file boolean sendStrings=false; //Turns sending on and off StringLoader sLoader; //Used to send values to Arduino boolean flag = true;
void setup(){ comPort = new Serial(this, "COM3", 9600); background(255,0,0); //Start with a Red background }
void draw(){
}
void mousePressed() { //Toggle between sending values and not sending values //sendStrings=!sendStrings;
//If sendStrings is True - then send values to Arduino if(sendStrings){ background(0,255,0); //Change the background to green
/*When the background is green, transmit text file values to the Arduino */ sLoader=new StringLoader(); sLoader.start(); }else{ background(255,0,0); //Change background to red //Reset the counter //counter=0; } sendStrings=false; }
/============================================================/ /* The StringLoader class imports data from a text file on a new Thread and sends each value once every half second */ public class StringLoader extends Thread{
public StringLoader(){ //default constructor }
public void run() { String textFileLines[]=loadStrings("../Directions.txt");
String lineItems[]=splitTokens(textFileLines[0], ",");
numItems=lineItems.length;
for(int i = counter; i<numItems; i++){
comPort.write(lineItems[i]);
delay(500);
}
counter=numItems;
}
}`
Answers
Edit post, highlight code, press Ctrl-o to format.
How do you know that the file has changed? Couldn't you remember how long the file is and check that and only do the expensive file parsing thing if it's changed, wouldn't that be less processing?
In this case, instead of using loadStrings, one could use a Java File object and periodically check its .length(). Checking every frame, might be unnecessary, though -- how often the file should be checked depends on how responsive sending should be.
Check the
FileWatcher
class in this post: https://forum.processing.org/two/discussion/comment/122726/#Comment_122726or check this post as it is more clear: https://stackoverflow.com/questions/4363197/getting-the-last-modified-date-of-a-file-in-java
What process is appending data to your file? Rate?
Kf