Strings in Arduino  What are they? + How to Use ▷ 2020

The Strings on Arduino are very useful tools that you must use to program your plate. Because of this, it is important to know what these functions are for and what are the Strings classes that you can find.

For this you need to read this article to the end because We will explain to you which Strings exist and how is the syntax that you should use to understand their work.

But this is not all, you can also find a guide to correctly use a String (Object) and a list of the best projects you can do yourself to practice.

What is a Strings in Arduino programming and what are they for when programming this type of hardware?

In arduino programming, Strings are tools used to save character strings. So it is not considered a String as a data in itself, but as a dependent class of these. The ending they have is by means of a null character. In addition, they are characterized by reserving a certain memory capacity of the arduino board to create a buffer and be able to use intensively the functions they offer to users.

Types of Strings in Arduino programming What are all that exist?

Types of Strings in Arduino programming What are all that exist?

Can be found different types of String that are used in programming Arduino.

We will show you each of them below:

Char Array

Char Array are character arrays used in large text strings. That is, every time you work on a string with a C ++ language that ends in the value 0 ( 0), consecutive memory compositions are created, therefore they occupy less memory and if not, would identify a String as char. Keep in mind that you always have to end with a null character and you can refer to the individual characters in the string.

Object

In case of not working with large amounts of texts you can use a String Object. These kinds of data improve handling of strings by means of methods that are used by users to compare two strings, find certain characters, concatenate and add elements to the string, among other functions.

Strings operators

Operators are symbols that are used to set a certain instruction to the String. In this way, actions can be established that serve to add, extract and see if a certain character in the string is true or not.

Syntax of a String (char array) How to understand its declarations and conditions of use?

When using a long text string you will have to use a Char Array.

To do this, we show you how you should handle it:

Declarations

The statements that are valid in a string for a String are:

  • char Str1[14]; This syntax is used to start an array in a general way.
  • char Str2[4] = {‘a’, ‘u’, ‘i’}; In this case additional characters are set, I want and compiler will add the null character.
  • char Str3[4] = {‘a’, ‘u’, ‘i’, ‘ 0’}; If you prefer and want to incorporate the null character manually, you will have to use this structure.
  • char Str4[] = “ipap”; You can initialize a string with a constant using single quotes. The IDE will set the size of the array.
  • char Str5[8] = “ipaparduino”; In case of setting the size manually and indicating a constant, use this syntax.
  • char Str6[15] = “ipaparduino”; This structure allows you to add a larger string, since a blank space is left.

Null termination

Null endings are used to define where a string ends, for this it is necessary to include a null character, of ASCII code , at the end of the function. Can be included manually through writing ” 0″ or automatically, so that it has interpreted by the Arduino IDE.

String arrays

Matrices are used to set up strings that have large amounts of texts. In this way it is possible to work more easily because the complexity of the handling is reduced.

Learn step by step how to use a Strings (Object) to program in Arduino

Learn step by step how to use a Strings (Object) to program in Arduino

To use a String in IDE you must follow this step by step:

Syntax

The first thing you will have to to know is how to handle the structure that has a String.

To do this, you will have to take into account the syntax used in a String (Object):

  • String(val)
  • String(val, base)
  • String(val, decimalPlaces)

Parameters

Next, you are going to have to implement the parameters, which are used in the previous syntax:

  • val: refers to the variable that needs to be formatted to get a string. The supported data in these parameters are byte, char, double, float, int, long, string, unsigned int, and unsigned long.
  • base: this parameter is optional and shows the base in which the variable should be formatted. It defaults to base 10, but can also be used on hexadecimal and binary bases. For example, String (14, HEX) and String (13, BIN).
  • decimalPlaces: when a floating or double data is used as values, the decimal place must be established.

Features

Finally, you will have to embed functions to the String.

