I am currently trying to get a value (Yes!) from the Arduino to a text file (data.txt).
The problem is that the data isn't being read from the Arduino's Serial. When I tried to simple print the value to the prompt in processing, I came out empty handed.
Below is my code for the Arduino
//Just a basic program to write to the Serial the word/phrase; `Yes!`.
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println("Yes!");
}
Below is my code for processing:
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
}
Yes, this code was found from this stackoverflow question.
Any help would be greatly appreciated!
Check out this line:
mySerial = new Serial( this, Serial.list()[0], 9600 );
This line assumes you only have one serial connection. If you have more than one serial connection, you're going to have to change the hard-coded index being used in this line.
Related
I connected my Bluetooth module to the mobile phone and made up a code to communicate between Arduino and mobile through Bluetooth (send messages from Bluetooth module to device and vice versa).
Now I want to make a response, which means that if I send from the mobile "hi" the arduino replies and says "Hello" or whatever.
I have tried tons of codes but none worked, so would anyone please help me?
#include <SoftwareSerial.h>
SoftwareSerial myserial (6,5);
void setup() {
myserial.begin(9600);
Serial.begin (9600);
}
void loop() {
if (myserial.available()) {
Serial.write(+ myserial.read());
}
if (Serial.available()) {
myserial.write(Serial.read());
}
}
Another code but making a loop without sending anything
#include <SoftwareSerial.h>
SoftwareSerial myserial(6,5); //Arduino: R:5,T:6; bluetooth: T:5, R:6;
void setup() {
myserial.begin(9600);
Serial.begin (9600);
}
void loop() {
if (myserial.available()) {
Serial.write(myserial.read());
}
if (Serial.available()) {
myserial.write(Serial.read());
}
for (int i = 0; i=2; i++) {
myserial.write("hello");
}
if (myserial.read() =="n") {
myserial.write("hello");
}
}
You need to build your serial string char by char using the SerialEvent() interrupt, then do a String comparison using the .equals method. Despite many people will tell you that String types are 'evil' (see this and this) it might be a good solution for making things clearer (and perhaps a bit easier if you don't want to mess with C char strcmp() functions and pointers. In the end, the String type is there for you and I see no reason for not using it in general projects.
Based on the SerialEvent() documentation [1], and the String reference [2], you could do something like:
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
//Then you compare the inputString with the word you want to detect using the .equals method from the String class
if(inputString.equals("Hi"){
Serial.println("Hello");
}
// clear the string for a new comparison:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the hardware serial RX. This
routine is run between each time loop() runs, so using delay inside loop can
delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
EDIT 1: Of course, you can replace the Serial object from this example code with your own myserial object from the BlueTooth communication.
First off this is my first Arduino project but I have coded basic c++ before. Anyway I am struggling to get the Arduino to acknowledge when save data to a variable. I know it's receiving the data but its not getting appended to my data variable. Here's the code and if I could get a basic explanation of what I did wrong I would appreciate it.
#include <SoftwareSerial.h>
SoftwareSerial BTserial(0, 1);
//declair pins
void setup() {
Serial.begin(9600);
//setup pins
}
void loop() {
String data;
bool run = false;
data = "";
while (Serial.available()) {
char inChar = (char)Serial.read();
Serial.print(inChar); //I know it is getting the sent data because prints here
if (inChar == '\n') {
Serial.print("Received Command: ");
if (data == "")
Serial.print("Data is NULL"); //this always prints too
Serial.print(data);
Serial.print('\n');
run = true;
break;
} else {
data += inChar;
}
}
if(run) {
//do stuff
}
}
I know there are plenty of websites I could copy paste from but I want to make my own and understand what I did wrong. I did read them though.
For example if I send command from my phone the output would be
command
Received Command: Data is NULL
The following segment will always appear null here on the first loop unless you receive characters other than newline when your serial begins listening because the program executes from top to bottom and you haven't given data a value yet here.
if (data == "") {
Serial.print("Data is NULL"); //this always prints too
}
P.S. This expression
String data;
data = "";
can be simplified to
String data ="";
More efficient.
I'll try to provide more information if I can figure out the issue once I get some sample data.
I'm trying to set up communications between my PC, and my Arduino with the Processing environment, but the Arduino doesn't seem to be getting any of the messages I send. I doubled checked, and I know I can receive messages from the Arduino, but I can't send anything back. Does anyone know how to fix this?
Here's my test code for processing:
import processing.serial.*;
Serial myPort;
void setup(){
myPort = new Serial(this, Serial.list()[0], 9600);
}
void draw(){
myPort.write("test");
while (myPort.available() > 0) {
String inByte = myPort.readString();
println(inByte);
}
}
Here's my test code for the Arduino:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
String data;
void loop() {
// put your main code here, to run repeatedly:
//Serial.println("is running");
if (Serial.available() > 0) {
// read the incoming byte:
data = Serial.readString();
// say what you got:
Serial.print("I received: ");
Serial.println(data);
}
}
I'd appreciate any help I can get! Thanks!
Okay, after looking into several different posts on the Arduino forum, I figured out what the problem is. The function processing uses to send data over serial does not automatically include a return character at the end of the string. This is important because the Arduino won't read from the serial buffer until it sees that return character. All I had to do was add "\r\n" to the end of each string I sent over serial, and that solved the problem!
My code is super simple, but I'm at a loss how to do a simple task.
Each time an RFID card is read, I want it to trigger an event once. This is working fine in isolation.
However, I also want a different one-time event to occur each time a card is taken away. This bit seems to mess up the whole thing.
I'm using the MFRC522 Library.
Could anyone tell me the method to do both within the same code? I'm kind of green as to all this.
Many thanks in advance :) My code is here:
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
bool executed = false;
void setup() {
Serial.begin(9600); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
}
void loop() {
if ( mfrc522.PICC_IsNewCardPresent()) {
if ( mfrc522.PICC_ReadCardSerial()) {
Serial.println("Great!.. each time a card is read and re-read this text will print *ONCE ONLY*");
}
}
// BELOW I WANT TO EXECUTE A COMMAND *ONCE ONLY* EACH TIME A CARD IS TAKEN AWAY
// WHEN UNCOMMENTED, THE "Oh dear.." PRINTS CONTINUOUSLY
// if ( !mfrc522.PICC_IsNewCardPresent()) {
// Serial.println("Oh dear... this seems to keep printing... ");
// }
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
}
Also, the revised code that I also tried is as follows. This also did not work. It printed the card present fine but when the card was taken away multiple prints continuously occured:
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9
#define SS_PIN 10
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
bool executed = false;
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
Serial.println("Waiting for RFID-chip...");
}
void loop() {
if ( mfrc522.PICC_IsNewCardPresent()) {
if ( mfrc522.PICC_ReadCardSerial()) {
Serial.println("Great!.. each time a card is read and re-read this text will print *ONCE ONLY*");
executed = true;
}
}
else {
if (executed) {
Serial.println("Oh dear... this seems to keep printing... ");
executed = false;
}
}
}
Perhaps instead of having 2 if stamenents, you can combine them into an if-else statement. You also want to use the variable executed you created at the top inside your conditionals.
Here is how I see it:
if ( mfrc522.PICC_IsNewCardPresent()) {
if ( mfrc522.PICC_ReadCardSerial()) {
Serial.println("Great!.. each time a card is read and re-read this text will print *ONCE ONLY*");
executed = true;
}
}
else {
if (executed) {
Serial.println("Oh dear... this seems to keep printing... ");
executed = false;
}
}
I found a possible solution using "CurrentCard" as variable to store te current card UID and "CardTimeOut" as time limit variable to reset the stored UID when you leave the card.
Hope this helps you!
String CurrentCard;
int CardTimeOut = 0;
void loop {
// Look for new cards
if (mfrc522.PICC_IsNewCardPresent())
{
CardTimeOut = 0;
if (mfrc522.PICC_ReadCardSerial())
{
String content= "";
for (byte i = 0; i < mfrc522.uid.size; i++)
{
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
content.toUpperCase();
if (content.substring(1) != CurrentCard)
{
if (content.substring(1) == "D7 48 35 4B") //change here the UID of the card/cards that you want to give access
{
Serial.println("Authorized access");
Serial.println();
//Do something
}
else
{
Serial.println(" Access denied");
}
CurrentCard = content.substring(1);
}
}
}
if (CardTimeOut > 10)
{
CurrentCard = "";
}
CardTimeOut += 1;
}
I have managed to connect the Arduino sketch to a Processing sketch, but I am stuck on how I get the Arduino to control an object in the processing.
Using a tilt sensor, the aim is that when the tilt sensor is tilted one way it will move the object in processing that way, and then when it is tilted the other way it will move the object the other way.
Can anyone help?
This is my code for Arduino:
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
// put your main code here, to run repeatedly:
Serial.println("Hello, World!");
delay(100);
}
This is my code for Processing:
import processing.serial.*;
Serial myPort;
String val;
PShape bike;
void setup()
{
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
size(800, 600);
bike = createShape(RECT, 0, 0, 200, 200);
bike.setFill(color(102, 204, 0));
bike.setStroke(false);
}
void draw()
{
if ( myPort.available() > 0)
{ // If data is available,
val = myPort.readStringUntil('\n'); // read it and store it in val
}
println(val); //print it out in the console
shape(bike, 0, 0);
}
Break your problem down into smaller pieces.
Write a simple example sketch (in other words a [mcve]) that only does one thing: it simply reads in values from the Arduino and prints them to the console. It doesn't even really need to draw anything to the screen.
Write another [mcve] that just does one thing: it simply moves an object on screen. Notice that this should not involve your Arduino code at all. Try to make it as standalone as possible.
When you get both of these working completely separately, then you can think about combining them into one sketch. And if you get stuck, you can post that [mcve] along with a specific technical question.
Here's a sketch that moves an object based on the mouse position, just go get you started:
float objectX = 0;
void setup() {
size(500, 100);
}
void draw() {
if (mouseX > objectX) {
objectX ++;
}
background(0);
ellipse(objectX, height/2, 25, 25);
}
your arduino code looks that´s only hello world.
What I do to use arduino libs (sensors, actuators) using processing, is to split the tasks for 2 arduinos: one that uses the libs and send/recive data from the other arduino. This second arduino is loaded with the standard firmdata (firmware), that allows to comunicate easily and directly from processing sketch: http://playground.arduino.cc/Interfacing/Processing