Arduino ESP8266 EEPROM commit() returns false - arduino

I want to save the SSID and password in the EEPROM in my Arduino Sketch Wlan.
Actually everything works so far, except that the commit () returns a false. And that's why the memory is empty again after a restart.
My code:
void writePROM()
{
EEPROM.begin(0);
EEPROM.write(0, 0xAA);
byte ssidLength = ssid.length();
byte passLength = pass.length();
int adress = 2;
EEPROM.write(1, (byte)ssidLength);
for(int i = 0; i < ssidLength; i++)
{
EEPROM.write(adress + i, (byte)ssid[i]);
}
adress += ssidLength + 1;
EEPROM.write(adress++, passLength);
for(int i = 0; i < passLength; i++)
{
EEPROM.write(adress + i, pass[i]);
}
bool bRc = EEPROM.commit();
if(bRc)
{
Serial.println("Write successfully");
}
else
{
Serial.println("Write error");
}
Serial.println("Write name to EEPROM = " + ssid);
Serial.println("Write password to EEPROM = " + pass);
}
What I am doing wrong?

First of all, good on you for checking the result of the commit() call.
You're passing 0 when you initialize the EEPROM library:
EEPROM.begin(0);
You need to pass it the number of bytes that you're looking to store using it.
You can read the code for the EEPROM library to confirm this:
void EEPROMClass::begin(size_t size) {
if (size <= 0) {
DEBUGV("EEPROMClass::begin error, size == 0\n");
return;
}
If you pass 0 it simply returns without doing any setup. You can also see that commit() will do nothing in this case:
bool EEPROMClass::commit() {
if (!_size)
return false;
In your case you should call EEPROM.begin() with at least the maximum size of an SSID and password plus one each for the zero terminating bytes (so, 32 characters for the SSID, 63 for the password, plus 2 for 97).
But, as #Juraj pointed out in the comments, you don't need to do any of this as the ESP8266 will automatically persist the Wifi credentials.

Related

Serial communication between two arduino

I am trying to write a Serial read function. That function will give me a data between '#' (start character) and '*' (end character). I tried to write it and it looks like it is kinda work but not perfectly. The problem is that:
I have two arduino. One of these send "MARCO" and other arduino read it. If the readed data is "MARCO" it is write to serial monitor "MARCOCORRECT" else it is write to serial monitor the readed data. Normally it must just write "MARCOCORRECT" because I only send "MARCO" but it don't. It writes something else too. I tried lower baud rate too but it is still same. How can I fix it?
Sender Code
#define BAUD_RATE 38400
void setup()
{
Serial.begin(BAUD_RATE);
}
String readed = "";
void loop()
{
String readed;
while (Serial.available() > 0)
{
readed += Serial.read();
}
Serial.println("#MARCO*");
}
Reader Code
#define BAUD_RATE 38400
#define MSG_START '#'
#define MSG_END '*'
String readed;
char readedChar;
bool msgStart = false;
String serialReadFunc()
{
readedChar = '0';
readed = "";
while (Serial.available() > 0 || msgStart)
{
if (readedChar == MSG_START)
{
msgStart = true;
}
readedChar = (char)Serial.read();
if (readedChar == MSG_END)
{
msgStart = false;
break;
}
if (msgStart)
{
readed += readedChar;
}
}
return readed;
}
void setup()
{
Serial.begin(BAUD_RATE);
}
void loop()
{
if (serialReadFunc() == "MARCO")
{
Serial.println("MARCOCORRECT");
}
else
Serial.println(readed);
}
Console Image On Proteus
Console Image Proteus
I suspect you're having synchronization issues. I may be wrong, though, and I'm unable to test it at the moment.
I'd recommend trying to insert a delay on the sender, like so:
String readed;
while (Serial.available() > 0)
{
readed += Serial.read();
}
delay(10);
Serial.println("#MARCO*");
It would also be interesting to see the return value of the reader Serial.available(). Again, not 100% sure, but I believe the buffer may be full (the buffer holds 64 bytes).

Write String to permanent flash memory of Arduino ESP32

I want to write some text into the flash memory of an Arduino ESP32. It works kinda but not as I want it to.
void writeString(const char* toStore, int startAddr) {
int i = 0;
for (; i < LENGTH(toStore); i++) {
EEPROM.write(startAddr + i, toStore[i]);
}
EEPROM.write(startAddr + i, '\0');
EEPROM.commit();
}
My call
writeString("TEST_STRING_TO_WRITE", 0);
only writes TEST into the memory. I do not understand why. Is that because of the _? Or am I missing something different?
Here is the used LENGTH macro
#define LENGTH(x) (sizeof(x)/sizeof(x[0]))
and the method I use to read the string from the memory again (which seems to work correctly):
String readStringFromFlash(int startAddr) {
char in[128];
char curIn;
int i = 0;
curIn = EEPROM.read(startAddr);
for (; i < 128; i++) {
curIn = EEPROM.read(startAddr + i);
in[i] = curIn;
}
return String(in);
}
Where on earth did you get that LENGTH macro from? It’s surreal.
sizeof will not do what you want here. It’s a compile-time function that computes the storage requirements of its argument. In this case it should return the length in bytes of a character pointer, not the string it points to.
You want to use strlen(), assuming your char* is a properly terminated C string. Add one to make sure the ‘\0’ at the end gets stored, too.
#define LENGTH(x) (strlen(x) + 1)
Below is the code to demonstrate the storing as well as retrieving of the string ssid in the EEPROM (permanent storage).
#include "EEPROM.h"
int addr = 0;
#define EEPROM_SIZE 64
// the sample text which we are storing in EEPROM
char ssid[64] = "CARNIVAL OF RUST";
void setup() {
Serial.begin(115200);
Serial.println("starting now...");
if (!EEPROM.begin(EEPROM_SIZE)) {
Serial.println("failed to init EEPROM");
while(1);
}
// writing byte-by-byte to EEPROM
for (int i = 0; i < EEPROM_SIZE; i++) {
EEPROM.write(addr, ssid[i]);
addr += 1;
}
EEPROM.commit();
// reading byte-by-byte from EEPROM
for (int i = 0; i < EEPROM_SIZE; i++) {
byte readValue = EEPROM.read(i);
if (readValue == 0) {
break;
}
char readValueChar = char(readValue);
Serial.print(readValueChar);
}
}
void loop() {
}

Sending array data from Processing to Arduino

I successfully managed to send a single integer from processing to Arduino but now I want to send an array of three integers and I can't get it working. I want to create a buzzer feedback with Arduino which processing will control which buzzer to activate. For example, the data send from processing should be [1,0,1] meaning sensor 1 and 3 should start working. The buzzers should be able to be activated simultaneously in case that [1,1,1] goes through.
This is the code I have so far:
I am trying to understand what data is being sent back to Arduino to know how to use it and I keep getting either a null value or a random integer.
I'm trying to learn how to do this so apologies if the code is bad.
Arduino
void setup(){
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop(){
if (Serial.available()){
const char data = Serial.read();
char noteBuzzer[] = {data};
for (int i = 0 ; i < sizeof(noteBuzzer); i++) {
}
Serial.print(noteBuzzer[1]);
}
}
Processing
import processing.serial.*;
String notes[];
String tempo[];
Serial myPort;
String val;
void setup(){
size(200,200);
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
notes = loadStrings("data/notes.txt");
tempo = loadStrings("data/tempo.txt");
}
void draw() {
if (keyPressed == true)
{
if (key == '1') {
println("Start");
readNotes();
}
}
}
void readNotes(){
for (int i = 0 ; i < notes.length; i++) {
println(notes[i]);
//println(tempo[i]);
myPort.write(notes[i]);
delay(int(tempo[i])); //this will be the tempo?
if ( myPort.available() > 0)
{
val = myPort.readStringUntil('\n');
println("Arduino",val);
}
}
}
If you're data is an array that always has 3 items and each of those items are always either 1 or 0 (bits), you could store that whole data in a single byte (and still have 5 more bits to spare). Sending and receiving a byte is pretty simple with Arduino.
Here's a basic sketch that shows you how to flip 3 bits in a single byte:
// the state as a byte
byte buzzerState = 0B000;
void setup(){
textFont(createFont("Courier New",18),18);
}
void draw(){
background(0);
text("DEC: " + buzzerState +
"\nBIN:" + binary(buzzerState,3),10,40);
}
void keyPressed(){
if(key == '1'){
buzzerState = flipBit(buzzerState,0);
}
if(key == '2'){
buzzerState = flipBit(buzzerState,1);
}
if(key == '3'){
buzzerState = flipBit(buzzerState,2);
}
}
// flips a bit at a given index within a byte and returns updated byte
byte flipBit(byte state,int index){
int bit = getBitAt(state,index);
int bitFlipped = 1 - bit;
return setBitAt(state,index,bitFlipped);
}
// returns the integer value of a bit within a byte at the desired index
int getBitAt(byte b,int index){
index = constrain(index,0,7);
return b >> index & 1;
}
// sets an individual bit at a desired index on or off (value) and returns the updated byte
byte setBitAt(byte b,int index, int value){
index = constrain(index,0,7);
value = constrain(value,0,1);
if(value == 1) b |= (1 << (index));
else b &= ~(1 << (index));
return b;
}
Use keys '1','2' and '3' to flip the bits.
Note that in keypress we're always updating the same byte.
The text will display the decimal value first and the binary value bellow.
This is the most efficient way to send your data and the simplest in terms of serial communication. On the Arduino side you can simply use bitRead() on the byte you get from Serial.read(). For more on binary/bits/bytes be sure to read the BitMath Arduino tutorial. Binary may seem intimidating at first, but it's really not that bad once you practice a bit and it's totally worth knowing.
Here's an updated version of the code above that sends the byte to Arduino on the first available serial port (be sure to change Serial.list()[0] with what makes sense for your setup and press 's' to send an update to Arduino:
import processing.serial.*;
// the state as a byte
byte buzzerState = 0B000;
Serial port;
void setup(){
textFont(createFont("Courier New",18),18);
try{
port = new Serial(this,Serial.list()[0],9600);
}catch(Exception e){
e.printStackTrace();
}
}
void draw(){
background(0);
text("DEC: " + buzzerState +
"\nBIN:" + binary(buzzerState,3),10,40);
}
void keyPressed(){
if(key == '1'){
buzzerState = flipBit(buzzerState,0);
}
if(key == '2'){
buzzerState = flipBit(buzzerState,1);
}
if(key == '3'){
buzzerState = flipBit(buzzerState,2);
}
if(key == 's'){
if(port != null){
port.write(buzzerState);
}else{
println("serial port is not open: check port name and cable connection");
}
}
}
// flips a bit at a given index within a byte and returns updated byte
byte flipBit(byte state,int index){
int bit = getBitAt(state,index);
int bitFlipped = 1 - bit;
return setBitAt(state,index,bitFlipped);
}
// returns the integer value of a bit within a byte at the desired index
int getBitAt(byte b,int index){
index = constrain(index,0,7);
return b >> index & 1;
}
// sets an individual bit at a desired index on or off (value) and returns the updated byte
byte setBitAt(byte b,int index, int value){
index = constrain(index,0,7);
value = constrain(value,0,1);
if(value == 1) b |= (1 << (index));
else b &= ~(1 << (index));
return b;
}
And here's a super basic Arduino sketch:
byte buzzerState;
void setup() {
Serial.begin(9600);
//test LEDs setup
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop() {
if(Serial.available() > 0){
buzzerState = Serial.read();
bool bit0 = bitRead(buzzerState,0);
bool bit1 = bitRead(buzzerState,1);
bool bit2 = bitRead(buzzerState,2);
//test LEDs update
digitalWrite(10,bit0);
digitalWrite(11,bit1);
digitalWrite(12,bit2);
}
}
If you connect 3 LEDs to pins 10,11,12 you should them toggle as you press keys '1','2','3' then 's' in Processing
One way around binary in Processing could be using a String representation of your data (e.g. "00000101" for [1,0,1]) and unbinary() to convert that String to an integer value you can write to serial, but it will be a bit annoying to getting and setting a character at an index (and potentially parsing that char to it's integer value and back)
When you need to send more than a byte things get a bit more complicated as you need to handle data corruption/interruptions, etc. In these situations it's best to setup/design a communication protocol based on your needs and this isn't easy if you're just getting started with Arduino, but not impossible either. Here's an example, there are many more online.
One quick and dirty thing you could try is sending that data as string terminated by a new line character (\n) which you could buffer until in Arduino then read 4 bytes at a time, discarding the \n when parsing:
e.g. sending "101\n" from Processing, representing [1,0,1] then on the Arduino side use Serial.readStringUntil('\n') and a combination of charAt() and toInt() to access each integer within that that string.
Here's an example Processing sketch:
import processing.serial.*;
// the state as a byte
String buzzerState = "010\n";
Serial port;
void setup(){
textFont(createFont("Courier New",18),18);
try{
port = new Serial(this,Serial.list()[0],9600);
}catch(Exception e){
e.printStackTrace();
}
}
void draw(){
background(0);
text(buzzerState,30,50);
}
void keyPressed(){
if(key == '1'){
buzzerState = flipBit(buzzerState,0);
}
if(key == '2'){
buzzerState = flipBit(buzzerState,1);
}
if(key == '3'){
buzzerState = flipBit(buzzerState,2);
}
if(key == 's'){
if(port != null){
port.write(buzzerState);
}else{
println("serial port is not open: check port name and cable connection");
}
}
}
String flipBit(String state,int index){
index = constrain(index,0,2);
// parse integer from string
int bitAtIndex = Integer.parseInt(state.substring(index,index+1));
// return new string concatenating the prefix (if any), the flipped bit (1 - bit) and the suffix
return state = (index > 0 ? state.substring(0,index) : "") + (1 - bitAtIndex) + state.substring(index+1);
}
And an Arduino one based on Arduino > File > Examples > 04.Communication > SerialEvent:
/*
Serial Event example
When new serial data arrives, this sketch adds it to a String.
When a newline is received, the loop prints the string and
clears it.
A good test for this is to try it with a GPS receiver
that sends out NMEA 0183 sentences.
Created 9 May 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialEvent
*/
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
// test LEDs setup
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// process string
bool bit0 = inputString.charAt(2) == '1';
bool bit1 = inputString.charAt(1) == '1';
bool bit2 = inputString.charAt(0) == '1';
//test LEDs update
digitalWrite(10,bit0);
digitalWrite(11,bit1);
digitalWrite(12,bit2);
// clear the string:
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;
}
}
}
Note this is more prone to error and used 4 times as much data as the the single byte option.

Arduino Serial communication output

I have 2 Arduinos Leonardo and I want them to communicate itself, so I did the following code:
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
String outMessage = ""; // String to hold input
while (Serial.available() > 0) { // check if at least 1 char is available
char inChar = Serial.read();
outMessage.concat(inChar); // add inChar to outMessage
}
if (outMessage != "") {
Serial.println("Sent: " + outMessage); // View Arduino 1 in Serial Monitor 1
Serial1.print(outMessage); // Send to Arduino 2
}
while (Serial1.available() > 0) {
Serial.print("Received: "); // View Arduino 1 in Serial Monitor 2
Serial.print(Serial1.read()); // Received from Arduino 1
Serial.println();
}
}
I want to send a message from Arduino 1, print in Serial Monitor and send via TX1 to Arduino 2 and vice-versa. The problem is that I don't receive what I was expecting. For instance if I type test:
Arduino 1:
Sent: test
Arduino 2:
Received: t
Received: e
Received: s
Received: t
I also tryed to do the receiving side like the sending side and use Serial.write but with no sucess.
Is there a easier way to do that or to fix it?
Thanks
Has mentioned by Hans, you need a protocol.
This is what I use to consider a message in Arduino to be a complete message:
char inData[10];
int index;
boolean started = false;
boolean ended = false;
String message =("I am Arduino 1 and I am ready");
void setup(){
Serial.begin(9600);
Serial.println(message);
}
void loop()
{
while(Serial.available() > 0)
{
char aChar = Serial.read();
if(aChar == '>')
{
started = true;
index = 0;
inData[index] = '\0';
}
else if(aChar == '<')
{
ended = true;
}
else if(started)
{
inData[index] = aChar;
index++;
inData[index] = '\0';
}
}
if(started && ended)
{
int inInt = atoi(inData);
Serial.println(inInt);
}
// Get ready for the next time
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
So, basically a message is considered completed only if it is between the special characters ><, like this: >message<. Then you can do the same on reading.
It does not have to be too complicated. If you look carefully at your last whlie-loop you can see that the software does not get a chance to read more than one character each time it passes through the loop. So that is what you get: one character at a time.
In your first while-loop you did better: you collected all the incoming letters until nothing was available and then sent them all at once. So if you make your last loop look more like the first one, you'll get a better result.
As mentioned a protocol to frame messages is needed between devices. A quick way to do this is to use Bill Porter's EasyTransfer library which does exactly what you are trying to do, over either UART or I2C. It has several examples.
Serial.read() reads only one byte every time you use it. A simple solution would be to store each byte on a char array while Serial.available>0 and then print the String with the whole message that was sent.
char message[40];
int count = 0;
while(Serial.available()>0){
message[count++] = Serial.read();
}
Serial.println(message);

Convert serial.read() into a usable string using Arduino

I'm using two Arduinos to sent plain text strings to each other using NewSoftSerial and an RF transceiver.
Each string is perhaps 20-30 characters in length. How do I convert Serial.read() into a string so I can do if x == "testing statements", etc.?
Unlimited string readed:
String content = "";
char character;
while(Serial.available()) {
character = Serial.read();
content.concat(character);
}
if (content != "") {
Serial.println(content);
}
From Help with Serial.Read() getting string:
char inData[20]; // Allocate some space for the string
char inChar = -1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
void setup() {
Serial.begin(9600);
Serial.write("Power On");
}
char Comp(char* This) {
while (Serial.available() > 0) // Don't read unless there
// you know there is data
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
}
}
if (strcmp(inData, This) == 0) {
for (int i=0; i<19; i++) {
inData[i] = 0;
}
index = 0;
return(0);
}
else {
return(1);
}
}
void loop()
{
if (Comp("m1 on") == 0) {
Serial.write("Motor 1 -> Online\n");
}
if (Comp("m1 off") == 0) {
Serial.write("Motor 1 -> Offline\n");
}
}
You can use Serial.readString() and Serial.readStringUntil() to parse strings from Serial on the Arduino.
You can also use Serial.parseInt() to read integer values from serial.
int x;
String str;
void loop()
{
if(Serial.available() > 0)
{
str = Serial.readStringUntil('\n');
x = Serial.parseInt();
}
}
The value to send over serial would be my string\n5 and the result would be str = "my string" and x = 5
I was asking the same question myself and after some research I found something like that.
It works like a charm for me. I use it to remote control my Arduino.
// Buffer to store incoming commands from serial port
String inData;
void setup() {
Serial.begin(9600);
Serial.println("Serial conection started, waiting for instructions...");
}
void loop() {
while (Serial.available() > 0)
{
char recieved = Serial.read();
inData += recieved;
// Process message when new line character is recieved
if (recieved == '\n')
{
Serial.print("Arduino Received: ");
Serial.print(inData);
// You can put some if and else here to process the message juste like that:
if(inData == "+++\n"){ // DON'T forget to add "\n" at the end of the string.
Serial.println("OK. Press h for help.");
}
inData = ""; // Clear recieved buffer
}
}
}
This would be way easier:
char data [21];
int number_of_bytes_received;
if(Serial.available() > 0)
{
number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
}
bool result = strcmp (data, "whatever");
// strcmp returns 0; if inputs match.
// http://en.cppreference.com/w/c/string/byte/strcmp
if (result == 0)
{
Serial.println("data matches whatever");
}
else
{
Serial.println("data does not match whatever");
}
The best and most intuitive way is to use serialEvent() callback Arduino defines along with loop() and setup().
I've built a small library a while back that handles message reception, but never had time to opensource it.
This library receives \n terminated lines that represent a command and arbitrary payload, space-separated.
You can tweak it to use your own protocol easily.
First of all, a library, SerialReciever.h:
#ifndef __SERIAL_RECEIVER_H__
#define __SERIAL_RECEIVER_H__
class IncomingCommand {
private:
static boolean hasPayload;
public:
static String command;
static String payload;
static boolean isReady;
static void reset() {
isReady = false;
hasPayload = false;
command = "";
payload = "";
}
static boolean append(char c) {
if (c == '\n') {
isReady = true;
return true;
}
if (c == ' ' && !hasPayload) {
hasPayload = true;
return false;
}
if (hasPayload)
payload += c;
else
command += c;
return false;
}
};
boolean IncomingCommand::isReady = false;
boolean IncomingCommand::hasPayload = false;
String IncomingCommand::command = false;
String IncomingCommand::payload = false;
#endif // #ifndef __SERIAL_RECEIVER_H__
To use it, in your project do this:
#include <SerialReceiver.h>
void setup() {
Serial.begin(115200);
IncomingCommand::reset();
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
if (IncomingCommand::append(inChar))
return;
}
}
To use the received commands:
void loop() {
if (!IncomingCommand::isReady) {
delay(10);
return;
}
executeCommand(IncomingCommand::command, IncomingCommand::payload); // I use registry pattern to handle commands, but you are free to do whatever suits your project better.
IncomingCommand::reset();
Here is a more robust implementation that handles abnormal input and race conditions.
It detects unusually long input values and safely discards them. For example, if the source had an error and generated input without the expected terminator; or was malicious.
It ensures the string value is always null terminated (even when buffer size is completely filled).
It waits until the complete value is captured. For example, transmission delays could cause Serial.available() to return zero before the rest of the value finishes arriving.
Does not skip values when multiple values arrive quicker than they can be processed (subject to the limitations of the serial input buffer).
Can handle values that are a prefix of another value (e.g. "abc" and "abcd" can both be read in).
It deliberately uses character arrays instead of the String type, to be more efficient and to avoid memory problems. It also avoids using the readStringUntil() function, to not timeout before the input arrives.
The original question did not say how the variable length strings are defined, but I'll assume they are terminated by a single newline character - which turns this into a line reading problem.
int read_line(char* buffer, int bufsize)
{
for (int index = 0; index < bufsize; index++) {
// Wait until characters are available
while (Serial.available() == 0) {
}
char ch = Serial.read(); // read next character
Serial.print(ch); // echo it back: useful with the serial monitor (optional)
if (ch == '\n') {
buffer[index] = 0; // end of line reached: null terminate string
return index; // success: return length of string (zero if string is empty)
}
buffer[index] = ch; // Append character to buffer
}
// Reached end of buffer, but have not seen the end-of-line yet.
// Discard the rest of the line (safer than returning a partial line).
char ch;
do {
// Wait until characters are available
while (Serial.available() == 0) {
}
ch = Serial.read(); // read next character (and discard it)
Serial.print(ch); // echo it back
} while (ch != '\n');
buffer[0] = 0; // set buffer to empty string even though it should not be used
return -1; // error: return negative one to indicate the input was too long
}
Here is an example of it being used to read commands from the serial monitor:
const int LED_PIN = 13;
const int LINE_BUFFER_SIZE = 80; // max line length is one less than this
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
Serial.print("> ");
// Read command
char line[LINE_BUFFER_SIZE];
if (read_line(line, sizeof(line)) < 0) {
Serial.println("Error: line too long");
return; // skip command processing and try again on next iteration of loop
}
// Process command
if (strcmp(line, "off") == 0) {
digitalWrite(LED_PIN, LOW);
} else if (strcmp(line, "on") == 0) {
digitalWrite(LED_PIN, HIGH);
} else if (strcmp(line, "") == 0) {
// Empty line: no command
} else {
Serial.print("Error: unknown command: \"");
Serial.print(line);
Serial.println("\" (available commands: \"off\", \"on\")");
}
}
String content = "";
char character;
if(Serial.available() >0){
//reset this variable!
content = "";
//make string from chars
while(Serial.available()>0) {
character = Serial.read();
content.concat(character);
}
//send back
Serial.print("#");
Serial.print(content);
Serial.print("#");
Serial.flush();
}
If you want to read messages from the serial port and you need to deal with every single message separately I suggest separating messages into parts using a separator like this:
String getMessage()
{
String msg=""; //the message starts empty
byte ch; // the character that you use to construct the Message
byte d='#';// the separating symbol
if(Serial.available())// checks if there is a new message;
{
while(Serial.available() && Serial.peek()!=d)// while the message did not finish
{
ch=Serial.read();// get the character
msg+=(char)ch;//add the character to the message
delay(1);//wait for the next character
}
ch=Serial.read();// pop the '#' from the buffer
if(ch==d) // id finished
return msg;
else
return "NA";
}
else
return "NA"; // return "NA" if no message;
}
This way you will get a single message every time you use the function.
Credit for this goes to magma. Great answer, but here it is using c++ style strings instead of c style strings. Some users may find that easier.
String string = "";
char ch; // Where to store the character read
void setup() {
Serial.begin(9600);
Serial.write("Power On");
}
boolean Comp(String par) {
while (Serial.available() > 0) // Don't read unless
// there you know there is data
{
ch = Serial.read(); // Read a character
string += ch; // Add it
}
if (par == string) {
string = "";
return(true);
}
else {
//dont reset string
return(false);
}
}
void loop()
{
if (Comp("m1 on")) {
Serial.write("Motor 1 -> Online\n");
}
if (Comp("m1 off")) {
Serial.write("Motor 1 -> Offline\n");
}
}
If you're using concatenate method then don't forget to trim the string if you're working with if else method.
Use string append operator on the serial.read(). It works better than string.concat()
char r;
string mystring = "";
while(serial.available()){
r = serial.read();
mystring = mystring + r;
}
After you are done saving the stream in a string(mystring, in this case), use SubString functions to extract what you are looking for.
I could get away with this:
void setup() {
Serial.begin(9600);
}
void loop() {
String message = "";
while (Serial.available())
message.concat((char) Serial.read());
if (message != "")
Serial.println(message);
}
Many great answers, here is my 2 cents with exact functionality as requested in the question.
Plus it should be a bit easier to read and debug.
Code is tested up to 128 chars of input.
Tested on Arduino uno r3 (Arduino IDE 1.6.8)
Functionality:
Turns Arduino onboard led (pin 13) on or off using serial command input.
Commands:
LED.ON
LED.OFF
Note: Remember to change baud rate based on your board speed.
// Turns Arduino onboard led (pin 13) on or off using serial command input.
// Pin 13, a LED connected on most Arduino boards.
int const LED = 13;
// Serial Input Variables
int intLoopCounter = 0;
String strSerialInput = "";
// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.
pinMode(LED, OUTPUT);
// initialize serial port
Serial.begin(250000); // CHANGE BAUD RATE based on the board speed.
// initialized
Serial.println("Initialized.");
}
// the loop routine runs over and over again forever:
void loop()
{
// Slow down a bit.
// Note: This may have to be increased for longer strings or increase the iteration in GetPossibleSerialData() function.
delay(1);
CheckAndExecuteSerialCommand();
}
void CheckAndExecuteSerialCommand()
{
//Get Data from Serial
String serialData = GetPossibleSerialData();
bool commandAccepted = false;
if (serialData.startsWith("LED.ON"))
{
commandAccepted = true;
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
}
else if (serialData.startsWith("LED.OFF"))
{
commandAccepted = true;
digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW
}
else if (serialData != "")
{
Serial.println();
Serial.println("*** Command Failed ***");
Serial.println("\t" + serialData);
Serial.println();
Serial.println();
Serial.println("*** Invalid Command ***");
Serial.println();
Serial.println("Try:");
Serial.println("\tLED.ON");
Serial.println("\tLED.OFF");
Serial.println();
}
if (commandAccepted)
{
Serial.println();
Serial.println("*** Command Executed ***");
Serial.println("\t" + serialData);
Serial.println();
}
}
String GetPossibleSerialData()
{
String retVal;
int iteration = 10; // 10 times the time it takes to do the main loop
if (strSerialInput.length() > 0)
{
// Print the retreived string after looping 10(iteration) ex times
if (intLoopCounter > strSerialInput.length() + iteration)
{
retVal = strSerialInput;
strSerialInput = "";
intLoopCounter = 0;
}
intLoopCounter++;
}
return retVal;
}
void serialEvent()
{
while (Serial.available())
{
strSerialInput.concat((char) Serial.read());
}
}
This always works for me :)
String _SerialRead = "";
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) //Only run when there is data available
{
_SerialRead += char(Serial.read()); //Here every received char will be
//added to _SerialRead
if (_SerialRead.indexOf("S") > 0) //Checks for the letter S
{
_SerialRead = ""; //Do something then clear the string
}
}
}

Resources