The functions used in the Arduino IDE are:

  • charAt (): This function is used to access a specific element of the chain.
  • compareTo (): With this tool you can compare two strings and in this way establish whether they are the same or not.
  • concat (): when you need to add an element or parameter to the string you will have to use this function.
  • c_str (): this variable is used when you need to convert a string to a type C string.
  • endsWith (): It is used to check if a certain string ends with a specific character.
  • equals (): You can use this function to compare two strings and they found equality.
  • equalsIgnoreCase (): Like the previous function, this variable is used to compare two strings, but not case sensitive.
  • getBytes (): allows you to copy characters from a string.
  • index of (): this function is used on a String when you need to search for a string or a value within a string.
  • lastIndexOf (): used to find a character or a string.
  • lenght (): when I need to know the length of the string, you are going to have to use this function.
  • remove (): remove or modify characters.
  • replace (): you can substitute one character for another within a string.
  • reserve (): This function can be used to establish a buffer to the memory of the board and in this way to be able to work with processes without affecting the performance of the hardware.
  • setCharAt (): serves to incorporate a character.
  • starts with (): This anointing is characterized by checking if a chain begins with a certain element.
  • substring (): its name says it all, this function is used to obtain a substring within a string.
  • toCharArray (): allows you to copy characters within the selected buffer to have a space in memory.
  • toDouble (): if the string is valid, it can be used to duplicate it.
  • toInt (): you can convert a string to an integer, as long as it is valid.
  • toFloat (): manages to convert a String to a float character.
  • toLowerCase (): When the String is written in uppercase and it is necessary to change to lowercase, this function must be used.
  • toUpperCase (): is the inverse situation to the previous function.
  • trim (): you can use this tool to get a white space at the beginning or end of the String version.

List of the best projects programmed with Strings that you can do yourself to practice

We will show you below the best projects that you can program yourself using Strings.

Let’s get started:

Quick response device

Quick response device

With a Arduino UNO board, a push button, a breadboard, a led screen, a resistance of 10k establishes necessary for the installation you can create a screen in which you enter a question and receive a random answer. To incorporate the questions and answers the String should be used.

The codes you should use:

#include <SPI.h>

#include <Wire.h>

#include <Adafruit_GFX.h>

#include <Adafruit_SSD1306.h>

Now, you will have to include the variables and configure them on the screen display:

#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 32

#define STRING_ARRAYSIZE 10

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) - Arduino UNO: A4(SDA - Data ), A5(SCL - Clock)

#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

Set the button variables:

const int buttonPin = 2;

int buttonState = 0;

int lastButtonState = 0;

int randomNumber = 0;

String mainText = "Preguntar";

void setup() {

// Serial setup

begin(9600);

// OLED setup

// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally

if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32

println(F("SSD1306 allocation failed"));

for(;;); // Don't proceed, loop forever

}

displayTextOnOLED(mainText);

// PIN dedicated to button setup

pinMode(buttonPin, INPUT);

// if analog input pin 0 is unconnected, random analog

// noise will cause the call to randomSeed() to generate

// different seed numbers each time the sketch runs.

// randomSeed() will then shuffle the random function.

randomSeed(analogRead(0));

}

// purpose is to listen to button state

// and when pressed the OLED to display a different text

// when released to show the setup() text

void loop() {

// read the state of the pushbutton value:

buttonState = digitalRead(buttonPin);

if ( buttonState != lastButtonState ){

if (buttonState == HIGH) {

displayTextOnOLED(randomText());

} else {

displayTextOnOLED(mainText);

}

}

lastButtonState = buttonState;

}

void displayTextOnOLED(String str) {

clearDisplay();

setTextSize(2); // Draw 2X-scale text

setTextColor(SSD1306_WHITE);

setCursor(0,0);

println(str);

display(); // Show initial text

}

Use the string:

String randomText(void) {

String texts[STRING_ARRAYSIZE] = {"Da", "Nu", "Nu stiu!", "Nu vreau!", "Du-te naibii!","Varule","Te pup!","Sigur!", "Sigur ca nu!","Nah!"};

if ( buttonState != lastButtonState ) {

randomNumber = random(1, 10);

return texts[randomNumber];

} else {

return texts[randomNumber];

}

}

Radar station

Radar station

You are going to need an Arduino board in this project, an ultrasonic sensor of the model HC-SR04, a servomotor, cables and a 10k resistor. You will have to connect the sensor to pins 10 and 11 of the board and then the servo to pin number 12.

Next, you will have to enter these codes using Strings:

#include <Servo.h>.

const int trigPin = 10;

const int echoPin = 11;

larga duración;

int distancia;

To control the servomotor you will have to create a servo object:

Servo myServo;

void setup () {

pinMode (trigPin, OUTPUT);

PinMode de salida (echoPin, INPUT);

begin (9600);

attach (12);

}

void loop () {

Set the turning radius of the servomotor between 15 to 165 degrees:

para (int i = 15; i <= 165; i ++) {

write (i);

retraso (30);

distancia = calcularDistancia ();

print (i);

print (",");

print (distancia);

print (".");

}

para (int i = 165; i> 15; i -) {

write ( yo);

retraso (30);

distancia = calcularDistancia ();

print (i);

print (",");

print (distancia);

print (".");

}

}

