In the previous two parts of the this tutorial, we went through a number of simple sketches to get you acquainted with the way that the Arduino handles various data types when passed through the Serial COM port. Here are the main themes from part ONE:
Stage One: Echoing data with the Arduino
Stage Two: Using Delimiters to split data.
Stage Three:Arduino Maths, simple addition
Stage Four:Sending a double to an Arduino, and then doubling it.
Stage Five:Sending Sensor data from the Arduino to the Serial Monitor
Stage Seven: Arduino and Processing join forces for more fun
Stage Eight: A simple project that shows Serial communication from Arduino to Processing
In Part Three - we will reverse the direction of communication and get Processing to send data to the Arduino via a USB cable,
Stage Nine: A simple processing sketch that switches an LED on the Arduino
Stage Ten: A processing sketch that reads from a text file
Stage Eleven: A processing sketch that reads data from a text file and sends to the Arduino
Stage Twelve: A processing sketch that trasmits data from a file to another Arduino via an XBee module.
Stage Nine - Using your computer to switch an LED
In this stage we create a simple Arduino sketch which will receive a simple command from the Processing Sketch to switch an LED. The Processing sketch will allow you to turn an LED on/off by clicking on the Processing Application window. It will detect the press of the mouse, and will send a command to the Arduino via the USB Serial COM port.
style="color: rgb(0, 128, 0);">/* =================================================== style="color: rgb(0, 128, 0);">Simple number reader: Written by ScottC - 07 Apr 2013 style="color: rgb(0, 128, 0);"> Arduino Version: 1.04 style="color: rgb(0, 128, 0);">======================================================*/
style="color: rgb(0, 128, 0);">// The onboard LED is on pin # 13 style="color: rgb(43, 145, 175);">int onboardLED = 13;
style="color: rgb(43, 145, 175);">void setup() { style="color: rgb(0, 128, 0);">// Begin Serial communication Serial.begin(9600);
style="color: rgb(0, 128, 0);">//Set the onboard LED to OUTPUT pinMode(onboardLED, OUTPUT); }
style="color: rgb(43, 145, 175);">void loop(){ style="color: rgb(0, 128, 0);">/* Read serial port, if the number is 0, then turn off LED style="color: rgb(0, 128, 0);"> if the number is 1 or greater, turn the LED on. */ style="color: rgb(0, 0, 255);">while (Serial.available() > 0) { style="color: rgb(43, 145, 175);">int num=Serial.read()-style="color: rgb(163, 21, 21);">'0'; style="color: rgb(0, 0, 255);">if(num<1){ digitalWrite(onboardLED, LOW); style="color: rgb(0, 128, 0);">//Turn Off LED } style="color: rgb(0, 0, 255);">else{ digitalWrite(onboardLED, HIGH); style="color: rgb(0, 128, 0);">//Turn On LED } } }
style="color: rgb(0, 128, 0);">/*=========================================================== style="color: rgb(0, 128, 0);"> Toggle Switch: Send Number to Arduino style="color: rgb(0, 128, 0);"> Written by Scott C on 07 Apr 2013 style="color: rgb(0, 128, 0);"> Processing Version: 2.0b8 style="color: rgb(0, 128, 0);">=============================================================*/
import processing.serial.*;
Serial comPort; boolean ledState=style="color: rgb(0, 0, 255);">false; style="color: rgb(0, 128, 0);">//LED is off
style="color: rgb(43, 145, 175);">void setup(){ style="color: rgb(0, 128, 0);">//Open COM Port for Communication comPort = style="color: rgb(0, 0, 255);">new Serial(style="color: rgb(0, 0, 255);">this, Serial.list()[0], 9600); background(255,0,0); style="color: rgb(0, 128, 0);">//Start with a Red background }
style="color: rgb(43, 145, 175);">void draw(){ }
style="color: rgb(43, 145, 175);">void mousePressed() { style="color: rgb(0, 128, 0);">//Toggle led ON and OFF ledState=!ledState;
style="color: rgb(0, 128, 0);">//If ledState is True - then send a value=1 (ON) to Arduino style="color: rgb(0, 0, 255);">if(ledState){ background(0,255,0); style="color: rgb(0, 128, 0);">//Change the background to green
style="color: rgb(0, 128, 0);">/*When the background is green, transmit style="color: rgb(0, 128, 0);"> a value=1 to the Arduino to turn ON LED */ comPort.write(style="color: rgb(163, 21, 21);">'1'); }style="color: rgb(0, 0, 255);">else{ background(255,0,0); style="color: rgb(0, 128, 0);">//Change background to red comPort.write(style="color: rgb(163, 21, 21);">'0'); style="color: rgb(0, 128, 0);">//Send "0" to turn OFF LED. } }
The Video
Stage Ten: Reading from a Text File
We are now going to give the Arduino a rest (for a moment) and concentrate on a Processing Sketch that will read from a text file. Once we learn this skill, we can then build this Processing functionality into our Arduino Projects. Reading from a text file in Processing is actually quite easy if you use the loadStrings()method. However, it is best if you make things easy for yourself by using delimiters. The most common delimitter is a "comma". The comma allows the computer to group information according to your needs.
11,22,33,44,55,66
1,1,2,2,3,3,4,4,5,5,6,6
112,223,334,455,566
The examples above contain the same numbers but are delimitted in different ways. We are going to import a few different numbers/letters and store them in an array. We will then iterate through the array to display the values within. So let us now create the text file. Copy and paste the following text into notepad and save the file, but remember where you save it, because we will need to know location and the name of the file in order to read from in.
Copy and Paste into Notepad:
100,200,A,B,C,10.2,0.1,wx,yz,arduinobasics
Save the file I am going to call my file data.txt, and will be saving it to my D drive, so the file will be located here:
D:/data.txt
We will now create the processing sketch to read the text file and display the data on the screen. We will use the comma delimiters to separate the data so that it displays in the following way:
style="color: rgb(0, 128, 0);">/* Split the data based on a "," delimiter. */ String[] data = splitTokens(lines[i], style="color: rgb(163, 21, 21);">","); style="color: rgb(43, 145, 175);">int dataCount = data.length;
style="color: rgb(0, 0, 255);">for(style="color: rgb(43, 145, 175);">int j=0; j<dataCount; j++){ style="color: rgb(0, 128, 0);">/* Set the size and colour of the text */ textSize(16); fill(100,100,255,50+(j*20));
style="color: rgb(0, 128, 0);">/* Display the text on the screen */ text(data[j],10,16+(16*j)); } } }
style="color: rgb(43, 145, 175);">void draw(){ }
The code above has the ability to display data from multiple lines within the text file, however for simplicity, I have chosen to use a single line. If I wanted to display more than one line, I would have to change the "for-loops".
Stage Eleven: Read Text File and send to Arduino
In stage 10 we used the Processing programming language to import a line of data from a text file, break-up the line into pieces (based on comma delimiters) and then displayed the data on the Computer Screen. We will now use this knowledge and take it one step further. We will create a text file, import the data using processing, but this time we will send the data to the Arduino. Meanwhile the Arduino will be waiting patiently for this data, and once it receives the data, it will react according to our needs. We are going to keep this simple. The goal is to send two different letters from the Computer to the Arduino. One letter will turn an LED on, and the other letter will turn the LED off. We will also send an integer to tell the Arduino how long to keep the LED on or off.
GOAL: Turn an LED on and off by reading a text file.
Our first step in this process is to create a text file that will store our important data. We will store two variables in this file. The first variable will be used to tell the Arduino whether we want to turn the LED on or whether we want to turn the LED off. We will use the letter "O" to turn the LED on, and use the letter "X" to turn the LED off. The second variable will be a time based variable. It will be used to tell the Arduino "how long" to keep the LED on or off. We will store this variable as an integer and will represent time in "milliseconds".
1000 milliseconds = 1 second
It makes sense to keep these two variables as a pair, however we will separate them using a comma delimitter. We will separate each command by putting the variables on a new line. Copy and paste the following data into notepad (or equivalent text editor), and save the file to your harddrive. I have saved this file as
D:/LEDdata.txt
Text File Data:Here is the data to put into your text file (notepad):
style="color: rgb(0, 128, 0);">/* Read TextFile Data: Written by ScottC on 24 April 2013 style="color: rgb(0, 128, 0);"> Arduino IDE version: 1.0.4 style="color: rgb(0, 128, 0);"> http://arduinobasics.blogspot.com.au/2013/04/serial-communication-tutorial-part-3.html style="color: rgb(0, 128, 0);">*/
style="color: rgb(0, 128, 0);">/* Global Variables */ byte byteRead; style="color: rgb(0, 128, 0);">//Used to receive data from computer. style="color: rgb(43, 145, 175);">int timeDelay; style="color: rgb(0, 128, 0);">//time that the LED is On or Off style="color: rgb(43, 145, 175);">int maxtimeDelay=10000; style="color: rgb(0, 128, 0);">//Maximum time delay = 10 seconds style="color: rgb(43, 145, 175);">int ledPin=13; style="color: rgb(0, 128, 0);">//LED connected to pin 13 on Arduino UNO.
style="color: rgb(43, 145, 175);">void setup() { style="color: rgb(0, 128, 0);">//Set pin 13 (ledPin) as an output pinMode(ledPin, OUTPUT); style="color: rgb(0, 128, 0);">// Turn the Serial Protocol ON Serial.begin(9600); }
style="color: rgb(43, 145, 175);">void loop() { style="color: rgb(0, 128, 0);">/* check if data has been sent from the computer: */ style="color: rgb(0, 0, 255);">if (Serial.available()) { style="color: rgb(0, 128, 0);">/* read the most recent byte */ byteRead = Serial.read();
style="color: rgb(0, 0, 255);">switch (byteRead) { style="color: rgb(0, 0, 255);">case 69: style="color: rgb(0, 128, 0);">//This is an enquiry, send an acknowledgement Serial.println(style="color: rgb(163, 21, 21);">"A"); style="color: rgb(0, 0, 255);">break; style="color: rgb(0, 0, 255);">case 79: style="color: rgb(0, 128, 0);">//This is an "O" to turn the LED on digitalWrite(ledPin, HIGH); style="color: rgb(0, 0, 255);">break; style="color: rgb(0, 0, 255);">case 88: style="color: rgb(0, 128, 0);">//This is an "X" to turn the LED off digitalWrite(ledPin, LOW); style="color: rgb(0, 0, 255);">break; style="color: rgb(0, 0, 255);">case 46: style="color: rgb(0, 128, 0);">//End of line style="color: rgb(0, 128, 0);">//Make sure time delay does not exceed maximum. style="color: rgb(0, 0, 255);">if(timeDelay > maxtimeDelay){ timeDelay=maxtimeDelay; } style="color: rgb(0, 128, 0);">//Set the time for LED to be ON or OFF delay(timeDelay); Serial.println(style="color: rgb(163, 21, 21);">"S"); timeDelay=0; style="color: rgb(0, 128, 0);">//Reset timeDelay; style="color: rgb(0, 0, 255);">break; style="color: rgb(0, 0, 255);">default: style="color: rgb(0, 128, 0);">//listen for numbers between 0-9 style="color: rgb(0, 0, 255);">if(byteRead>47 && byteRead<58){ style="color: rgb(0, 128, 0);">//number found, use this to construct the time delay. timeDelay=(timeDelay*10)+(byteRead-48); } } } }
Our next step is to import the data in the text file into Processing and then send the data to the Arduino. You may want to review Stage 10 of this tutorial for another example of importing text file data into Processing. You may also want to review stage 7 which shows how to receive data from an Arduino. We will import all of the data from the file when we push a button on the Processing Window, and send this data to the Arduino via the USB cable that is connected to the computer. We are going to use the same COM port that the Computer uses to upload Arduino Sketches, therefore it is important that you close the Arduino Serial Monitor before you run the processing sketch, otherwise you will get an error which states that the COM port is not available.
style="color: rgb(0, 128, 0);">/* TextFile Data sender (Stage 11) style="color: rgb(0, 128, 0);"> Written by ScottC on 24th April 2013 style="color: rgb(0, 128, 0);"> using Processing Version 2.0b8 style="color: rgb(0, 128, 0);"> style="color: rgb(0, 128, 0);"> The full tutorial can be found here: style="color: rgb(0, 128, 0);"> http://arduinobasics.blogspot.com/2013/04/serial-communication-tutorial-part-3.html style="color: rgb(0, 128, 0);">*/
import processing.serial.*;
Serial comPort; style="color: rgb(0, 128, 0);">//The com port used between the computer and Arduino style="color: rgb(43, 145, 175);">int counter=0; style="color: rgb(0, 128, 0);">// Helps to keep track of values sent. style="color: rgb(43, 145, 175);">int numItems=0; style="color: rgb(0, 128, 0);">//Keep track of the number of values in text file String comPortString; style="color: rgb(0, 128, 0);">//String received From Arduino String textFileLines[]; style="color: rgb(0, 128, 0);">//Array of text file lines String lineItems[]; style="color: rgb(0, 128, 0);">//Array of line items
style="color: rgb(43, 145, 175);">void setup(){ comPort = style="color: rgb(0, 0, 255);">new Serial(style="color: rgb(0, 0, 255);">this, Serial.list()[0], 9600); style="color: rgb(0, 128, 0);">//Setup the COM port comPort.bufferUntil(style="color: rgb(163, 21, 21);">'\n'); style="color: rgb(0, 128, 0);">//Generate a SerialEvent when a newline is received background(255,0,0); style="color: rgb(0, 128, 0);">//Start with a Red background }
style="color: rgb(0, 128, 0);">/* Draw method is not used in this sketch */ style="color: rgb(43, 145, 175);">void draw(){ }
style="color: rgb(0, 128, 0);">//When the mouse is pressed, write an "E" to COM port. style="color: rgb(0, 128, 0);">//The Arduino should send back an "A" in return. This will style="color: rgb(0, 128, 0);">//generate a serialEvent - see below. style="color: rgb(43, 145, 175);">void mousePressed() { comPort.write(style="color: rgb(163, 21, 21);">"E"); }
style="color: rgb(0, 128, 0);">/*If the String received = A, then import the text file style="color: rgb(0, 128, 0);"> change the background to Green, and start by sending the style="color: rgb(0, 128, 0);"> first line of the text file to the Arduino */ style="color: rgb(0, 0, 255);">if(comPortString.equals(style="color: rgb(163, 21, 21);">"A")){ textFileLines=loadStrings(style="color: rgb(163, 21, 21);">"D:/LEDdata.txt"); background(0,255,0); sendLineNum(counter); }
style="color: rgb(0, 128, 0);">/*If the the String received = S, then increment the counter style="color: rgb(0, 128, 0);"> which will allow us to send the next line in the text file. style="color: rgb(0, 128, 0);"> If we have reached the end of the file, then reset the counter style="color: rgb(0, 128, 0);"> and change the background colour back to red. */ style="color: rgb(0, 0, 255);">if(comPortString.equals(style="color: rgb(163, 21, 21);">"S")){ counter++; style="color: rgb(0, 0, 255);">if(counter > (textFileLines.length-1)){ background(255,0,0); counter=0; } style="color: rgb(0, 0, 255);">else { sendLineNum(counter); } } } }
style="color: rgb(0, 128, 0);">/*The sendLineNum method is used to send a specific line style="color: rgb(0, 128, 0);"> from the imported text file to the Arduino. The first style="color: rgb(0, 128, 0);"> line item tells the Arduino to either switch the LED on or off. style="color: rgb(0, 128, 0);"> The second line item, tells the Arduino how long to keep the style="color: rgb(0, 128, 0);"> LED on or off. The full-stop is sent to the Arduino to indicate style="color: rgb(0, 128, 0);"> the end of the line. */
I need to finish my XBee tutorial before doing this stage. But am just about to start studying again. So this stage probably won't get completed for another couple of months. But I hope there is enough content to keep you satisfied for the time being.
The following tutorial will demonstrate how to Read values from a Text file (.txt, .csv) to blink 1 of 9 LEDs attached to an Arduino. It uses the combination of an Arduino and Processing program to process the file. The Processing program will read the text file in real time, only sending new information to the Arduino.
Components Required
Arduino UNO
Breadboard
9 LEDs
9 x 330 ohm resistors
Wires to connect the circuit
USB connection cable: to connect the computer to the Arduino
A computer: to run the processing sketch, and to compile / upload the Arduino sketch
Processing Program installed on computer
Arduino Program installed on the computer
A comma separated text file (*.txt).
Arduino Layout
The Text File
Open Notepad or equivalent text file editor, and paste the following data into it.
1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1
Save the file on your hard drive. In my case, I have chosen to save the file at this location.
D:/mySensorData.txt
It should look like the following screenshot
Additional notes regarding the Text file:
Just remember what you call it, and where you saved it, because we will be referring to this file later on in the Processing script.
Keep all values on the same line.
Separate each number with a comma.
The number 1 will blink the first LED which is attached to Pin 2 on the Arduino.
The number 9 will blink the last LED which is attached to Pin 10 on the Arduino.
Processing Code
You can download the Processing IDE from this site.
style="color: rgb(43, 145, 175);">void setup(){ style="color: green;">//Create a switch that will control the frequency of text file reads. style="color: green;">//When mySwitch=1, the program is setup to read the text file. style="color: green;">//This is turned off when mySwitch = 0 mySwitch=1;
style="color: green;">//Open the serial port for communication with the Arduino style="color: green;">//Make sure the COM port is correct myPort = style="color: blue;">new Serial(this, style="color: rgb(163, 21, 21);">"COM6", 9600); myPort.bufferUntil(style="color: rgb(163, 21, 21);">'\n'); }
style="color: rgb(43, 145, 175);">void draw() { style="color: blue;">if (mySwitch>0){ style="color: green;">/*The readData function can be found later in the code. style="color: green;"> This is the call to read a CSV file on the computer hard-drive. */ readData(style="color: rgb(163, 21, 21);">"D:/mySensorData.txt");
style="color: green;">/*The following switch prevents continuous reading of the text file, until style="color: green;"> we are ready to read the file again. */ mySwitch=0; } style="color: green;">/*Only send new data. This IF statement will allow new data to be sent to style="color: green;"> the arduino. */ style="color: blue;">if(counter<subtext.length){ style="color: green;">/* Write the next number to the Serial port and send it to the Arduino style="color: green;"> There will be a delay of half a second before the command is style="color: green;"> sent to turn the LED off : myPort.write('0'); */ myPort.write(subtext[counter]); delay(500); myPort.write(style="color: rgb(163, 21, 21);">'0'); delay(100); style="color: green;">//Increment the counter so that the next number is sent to the arduino. counter++; } style="color: blue;">else{ //If the text file has run out of numbers, then read the text file again in 5 seconds. delay(5000); mySwitch=1; } }
style="color: green;">/* The following function will read from a CSV or TXT file */ style="color: rgb(43, 145, 175);">void readData(String myFileName){
style="color: green;">/* keep reading each line until you get to the end of the file */ style="color: blue;">while((text=br.readLine())!=style="color: blue;">null){ /* Spilt each line up into bits and pieces using a comma as a separator */ subtext = splitTokens(text,style="color: rgb(163, 21, 21);">","); } }style="color: blue;">catch(FileNotFoundException e){ e.printStackTrace(); }style="color: blue;">catch(IOException e){ e.printStackTrace(); }style="color: blue;">finally{ try { style="color: blue;">if (br != null){ br.close(); } } style="color: blue;">catch (IOException e) { e.printStackTrace(); } } }
style="color: green;">/* This program was created by ScottC on 8/5/2012 to receive serial style="color: green;">signals from a computer to turn on/off 1-9 LEDs */
style="color: rgb(43, 145, 175);">void setup() { style="color: green;">// initialize the digital pins as an output. pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); style="color: green;">// Turn the Serial Protocol ON Serial.begin(9600); }
style="color: green;">/* check if data has been sent from the computer: */ style="color: blue;">if (Serial.available()) {
style="color: green;">/* read the most recent byte */ byteRead = Serial.read(); style="color: green;">//You have to subtract '0' from the read Byte to convert from text to a number. byteRead=byteRead-style="color: rgb(163, 21, 21);">'0';
style="color: green;">//Turn off all LEDs if the byte Read = 0 style="color: blue;">if(byteRead==0){ style="color: green;">//Turn off all LEDS digitalWrite(2, LOW); digitalWrite(3, LOW); digitalWrite(4, LOW); digitalWrite(5, LOW); digitalWrite(6, LOW); digitalWrite(7, LOW); digitalWrite(8, LOW); digitalWrite(9, LOW); digitalWrite(10, LOW); }
style="color: green;">//Turn LED ON depending on the byte Read. style="color: blue;">if(byteRead>0){ digitalWrite((byteRead+1), HIGH); style="color: green;">// set the LED on } } }
Additional Information:
The Arduino code will still work without the processing program. You can open the serial monitor window to send the commands to the Arduino manually. In fact, if you encounter any problems, I would suggest you do this. It will help to identify the root cause of the problem (ie Processing or Arduino Code, or physical connections).
If you choose to use the Serial Monitor feature of the Arduino IDE, you cannot use the Processing program at the same time.
Once you have assembled the Arduino with all the wires, LEDs, resistors etc, you should now be ready to put it all together and get this baby cranking!
Connecting it all together
Connect the USB cable from your computer to the Arduino, and upload the code.
Keep the USB cable connected between the Arduino and the computer, as this will become the physical connection needed by the Processing Program
Make sure that you have the text file in the correct location on your hard drive, and that it only contains numbers relevant to the code provided (separated by commas).
Run the Processing program and watch the LEDs blink in the sequence described by the text file.
You can add more numbers to the end of the line, however, the processing program will not be aware of them until you save the file. The text file does not have to be closed.
Other programs can be used to create text file, but you will need the processing program to read the file and send the values to the Arduino. The Arduino will receive each value and react appropriately.
SIMILAR PROJECT: Use a mouse to control the LEDs on your Arduino - see this post.
An alternative Processing Sketch
This Processing sketch uses the loadStrings()method instead of the FileReader method used in the first sketch. This sketch also provides better control over sending the values to the Arduino. When the sketch first loads, the application window will be red. By clicking your mouse inside the window, the background will turn green and the file will be imported and sent to the Arduino, with every value being sent at half second intervals. If you update the text file and save, only new values will be transmitted, however, if you want the entire file to transmit again, you can press the window once (to reset the counter), and then again to read the file and send the values again from the beginning of the file. I personally like this updated version better than the first, plus I was inspired to update this blog posting due to the fact that some people were having problems with the FileReader method in the first sketch. But both sketches should work (they worked for me).
style="color: rgb(0, 128, 0);">/* TextFile Sender: Written by Scott C on 5th April 2013 style="color: rgb(0, 128, 0);"> using Processing Version 2.0b8 */
import processing.serial.*;
Serial comPort; style="color: rgb(43, 145, 175);">int counter=0; style="color: rgb(0, 128, 0);">// Helps to keep track of values sent. style="color: rgb(43, 145, 175);">int numItems=0; style="color: rgb(0, 128, 0);">//Keep track of the number of values in text file boolean sendStrings=style="color: rgb(0, 0, 255);">false; style="color: rgb(0, 128, 0);">//Turns sending on and off StringLoader sLoader; style="color: rgb(0, 128, 0);">//Used to send values to Arduino
style="color: rgb(43, 145, 175);">void setup(){ comPort = style="color: rgb(0, 0, 255);">new Serial(style="color: rgb(0, 0, 255);">this, Serial.list()[0], 9600); background(255,0,0); style="color: rgb(0, 128, 0);">//Start with a Red background }
style="color: rgb(43, 145, 175);">void draw(){ }
style="color: rgb(43, 145, 175);">void mousePressed() { style="color: rgb(0, 128, 0);">//Toggle between sending values and not sending values sendStrings=!sendStrings;
style="color: rgb(0, 128, 0);">//If sendStrings is True - then send values to Arduino style="color: rgb(0, 0, 255);">if(sendStrings){ background(0,255,0); style="color: rgb(0, 128, 0);">//Change the background to green
style="color: rgb(0, 128, 0);">/*When the background is green, transmit style="color: rgb(0, 128, 0);"> text file values to the Arduino */ sLoader=style="color: rgb(0, 0, 255);">new StringLoader(); sLoader.start(); }style="color: rgb(0, 0, 255);">else{ background(255,0,0); style="color: rgb(0, 128, 0);">//Change background to red style="color: rgb(0, 128, 0);">//Reset the counter counter=0; } }
style="color: rgb(0, 128, 0);">/*============================================================*/ style="color: rgb(0, 128, 0);">/* The StringLoader class imports data from a text file style="color: rgb(0, 128, 0);"> on a new Thread and sends each value once every half second */ style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">StringLoader extends Thread{
In a previous post, I showed you how to export data to a text file. Now I will show you how to import it back into your Processing program. This will come in handy later on.
This is what my data looks like in the text file:
There are many ways to import text from a text file, and there are many ways to store the data within your code after you have imported it. Feel free to make mention of your method in the comments, however, this one definitely works, and is doing what I want it to do.
I have decided to store each line within an ArrayList. The first column is stored in another ArrayList by splitting the data into bits using splitTokens. Most of the file reading code was taken from this Java site, and seems to work quite fine with the Processing programming language. I have taken bits and pieces of code from various places, and added my own flavour.
Here is a snippet of the data after import.
You can see that I have separated the two ArrayLists using dots "....."
/*========================================================== Project: Read data from Text file into Processing Author: ScottC Created: 23rd Jun 2011 (Updated 26th Aug 2014) Description: Use processing to read a text file and populate an ArrayList. The ArrayList is then printed to the debug window. Processing version tested: 2.2.1 References: This was made possible using bits and pieces from these sites http://www.kodejava.org/examples/28.html http://processing.org/reference/ArrayList.html http://processing.org/reference/splitTokens_.html =========================================================== */ import java.io.FileReader; import java.io.FileNotFoundException;
void setup(): this creates 2 new ArrayLists to hold the data, and then calls the readData function. The readData() function needs the name of the file that you want to analyse, eg. C:/mySensorData.txt
br=new BufferedReader(new FileReader(file)); This just sets up the file that you will be reading, which then allows you to use a "while-loop" to read one line at a time using br.readLine().
String [] subtext = splitTokens(text,","); This splits each line into bits, using a "," as a separator, and puts it into the subtext array.
columnOne.add(int(subtext[0])); This shows how you can extract the first number or column from each line. If you wanted the second number or column, you would use subtext[1] instead.
sensorData.add(text); This shows how you can extract the ENTIRE line.
}catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); This is just error handling related to file reading.
br.close(); This closes the file.
for (int i=0; i<sensorData.size()-1; i++){ print(columnOne.get(i) + "....."); println(sensorData.get(i)); } This just prints the data to your screen so that you can see if the whole process has been successful.
Update : If you want to read values from a text file and then send these values to the Arduino - read this blog entry.
Sometimes it would be useful to have a function to save data to a text file. I plan to save some of my Arduino sensor data to a text file using the Processing language. Ninety percent of the following code comes from this forum posting. Thank goodness for the internet, and for people like PhiLho and Cedric. I modified their code and ended up with this (to suit my own project):
/* ===================================================================== Project : Append data to a text file Author : ScottC Created : 16 Nov 2011 (Updated 26 Aug 2014) Description : Use the Processing language to store data on the computer. This code can be used to create a new text file or append to an existing file. Processing Version tested : 2.2.1 Reference: http://processing.org/discourse/yabb2/YaBB.pl?num=1251025598/4
//To insert data into a new file //saveData(myFileName, mySensorData, false);
//To append data to an existing file saveData(myFileName, mySensorData, true); }
voiddraw(){ }
/* -------------------------------------------------------------- SaveData: - This code is used to create/append data to a designated file. - fileName = the location of the output data file (String) - newData = the data to be stored in the file (String) - appendData = true if you want to append = false if you want to create a new file --------------------------------------------------------------*/ void saveData(String fileName, String newData, boolean appendData){ BufferedWriter bw = null; try { FileWriter fw = new FileWriter(fileName, appendData); bw = new BufferedWriter(fw); bw.write(newData + System.getProperty("line.separator")); } catch (IOException e) { } finally { if (bw != null){ try { bw.close(); } catch (IOException e) {} } } }
This will append the sensor data of 10,20,30,40,50 to the end of mySensorData.txt file.
If I wanted to create a new text file instead, then I would call saveData in the following way:
saveData(myFileName, mySensorData, false);
If you found this code useful, please support me here: