I have some position data continually coming in and I am currently printing it to the serial.
Say I have the string "5" and want to print that to a text file, "myTextFile", what would I need to do to achieve this? To be clear, the text file would be saved on my computer not on an SD card on the Arduino.
Also, is their a way to create a text file within the program before I start saving to it?
You can create a python script to read the serial port and write the results into a text file:
##############
## Script listens to serial port and writes contents into a file
##############
## requires pySerial to be installed
import serial # sudo pip install pyserial should work
serial_port = '/dev/ttyACM0';
baud_rate = 9600; #In arduino, Serial.begin(baud_rate)
write_to_file_path = "output.txt";
output_file = open(write_to_file_path, "w+");
ser = serial.Serial(serial_port, baud_rate)
while True:
line = ser.readline();
line = line.decode("utf-8") #ser.readline returns a binary, convert to string
print(line);
output_file.write(line);
U have to Use serial-lib for this
Serial.begin(9600);
Write your sensor values to the serial interface using
Serial.println(value);
in your loop method
on the processing side use a PrintWriter to write the data read from the serial port to a file
import processing.serial.*;
Serial mySerial;
PrintWriter output;
void setup() {
mySerial = new Serial( this, Serial.list()[0], 9600 );
output = createWriter( "data.txt" );
}
void draw() {
if (mySerial.available() > 0 ) {
String value = mySerial.readString();
if ( value != null ) {
output.println( value );
}
}
}
void keyPressed() {
output.flush(); // Writes the remaining data to the file
output.close(); // Finishes the file
exit(); // Stops the program
}
Related
I want to get Processing to read Strings from Arduino.
I send two Strings massages from the arduino and I want to store them in two different variables on Processing.
I tried to do it, but the two Strings are passed to the first variable and the second variable remains empty. I don't understand why this is the case. Can someone help?
Regards
Arduino Code
void setup() {
Serial.begin(9600);
delay(1000);
Serial.println("1.first message");
Serial.println("2.second message");
delay(100);
}
void loop() {
}
Processing Code
import processing.serial.*;
Serial myPort;
void setup() {
myPort=new Serial(this, "COM3", 9600);
}
void draw() {
String s1=myPort.readStringUntil('\n');
String s2=myPort.readStringUntil('\n');
// printing variables
if(s1!=null){
print("s1:",s1);
}
if(s2!=null){
println("s2:",s2);
}
}
The following works on my Mac system. The incoming strings are placed in a string array as they arrive. The string at index[0] then becomes s1 and the string at index[1] is s2. I also added a delay(100); between the two strings on the Arduino side, but this may not be necessary; you can try it both ways.
import processing.serial.*;
Serial myPort;
String[] s; // Array to hold two strings.
int counter = 0;
void setup() {
printArray(Serial.list()); // List of serial ports
// Enter appropriate number for your system
myPort = new Serial(this, Serial.list()[2], 9600);
s = new String[2];
println("===========");
}
void draw() {
String str = myPort.readStringUntil('\n');
if(str != null) {
s[counter] = str;
if(counter == 0){
println("s1 = ",s[0]);
} else {
println("s2 = ",s[1]);
}
counter++;
}
}
I have 2 Arduino and 2 xbee. I send 2 sensor data from Arduino 1 (router) to Arduino to (coordinator):
On coordinator, I receive wireless data from this 2 sensors(from router) perfectly.
The data stream is something like this:
20.1324325452924 divided in: -first sensor(temperature): 20.1324325452 -second sensor(gas):924
My goal is to have these 2 values as 2 variables that get updated constantly and then pass these values on to the rest of the program to make something like print on LCD or something else:
temperature=20.1324325452 gas=924
I managed to divide that initial string that I receive on serial (20.1324325452924) in 2 variables but values from this 2 variables not updating like in the initial string (when sensor values are changed):
My code:
LiquidCrystal lcd(12,11,10,9,8,7);
String temperature;
String gas;
String readString;
char IncomingData[13];
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0)
{
char IncomingData = Serial.read();
readString += IncomingData ;
temperature = readString.substring(0, 13); //get the first 13 characters
gas = readString.substring(13, 16); //get the last 3 characters
Serial.print(IncomingData); //here I have my string: 20.1324325452924 which is updating properly when I have sensor values changes
// Process message when new line character is DatePrimite
if (IncomingData == '\n')
{
Serial.println(temperature);
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.write("T:");
lcd.print(temperature);
delay(500);
temperature = ""; // Clear DatePrimite buffer
Serial.println(gaz);
lcd.begin(16, 2);
lcd.setCursor(0,1);
lcd.write("G:");
lcd.print(gas);
delay(500);
gaz = ""; // Clear DatePrimite buffer
}
}
}
Output from serial: 20.1324325452924
20.1324325452 924
First string it's updating when I receive new sensor data but the next 2 remains the same every time. I'm stuck for days I don't know to do this work. All I need to do is to divide the initial string which contains the data from 2 sensors in 2 variables that get updated constantly and then pass these values on to the rest of the program to make something like print on LCD.
Does anyone have any idea how to make this work?
Split the data after you receive the complete string.
void loop() {
while(!Serial.available()); // wait till data to be filled in serial buffer
String incommingStr = Serial.readStringUntil('\n'); // read the complete string
String temperature = incommingStr.substring(0, 13);
String gas = incommingStr.substring(13, 16);
Serial.print(incommingStr);
Serial.println(temperature);
Serial.println(gas);
lcd.setCursor(0,0);
lcd.print(temperature);
lcd.setCursor(0,1);
lcd.print(gas);
delay(500);
}
You only need to call lcd.begin() once. Calling it from the setup() function.
you have to modify the program like this: (do an action on readString in loop)
// Process message when new line character is DatePrimite
if (IncomingData == '\n')
{
Serial.println(temperature);
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.write("T:");
lcd.print(temperature);
delay(500);
temperature = ""; // Clear DatePrimite buffer
Serial.println(gaz);
lcd.begin(16, 2);
lcd.setCursor(0,1);
lcd.write("G:");
lcd.print(gas);
delay(500);
gaz = ""; // Clear DatePrimite buffer
readString = ""; //clear either you concatenate at each loop!!*******
}
I'm trying to read a text file in an Arduino SD card reader and copy its text into a string variable, but the function .read always returns -1. How can I solve this problem?
Here's the code:
#include <SPI.h>
#include <SD.h>
File mappa;
String text;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
mappa = SD.open("map.txt");
// if the file opened okay, write to it:
if (mappa) {
Serial.println("File aperto");
} else {
// if the file didn't open, print an error:
Serial.println("error opening map.txt");
}
Serial.println("map.txt:");
// read from the file until there's nothing else in it:
while (mappa.available()) {
Serial.write(mappa.read());
// text = parseInt(mappa.read());
}
Serial.println(text);
// close the file:
mappa.close();
}
void loop() {
// nothing happens after setup
}
I know that .read() returns an array of integers, but I don't know how to access them separately.
After further research, I got how .read works: It reads the character its cursor is pointing at while advancing the cursor.
So, in order to read the entirety of the file you have to remove the Serial.write portion and convert the characters into char:
String finalString = "";
while (mappa.available())
{
finalString += (char)mappa.read();
}
I'm currently experimenting with sending a string to my Arduino Yun and trying to get it to reply back depending on what I send it.
I picked up a framework of some code here and have been experimenting with it but apart from the serial monitor displaying 'ready' I can't make it go any further.
The code is:
//declace a String to hold what we're inputting
String incomingString;
void setup() {
//initialise Serial communication on 9600 baud
Serial.begin(9600);
while(!Serial);
//delay(4000);
Serial.println("Ready!");
// The incoming String built up one byte at a time.
incomingString = "";
}
void loop () {
// Check if there's incoming serial data.
if (Serial.available() > 0) {
// Read a byte from the serial buffer.
char incomingByte = (char)Serial.read();
incomingString += incomingByte;
// Checks for null termination of the string.
if (incomingByte == '\0') {
// ...do something with String...
if(incomingString == "hello") {
Serial.println("Hello World!");
}
incomingString = "";
}
}
}
Can anyone point me in the right direction?
Thanks
I suspect the problem is that you're adding the null terminator onto the end of your string when you do: incomingString += incomingByte. When you're working with string objects (as opposed to raw char * strings) you don't need to do that. The object will take care of termination on its own.
The result is that your if condition is effectively doing this: if ("hello\0" == "hello") .... Obviously they're not equal, so the condition always fails.
I believe the solution is just to make sure you don't append the byte if it's null.
Try This:
String IncomingData = "";
String Temp = "";
char = var;
void setup()
{
Serial.begin(9600);
//you dont have to use it but if you want
// if(Serial)
{
Serial.println("Ready");
}
//or
while(!Serial)
{delay(5);}
Serial.println("Ready");
void loop()
{
while(Serial.available())
{
var = Serial.read();
Temp = String(var);
IncomingData+= Temp;
//or
IncomingData.concat(Temp);
// you can try
IncomindData += String(var);
}
Serial.println(IncomingData);
IncomingData = "";
}
I am trying to create an app that would allow the user some sounds and then use this in a playback fashion.
I would like to have my application play a .wav file that the user will record.
I am having trouble figuring out how to code this, as I keep getting a error.
==== JavaSound Minim Error ====
==== Error invoking createInput on the file loader object: null
Snippet of code:
import ddf.minim.*;
AudioInput in;
AudioRecorder recorder;
RadioButtons r;
boolean showGUI = false;
color bgCol = color(0);
Minim minim;
//Recording players
AudioPlayer player1;
AudioPlayer player2;
void newFile()
{
countname =(name+1);
recorder = minim.createRecorder(in, "data/" + countname + ".wav", true);
}
......
void setup(){
minim = new Minim(this);
in = minim.getLineIn(Minim.MONO, 2048);
newFile();
player1 = minim.loadFile("data/" + countname + ".wav");// recording #1
player2 = minim.loadFile("data/" + countname + ".wav");//recording #2
void draw() {
// Draw the image to the screen at coordinate (0,0)
image(img,0,0);
//recording button
if(r.get() == 0)
{
for(int i = 0; i < in.left.size()-1; i++)
}
if ( recorder.isRecording() )
{
text("Currently recording...", 5, 15);
}
else
{
text("Not recording.", 5, 15);
}
}
//play button
if(r.get() == 1)
{
if(mousePressed){
.......
player_1.cue(0);
player_1.play();
}
if(mousePressed){
.......
player_2.cue(0);
player_2.play();
}
}
The place where I have a problem is here:
player1 = minim.loadFile("data/" + countname + ".wav");// recording #1
player2 = minim.loadFile("data/" + countname + ".wav");//recording #2
The files that will be recorded will be 1.wav, 2.wav. But I can not place this in the
player1.minim.loadFile ("1.wav");
player2.mminim.loadFile("2.wav");
How would I do this?
As indicated in the JavaDoc page for AudioRecorder [1], calls to beginRecord(), endRecord() and save() will need to happen so that whatever you want to record is actually recorded and then also saved to disk. As long as that does not happen there is nothing for loadFile() to load and you will therefore receive errors. So the problem lies in your program flow. Only when your program reaches a state where a file has already been recorded and saved, you can actually load that.
There are probably also ways for you to play back whatever is being recorded right at the moment it arrives in your audio input buffer (one would usually refer to such as 'monitoring'), but as i understand it, that is not what you want.
Aside this general conceptual flaw there also seem to be other problems in your code, e.g. countname is not being iterated between two subsequent loadFile calls (I assume that it should be iterated though); Also at some point you have "player_1.play();" (note the underscore), although you're probably refering to this, differently written variable earlier initialized with "player1 = minim.loadFile(...)" ? ...
[1] http://code.compartmental.net/minim/javadoc/ddf/minim/AudioRecorder.html
This is the approach to record from an audio file into an AudioRecorder object. You load a file, play it and then you choose what section to save into another file that you can play using and AudioPlayer object or your favorite sound player offered by your OS.
Related to
I am having trouble figuring out how to code this, as I keep getting a
error.
Despite it says it is an error, it doesn't affect executing your program. I would consider this a warning and ignore it. If you want to fix it, I believe you will need to edit the file's tags to properly set their values.
INSTRUCTIONS: In the code, define your file to play. When you run the sketch, press r to begin recording, r again to stop recording. Don't forget to press s to save the file to an audio file which will be located in the data folder.
NOTE: If you need to play wav files, you will need a Sampler object instead of a FilePlayer one.
//REFERENCE: https:// forum.processing.org/one/topic/how-can-i-detect-sound-with-my-mic-in-my-computer.html
//REFERENCE: https:// forum.processing.org/two/discussion/21842/is-it-possible-to-perform-fft-with-fileplayer-object-minim
/**
* This sketch demonstrates how to use an <code>AudioRecorder</code> to record audio to disk.
* Press 'r' to toggle recording on and off and the press 's' to save to disk.
* The recorded file will be placed in the sketch folder of the sketch.
* <p>
* For more information about Minim and additional features,
* visit http://code.compartmental.net/minim/" target="_blank" rel="nofollow">http://code.compartmental.net/minim/</a>;
*/
import ddf.minim.*;
import ddf.minim.ugens.*;
import ddf.minim.analysis.*;
Minim minim;
FilePlayer player;
AudioOutput out;
AudioRecorder recorder;
void setup()
{
size(512, 200, P3D);
textFont(createFont("Arial", 12));
minim = new Minim(this);
player = new FilePlayer(minim.loadFileStream("energeticDJ.mp3"));
// IT DOESN'T WORK FOR WAV files ====> player = new FilePlayer(minim.loadFileStream("fair1939.wav"));
out = minim.getLineOut();
TickRate rateControl = new TickRate(1.f);
player.patch(rateControl).patch(out);
recorder = minim.createRecorder(out, dataPath("myrecording.wav"),true);
player.loop(0);
}
void draw()
{
background(0);
stroke(255);
// draw a line to show where in the song playback is currently located
float posx = map(player.position(), 0, player.length(), 0, width);
stroke(0, 200, 0);
line(posx, 0, posx, height);
if ( recorder.isRecording() )
{
text("Currently recording...", 5, 15);
} else
{
text("Not recording.", 5, 15);
}
}
void keyReleased()
{
if ( key == 'r' )
{
// to indicate that you want to start or stop capturing audio data, you must call
// beginRecord() and endRecord() on the AudioRecorder object. You can start and stop
// as many times as you like, the audio data will be appended to the end of the buffer
// (in the case of buffered recording) or to the end of the file (in the case of streamed recording).
if ( recorder.isRecording() )
{
recorder.endRecord();
} else
{
recorder.beginRecord();
}
}
if ( key == 's' )
{
// we've filled the file out buffer,
// now write it to the file we specified in createRecorder
// in the case of buffered recording, if the buffer is large,
// this will appear to freeze the sketch for sometime
// in the case of streamed recording,
// it will not freeze as the data is already in the file and all that is being done
// is closing the file.
// the method returns the recorded audio as an AudioRecording,
// see the example AudioRecorder >> RecordAndPlayback for more about that
recorder.save();
println("Done saving.");
}
}