int calculateDistance () {

digitalWrite (trigPin, BAJO);

delayMicroseconds (2);

digitalWrite (trigPin, HIGH);

delayMicroseconds (10);

digitalWrite (trigPin, BAJO);

duración = pulseIn (echoPin, HIGH);

distancia = duración * 0.034 / 2;

distancia de regreso;

}

Usa SerialEvent () para recibir valores de distancia y ángulo:

vacío dibujarRadar () {

pushMatrix ();

traducir (960,1000);

noFill ();

strokeWeight (2);

accidente cerebrovascular (98,245,31);

arco arc (0,0,1800,1800, PI, TWO_PI);

arco (0,0,1400,1400, PI, TWO_PI);

arco (0,0,1000,1000, PI, TWO_PI);

arco (0,0,600,600, PI, TWO_PI);

línea de las líneas angulares (-960,0,960,0);

línea (0,0, -960 cos (radianes (30)), - 960 sin (radianes (30)));

línea (0,0, -960 cos (radianes (60)), - 960 sin (radianes (60)));

línea (0,0, -960 cos (radianes (90)), - 960 sin (radianes (90)));

línea (0,0, -960 cos (radianes (120)), - 960sin (radianes (120)));

line (0,0, -960 cos (radianes (150)), - 960 sin (radianes (150)));

línea (-960 * cos (radianes (30)), 0,960,0);

popMatrix ();

}

Draw the lines that will be seen on the radar:

vacío drawLine () {

pushMatrix ();

strokeWeight (9);

accidente cerebrovascular (30,250,60);

traducir (960,1000);

línea de ubicación (0,0,950 cos (radianes (iAngle)), - 950 sin (radianes (iAngle)));

popMatrix ();

}

Radar-Print-Screen-04

Now you are going to have to draw the objects that the radar detects:

vacío drawObject () {

pushMatrix ();

traducir (960,1000);

strokeWeight (9);

accidente cerebrovascular (255,10,10);

pixsDistance = iDistance 22.5;

si (iDistance <40) {

// dibuja el objeto de acuerdo con el ángulo y la

línea de distancia (pixsDistance cos (radianes (iAngle)), -pixsDistance sin (radianes (iAngle)), 950 cos (radianes (iAngle)), - 950 * sin (radianes (iAngle)));

}

popMatrix ();

}

Add words to the screen:

vacío dibujar () {

llenar (98,245,31);

textFont (orcFont);

noStroke ();

llenar (0,4);

rect (0, 0, ancho, 1010);

llenar (98,245,31); // color verde

drawRadar ();

Dibujar linea();

drawObject ();

drawText ();

}

Make the radar programming:

procesamiento de importación.serie. *;

import java.awt.event.KeyEvent;

import java.io.IOException;

Serial myPort;

String angle = "";

Distancia de la cuerda = "";

String data = "";

String noObject;

float pixsDistance;

int iAngle, iDistance;

int index1 = 0;

int index2 = 0;

PFont orcFont;

configuración vacía () {

tamaño (1920, 1080);

suave();

myPort = new Serial (esto, "COM4", 9600);

bufferUntil ('.');

orcFont = loadFont ("OCRAExtended-30.vlw");

}

vacío dibujar () {

llenar (98,245,31);

textFont (orcFont);

noStroke ();

llenar (0,4);

rect (0, 0, ancho, 1010);

llenar (98,245,31);

drawRadar ();

Dibujar linea();

drawObject ();

drawText ();

}

void serialEvent (Serial myPort) {

datos = myPort.readStringUntil ('.');

data = data.substring (0, data.length () - 1);

index1 = data.indexOf (",");

angle = data.substring (0, index1);

distance = data.substring (index1 + 1, data.length ());

At this time you will have to convert the variables of the String into Integer:

iAngle = int (angle);

iDistance = int (distancia);

}

vacío dibujarRadar () {

pushMatrix ();

traducir (960,1000);

noFill ();

strokeWeight (2);

accidente cerebrovascular (98,245,31);

// dibuja las líneas del

arco arc (0,0,1800,1800, PI, TWO_PI);

arco (0,0,1400,1400, PI, TWO_PI);

arco (0,0,1000,1000, PI, TWO_PI);

arco (0,0,600,600, PI, TWO_PI);

// dibuja la

línea de las líneas angulares (-960,0,960,0);

línea (0,0, -960 cos (radianes (30)), - 960 sin (radianes (30)));

línea (0,0, -960 cos (radianes (60)), - 960 sin (radianes (60)));

línea (0,0, -960 cos (radianes (90)), - 960 sin (radianes (90)));

line (0,0, -960 cos (radianes (120)), - 960 sin (radianes (120)));

line (0,0, -960 cos (radianes (150)), - 960 sin (radianes (150)));

línea (-960 cos (radianes (30)), 0,960,0);

popMatrix ();

}

vacío drawObject () {

pushMatrix ();

traducir (960,1000);

strokeWeight (9);

accidente cerebrovascular (255,10,10);

pixsDistance = iDistance 22.5;

si (iDistance <40) {

// dibuja el objeto de acuerdo con el ángulo y la

línea de distancia (pixsDistance cos (radianes (iAngle)), - pixsDistance sin (radianes (iAngle)), 950 cos (radianes (iAngle)), - 950 sin (radianes (iAngle) ));

}

popMatrix ();

}

vacío drawLine () {

pushMatrix ();

strokeWeight (9);

accidente cerebrovascular (30,250,60);

traducir (960,1000);

línea de ubicación (0,0,950 cos (radianes (iAngle)), - 950 sin (radianes (iAngle)));

popMatrix ();

}

Incorporate texts on the screen:

void drawText () {

pushMatrix ();

if (iDistance> 40) {

noObject = "Fuera de rango";

}

else {

noObject = "Dentro del rango";

}

llenar (0,0,0);

noStroke ();

rect (0, 1010, ancho, 1080);

llenar (98,245,31);

textSize (25);

texto (“10 cm”, 1180,990);

texto (“20cm”, 1380,990);

texto (“30cm”, 1580,990);

texto (“40cm”, 1780,990);

textSize (40);

texto (“Objeto:" + noObjeto, 240, 1050);

texto (“Ángulo:" + iAngle + ”°”, 1050, 1050);

texto ("Distancia:", 1380, 1050);

if (iDistance <40) {

text (”" + iDistance + ”cm", 1400, 1050);

}

textSize (25);

llenar (98,245,60);

traducir (961 + 960cos (radianes (30)), 982-960 sin (radianes (30)));

rotar (-radianes (-60));

texto (“30 °”, 0,0);

resetMatrix ();

traducir (954 + 960 cos (radianes (60)), 984-960 sin (radianes (60)));

rotar (-radianes (-30));

texto (“60 °”, 0,0);

resetMatrix ();

traducir (945 + 960 cos (radianes (90)), 990-960 sin (radianes (90)));

rotar (radianes (0));

texto ("90 °", 0,0);

resetMatrix ();

traducir (935 + 960 cos (radianes (120)), 1003-960 sin (radianes (120)));

rotar (radianes (-30));

texto (“120 °”, 0,0);

resetMatrix ();

traducir (940 + 960 cos (radianes (150)), 1018-960 sin (radianes (150)));

rotar (radianes (-60));

texto ("150 °", 0,0);

popMatrix ();

}

Humidity detector

put one Arduino UNO R3 board, a breadboard, humidity sensor, cables and resistance you will be able to build a humidity sensor.

The connection must be made through the image that we show you below:

Humidity detector

After this, you will have to enter these codes with Strings:

#include <SparkFun_RHT03.h>

const int RHT03_DATA_PIN = 0;

RHT03 rht;

configuración vacía ()

{

begin (9600);

begin (RHT03_DATA_PIN);

}

bucle vacío ()

{

int updateRet = rht.update ();

// Si tiene éxito, la función update () devolverá 1, en caso contrario será un valor <0

si (updateRet == 1)

{

float latestHumidity = rht.humidity ();

float latestTempC = rht.tempC ();

float latestTempF = rht.tempF ();

What you will have to do at this time is to print the results obtained:

println ("Humedad:" + String (latestHumidity, 1) + "%");

println ("Temp (F):" + String (latestTempF, 1) + "grado F");

println ("Temp (C):" + String (latestTempC, 1) + "grado C");

}

{

retraso (RHT_READ_INTERVAL_MS);

}

retraso (1000);

}

If you have any questions, leave them in the comments, we will answer you as soon as possible, and it will also be of great help to more members of the community. Thank you! 😉

You may be interested:

Rate this post

Leave a Comment