text:
'Serial1' was not declared in this scope for automatic plant watering
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
int in1 = 2;
int in2 = 3;
LiquidCrystal lcd(14,15,16,17,18,19);
int led = 13;
int flag = 0;
int motorpin = 11;
int sensorpin = 7;

void setup()
{
  lcd.begin(16,2);
  Serial1.begin(9600);
  pinMode(led, OUTPUT);
  pinMode(motor, OUTPUT);
  pinMode(sensor, INPUT_PULLUP);
  lcd.print("Plant Watering");
  lcd.setCursor(4,1);
  delay(2000);
  lcd.clear()
  lcd.print("RCC INSTITUTE");
  lcd.setCursor(0,1);
  lcd.print("Starting....");
  delay(2000);
  gsmInit();
  lcd.clear();
  lcd.print("System Ready");
}

void loop()
{
  lcd.setCursor(0,0);
  lcd.print("Automatic Mode");
  if (digitalRead(sensor) == 1 && flag == 0)
  {
    delay(1000);
    if (digitalRead(sensor) == 1)
    {
      digitalWrite(led, HIGH);
      sendSMS("Low Soil Moisture detected. Motor turned ON");
      lcd.begin(16, 2);
      lcd.setCursor(0, 1);
      lcd.print("Motor ON ");
      digitalWrite(motor, HIGH);
      delay(2000);
      flag=1;
    }
  } else if(digitalRead(sensor) == 0 && flag == 1)
  {
    delay(1000);
    if (digitalRead(sensor) == 0)
    {
      digitalWrite(led, LOW);
      sendSMS("Soil Moisture is Normal. Motor turned OFF");
      digitalWrite(motor, LOW);
      lcd.begin(16, 2);
      lcd.print("Motor OFF");
      lcd.setCursor(0, 1);
      lcd.print("Motor OFF");
      delay(2000);
      flag = 0;
    }
  }
}

void sendSMS(String msg)
{
  lcd.clear();
  lcd.print("Sending SMS");
  Serial1.println("AT+CMGF=1");
  delay(500);
  Serial1.print("AT+CMGS=");
  Serial1.print('"');
  Serial1.print("+918xxxxxxxxx"); // number
  Serial1.print('"');
  Serial1.println();
  delay(500);
  Serial1.println(msg);
  delay(500);
  Serial1.write(26);
  delay(1000);
  lcd.clear();
  lcd.print("SMS Sent");
  delay(1000);
  lcd.begin(16, 2);
}

void gsmInit()
{
  lcd.clear();
  lcd.print("Finding Module..");
  boolean at_flag = 1;
  while (at_flag)
  {
    Serial1.println("AT");
    while (Serial1.available() > 0)
    {
      if (Serial1.find("OK"))
      at_flag = 0;
    }
    delay(1000);
  }
  Serial1.println("ATE0"); //<=== it says 'Serial1' was not declared in this scope
  lcd.clear();
  lcd.print("Finding Network..");
  boolean net_flag = 1;
  while(net_flag)
  {
    Serial1.println("AT+CPIN?");
    while(Serial1.available() > 0)
    {
      if (Serial1.find("READY"))
        net_flag = 0;
      break;
    }
    delay(1000);
  }
  Serial1.println("AT+CNMI=2,2,0,0,0");
  delay(1000);
  Serial1.println("AT+CMGF=1");
  delay(1000);
  Serial1.println("AT+CSMP=17,167,0,0");
  lcd.clear();
  Serial1.flush();
}

UNO has no Serial1, so what did you expect?

The Uno has no Serial1. Just use Serial. 2. When asking about a compilation error on this site, you always have to include the complete error message, including information, where the error happened.

As an aside: in gsmInit(), the break isn't inside the if (Serial1.find("READY")) for lack of {}; possible bug.

FYI I flagged an admin to purge the phone number from your code.

The UNO only has one serial port, named Serial.  You can create another one using SoftwareSerial (which you have included but not used) and you can, if you choose, name this Serial1.

#include <SoftwareSerial.h>

SoftwareSerial Serial1(4, 5); // RX, TX


text:
Not output on serial monitor, sending string on serial.print
I get two 10-bit values from analog pins. These two values in a string, ";" combine with.
for ex:  515; 510
I am sending it to another arduino via Serial.print. I cannot display this string expression on other arduino's serial monitor. But when I press the reset button of Coordinator arduino, there are a few values. Can you help me?
My Coordinator Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger3;
int deger4;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

void setup() {
  //Serial.begin(9600);
  xBeeSerial.begin(38400);
  }void loop() {

    deger3 = analogRead(A0);
    deger4 = analogRead(A2);

    String deger5 = " " + (String)deger3 + ";" + (String)deger4 ;

    Serial.println("string ifade: " + deger5);

    xBeeSerial.print(deger5);
  }

My Receiver Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
String d1;

void setup() {
  xBeeSerial.begin(38400);
  Serial.begin(38400);
}
void loop() {
  if(xBeeSerial.available()){
    d1=xBeeSerial.readString();
    Serial.print(d1);
  }
}

I obtained the values I wanted and performed the separation. I am sending a list of joystick positions via the serial connection to the arduino in the following format
515;520
Which would be parsed as:
x=515
y=520
MyCoordinator:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger3;
int deger4;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

void setup() {
  Serial.begin(38400);

}void loop() {
  xBeeSerial.begin(38400);
  deger3 = analogRead(A0);
  deger4 = analogRead(A2);

  String deger5 =  (String)deger3 + ";" + (String)deger4 ;
  Serial.println("string ifade: " + deger5);

  xBeeSerial.println(deger5);

  delay(200);
}

MyReceiver:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
String d1,d2,d3;

void setup() {
  xBeeSerial.begin(38400);
  Serial.begin(38400);
}
void loop() {
  if(xBeeSerial.available()>0){
    d1=xBeeSerial.readStringUntil('\n');
    //Serial.print(d1);
    d2 = d1.substring(0,d1.indexOf(59));
    d3 = d1.substring(d1.indexOf(59)+1);
    Serial.println("x ekseni: " + d2);
    Serial.println("y ekseni: " + d3);
  }
}

There is a fundamental problem with your communication strategy, and that is you have nothing to tell the receiver "This is the end of a message".
You are sending a constant stream of
 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510.....

and the receiver really doesn't know what to make of that.
This is because you are using the function .readString() at the receiver. This will blindly receive characters and store them in the target string up until the point those characters stop arriving. And that happens only after a break of at least 1 second in transmission. That never comes. So never ends. That is, until you reset the sender and it sees that break in transmission.
It's a very crude function and I'd never recommend anyone ever using it for anything.
Instead you need to break your transmission up into separate lines with .println() or appending \n to the string.  Then you can use .readStringUntil('\n') to get each line in turn and display it.
Also, on a side note, you really shouldn't be appending all your data to a string then sending the string, that's completely redundant. Just send each individual part of the data as separate prints. All you're achieving with all that String manipulation is to fragment your heap and cause your code to be unstable.

Can I handle it using xBeeSerial.end, like xBeeSerial.begin?

No. You have to construct a proper syntax and flow of information. Just like English. At the moment you're sending the contents of a book all on one line with no punctuation and no paragraphs. Do it properly. Don't try and cut corners. You will just end up even more frustrated.

I am newbie in working with Arduino. It's really hard for me. Also, i am not good at English, sorry about that. Can you make improvements directly to the code?

I have told you explicitly what to change. I'm not going to program it for you too.

if(xBeeSerial.available()){
d1=xBeeSerial.readStringUntil('\n');
Serial.println(d1);
}

509;509 509;508 510;508 510;508 510;508 510;508 510;508 510;508 510;508 511;508 510;508

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Am I at the limit of UART transmission time?
I'm currently using an STM32F103C8 (With an arduino core) to read 4 sensors at 1kHz, then send that data via UART (at 115200 baud) to another device. Each sensor returns a float, I also include an unsigned long representing milliseconds since boot time. This adds up to be a 20 byte package, that I attempt to send at 1kHz. Sensor sampling is carried out via a timer interrupt, as it is crucial the time between samples is constant.
The data transmission itself (If I send it slowly) takes approx. 70 microseconds. When sped up to 1kHz, it takes approx. 2500. I assume this is because I am filling a serial buffer of some sort.
Is this about the limit of the communication method? If it takes longer than 1000 microseconds to send the data, then presumably the interrupt will trigger before the data is sent and it will have to start again?

You could try a higher baudrate. Though that depends on how high a baudrate the other device can handle

At 115200 baud you can send 11520 characters per second. At 20 bytes per packet you can send 576 packets per second. That's 1,736µs per packet.
That's assuming zero wait between bytes. That's not going to happen.
Your measurement of 70µs will just be the time taken to place data into the transmit buffer, and has nothing to do with how long the transmission itself takes.
Roll all that together and the value of 2,500µs per packet is not unreasonable.
To transmit faster you will simply have to run at a faster baud rate.  If you're getting 2500µs per packet currently and a packet takes 1736µs (call it 1,750 for simplicity) then there's about a 750µs overhead per packet to do the actual work of sending the data from the buffer. I'll assume this is a fixed value, though with no knowledge of how the STM32F1 UART works it may not be.
If you want <1000µs then that leaves you about 250µs of time to fit the packet into. That means an equivalent of 4,000 packets per second, or 80,000 bytes per second, or a baud rate of 800,000baud.
1 MBaud is more than possible, and is a good standard baud rate number that most things can cope with. So raising your baud rate to 1,000,000 should allow the communication to happen fast enough.

Interesting! I wasn't really aware such high baud rates were feasible! I have had some success with a rate of 921600 rather than 1000,000, so presumably something to do with a multiple of crystal frequencies

The closer you are to an integer factor of your clock speed the more accurate the baud will be. But if both ends of the connection use the same clock the error difference between the two ends will be 0 so is meaningless.

Of course at higher baud rates you're more at the mercy of the clock accuracy, as any slight deviation in clock will cause a bigger percentage of difference in the baud rate.

I tested a lot of baud rates on Arduino Unos, including cheap Chinese models, and decided to use a default 115200 for my DaqPort system (https://www.daqarta.com/dw_rraa.htm).  I had found problems, like the system hanging after a second or so at 150000 baud, and didn't want to have my users run into issues that would be hard to troubleshoot.
So I'm wondering if you can reduce the bytes you need to send.  Do you really need to send floats?  I'm thinking 4 bytes for the data and 4 for the time would give ample resolution for almost anything, and I can't (off the top of my head anyway) think of a sensor type with more than 32-bit resolution. Also, 32 bits of msec is nearly 50 days; if you need more than that it should be pretty easy to unwrap the times after the fact.
Just a thought...

I had honestly completely forgotten about shorts as a datatype, my sensors are only 12 bit anyway so that's going to help a huge amount. I should be able to just store a raw sensor reading as a short and post-process everything to floating point later. I'm using microseconds rather than millis for time, so the unsigned long is only 70 minutes - my max sampling duration is 20 minutes, so too long for an unsigned int.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Standalone ATmega328P stops responding when RX is connected
I have followed this demo and have set up a standalone ATmega328P being programmed from a Raspberry Pi via the SPI lines. I have also added a 16 MHz crystal with 22 pF capacitors, as well as I have enabled and set up I²C between the ATmega and Raspberry Pi.
I have compiled and uploaded a bunch of programs and I can confirm everything works as expected.
As you can imagine, it is quite hard debugging things without a serial connection, so I connected pin 2 of the ATmega to GPIO14 of the Raspberry Pi and pin 3 to GPIO15. At this point, when I try uploading a program, I get this:
$ avrdude -P /dev/spidev0.0 -c linuxspi -p m328p -U flash:w:build-uno/program.hex

avrdude: error: AVR device not responding
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

If I break the pin2 to GPIO14 connection, then my program gets uploaded. And if I restore the connection between the pins and open Minicom on the Raspberry Pi I see the output of my simple program:
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(1000);

  Serial.println("Echo Test");
}

$ minicom -b 9600 -o -D /dev/ttyS0

Welcome to minicom 2.7.1

OPTIONS: I18n
Compiled on Aug 13 2017, 15:25:34.
Port /dev/ttyS0, 16:50:17

Press CTRL-A Z for help on special keys

Echo Test
Echo Test
Echo Test
Echo Test

But whenever I press a button on the keyboard (inside Minicom), I notice that the ATmega gets reset. If I hold the button down the transmission of "Echo Test" seizes as it is getting reset rapidly.
How can I get serial to function properly?
Addendum:
I'm using a Raspberry Pi 4, and in raspi-config I have disabled serial login and left the serial hardware enabled.

There are two things wrong with the circuit in that demo.

There is no decoupling capacitor on the power pins. This is required to keep the power stable during opertaion.
More critically: this is being powered from 3.3V, but is being run at 16MHz. That is outside specifications. You should use an 8MHz crystal to operate at 3.3V.

Thanks for pointing out, I see now indeed it's unrelated. Upvoted yours, deleted mine.

Here is another video from the same creator which shows it working at 3.3V. He is using /dev/ttyAMA0 which doesn't work in my case so something is different but I can't tell what. I'll try adding a 0.1uF capacitor on the input, see if that makes any difference.

It will work at 3.3V, but it won't be stable. The serial port name change is because of a different version of Pi being used.

Well in my case it is not only unstable it plain doesn't work, guess I'll just call it unlucky then and stick to debugging through i2c until I can establish a better setup. Thank you!


text:
How to make my LCD screen brighter
I'm trying to make my LCD screen brighter, can someone can help?
These are the code and the connections:
//LCD
#include <LiquidCrystal.h>
int Contrast=75;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

//LED
int LdrPin = A0;   // the cell and 10K pulldown are connected to a0
int LdrValue = 0;  // the analog reading from the sensor divider
int LedPin = 10;   // connect Red LED to pin 11 (PWM pin)
int LedBrightness;

//כתום
int LdrPin2 = A0;  // the cell and 10K pulldown are connected to a0
int LdrValue2 = 0; // the analog reading from the sensor divider
int LedPin2 = 9;   // connect Red LED to pin 11 (PWM pin)
int LedBrightness2;

//צהוב
int LdrPin3 = A0;  // the cell and 10K pulldown are connected to a0
int LdrValue3 = 0; // the analog reading from the sensor divider
int LedPin3 = 8;   // connect Red LED to pin 11 (PWM pin)
int LedBrightness3;

//serial monitor
char rx_byte = 0;
//random
long randNumber;

void setup()
{
  //אתחול LCD
  analogWrite(6, Contrast);
  lcd.begin(16, 2);

  //אתחול LED
  pinMode(LdrPin, INPUT);
  pinMode(LedPin, OUTPUT);
  Serial.begin(9600);

  pinMode(LdrPin2, INPUT);
  pinMode(LedPin2, OUTPUT);
  Serial.begin(9600);

  pinMode(LdrPin3, INPUT);
  pinMode(LedPin3, OUTPUT);
  Serial.begin(9600);

  //serial monitor
  Serial.begin(9600);

  //random אתחול
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop()
{
  // lcd.setCursor(2, 0);
  // lcd.print("Good Morning");

  LdrValue = analogRead(LdrPin);
  //Serial.print("LDR reading = ");
  //Serial.println(LdrValue);    // print the raw analog reading
  LedBrightness = map(LdrValue, 679, 6, 255, 0);

  if (Serial.available() > 0) // is a character available?
  {
    rx_byte = Serial.read();       // get the character
  }
  //check if morning and show good morning on thr LCD
  if (LdrValue == 679 && rx_byte == '7')
  {
    lcd.setCursor(2, 0);
    lcd.print("Good Morning!");
    //random 50% order of lights
    randNumber = random(0, 2);
    Serial.print(randNumber);
    if (randNumber == 1)
    {
      //אדום
      for (int i=0; i<8; i++)
      {
        digitalWrite(LedPin, HIGH);
        delay(1000);
        digitalWrite(LedPin, LOW);
        delay(1000);
        //led start working on red
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("red");
      }
      //כתום
      for (int i=0; i<4; i++)
      {
        digitalWrite(LedPin2, HIGH);
        delay(1000);
        digitalWrite(LedPin2, LOW);
        delay(1000);
        //led start working on orange
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("orange");
      }

      //צהוב
      for (int i=0; i<5; i++)
      {
        digitalWrite(LedPin3, HIGH);
        delay(1000);
        digitalWrite(LedPin3, LOW);
        delay(1000);
        //led start working on yellow
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("yellow");
      }
    } else
    {
      //צהוב
      for (int i=0; i<5; i++)
      {
        digitalWrite(LedPin3, HIGH);
        delay(1000);
        digitalWrite(LedPin3, LOW);
        delay(1000);
        //led start working on yellow
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("yellow");
      }

      //כתום
      for (int i=0; i<4; i++)
      {
        digitalWrite(LedPin2, HIGH);
        delay(1000);
        digitalWrite(LedPin2, LOW);
        delay(1000);
        //led start working on orange
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("orange");
      }

      //אדום
      for (int i=0; i<8; i++)
      {
        digitalWrite(LedPin, HIGH);
        delay(1000);
        digitalWrite(LedPin, LOW);
        delay(1000);
        //led start working on red
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("red");
      }
    }
  } else
  {
    lcd.setCursor(2, 0);
    lcd.print("Good night!");
  }
}

Provide more power to the back light

Use a lower value resistor than the 1kOhm shown in the diagram. Around 100Ohm if your LCD uses a white led. Some modules already have a resistor on the board, to limit the current thought the backlight led, but you'd have to check if yours does.

For a complete answer, we would need the datasheet of the LCD screen, but in general, LCD screens have a pin for the backlight, or two, one for plus and one for ground.
In the datasheet you can find what voltage the backlight wants, and what the maximum voltage is, and then set it to what you want.
For extra points, you can feed the backlight with PWM and set the brightness from the Arduino; if you do, make sure you don't pull too much current from the Arduino pin; add a FET if necessary.

Use a 220 ohm resistor for the backlight. Treat it just as an LED. That's what it is, just a normal LED.


text:
Is there a way to send a String via a Webserver Textbox without the use of the SD card?
Since my last post, I've been trying to do some extra things with my Stranger Things Wall Project.
I connected a LCD Screen (16x2) that will take any text being processed to the wall and show what is being written (So we can read the full message even if we lost the first chars being flashed)
The original example I followed used a Bluetooth App to send the message, however I want to use a Web Server with Ethernet.
My current challenge is if it is possible to make a WebServer to feed text to arduino, without the use of a SD card. I did manage to find an example that sends a simple command, but in my case, I need to call a function and sends a string.
My knowledge is limited on the areas of HTML and JS, so any help is welcome. If it matters, the Ethernet Shield I am using currently is the W5100.
The schematic is the same as the last post, however, here is the updated code:
#include <Wire.h> //INCLUSÃO DE BIBLIOTECA
#include <LiquidCrystal_I2C.h> //INCLUSÃO DE BIBLIOTECA
#include <SPI.h> //INCLUSÃO DE BIBLIOTECA
#include <Ethernet.h> //INCLUSÃO DE BIBLIOTECA

//Pin connected to ST_CP of 74HC595
#define latchPin 5
//Pin connected to SH_CP of 74HC595
#define clockPin 7
////Pin connected to DS of 74HC595
#define dataPin 6
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   90
// size of buffer that stores a line of text for the LCD + null terminator
#define LCD_BUF_SZ   17
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer
LiquidCrystal_I2C lcd(0x27,16,2);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //ATRIBUIÇÃO DE ENDEREÇO MAC AO ETHERNET SHIELD W5100 - ETIQUETINHA
EthernetServer server(80);
String text;                                                    //Variável do tipo string que receberá o texto

void setup() {
  Serial.begin(9600);                                           //Velocidade de comunicação
  for (int i = 2; i < 7; i++) {
    if (i != 4) {
      pinMode(i, OUTPUT);                                   //Declarando o pino como saída
    }
  }
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  lcd.init();
  lcd.setBacklight(HIGH);
  lcd.setCursor(0,0);
  lcd.print("Iniciando");
  if (Ethernet.begin(mac) == 0) {
    lcd.clear();
    lcd.setCursor(1,0);
    lcd.print("FALHA AO PEGAR");
    lcd.setCursor(7,1);
    lcd.print("IP");
  // no point in carrying on, so do nothing forevermore:
    delay(5000);
    return;
  }
  // print your local IP address:
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("PRONTO");
  lcd.setCursor(0,1);
  lcd.print(Ethernet.localIP());
  server.begin();
  brilho(255);
  inicializationEffect();                                       //Chamada da Função responsável pelo efeito inicial
}
void loop() {
   EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          client.println("
Stranger Things

");
          client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }

  //receiveText();                                               //Chamada da função responsável por receber o texto digitado
}
//Função que recebe o texto diitado
void receiveText() {
  while (Serial.available() > 0) {                              //Verifica se existe alguma informação na Serial
    char c = Serial.read();                                     //atribui cada caractere a variável c que é do tipo char
    if (c != '\n') text.concat(c) ;                              //verifica se a variável do tipo char recebeu uma quebra de linha que indica o fim da palavra ou frase e concatena todos os caracteres na String text
    delay(10);                                                  //aguarda 10 milissegundos
  }
  if (text.length() > 0) {                                      //verifica se a string text tem tamanho maior que 0
    text.toUpperCase();                                       //transforma tudo que estiver na string text para maiúsculo
    if (text[0]=='#'){
      waveEffect();
    }else if(text[0]=='!'){
      blink();
    }else {
      executeEffect(text);                                        //chama a função executeEffect passando a string text como parâmetro
    }
  }
  text = "";                                                    //limpa a string text
}
//Função responsável por ativar linha que recebe como parâmetro o número da linha
void lineActivation(int line, int keepalive) {
  if (keepalive == 0) {
    for (int i = 2; i <= 4; i++) {
      if (i == 4) { i = 8; } //porta 4 usada pelo SD do Ethernet
      digitalWrite(i, LOW);
    }
  }
  if (line >= 1 && line <=3){
    if (line == 3) { line = 7; } //porta 4 usada pelo SD do Ethernet
    digitalWrite(line+1, HIGH);                               //coloca a linha 1 em estado lógico alto
  }
}

void activateLetter(char letter, int on, int off) {
  int lt;
  brilho(255);
  lt = (((int)letter - 64) % 9);
  if (((int)letter - 64) > 8) {
    lt = lt + 1;
  }
  if (on) {
    callCol(1<<lt-1);
    delay(on);                                                //mantém o pino em nível lógico alto durante o tempo que foi determinado no parâmetro da função
  }
  if (off) {
    callCol(0);
    delay(off);                                               //mantém o pino em nível lógico baixo durante o tempo que foi determinado no parâmetro da função
  }

}

void callCol(int col){
  digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, highByte(col));
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(col));
  digitalWrite(latchPin, HIGH);

}
void executeEffect(String text) {
  for (int i = 0; i < text.length(); i++) {
    if (text[i] == ' ') {
      delay(1000);
    } else if ((int)text[i] < 65 or (int)text[i] > 90) {
    } else {
      lineActivation(int(((int)text[i] - 64) / 9) + 1, 0);
      activateLetter(text[i], 1000, 200);
    }
  }
}

void inicializationEffect() {
  for (int i = 1; i < 27; i++) {
    lineActivation(int(i / 9) + 1, 0);                          //ativa a linha
    activateLetter(char(64 + i), 100, 10);                   //ativa a letra
  }
}
void waveEffect() {
  Serial.println("Wave");
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);                          //ativa a linha
  }
  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 100, 0);
  }

  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 0, 100);
  }
    lineActivation(0, 0);                          //ativa a linha

}
void blink() {
  Serial.println("Blink");
  callCol(511);
  lineActivation(1,1);
  lineActivation(2,1);
  lineActivation(3,1);
  for (int i = 0; i < 256; i++){
    brilho(i);
    delay(1);
  }
  delay(100);
  for (int i = 255; i >= 0; i--){
    brilho(i);
    delay(1);
  }
}

void brilho(byte brt) { // 0 to 255
  analogWrite(9, 255-brt);
}

your code has no SD card functions ... it is unclear what you are asking

Yes. I do not have SD card functions and I am not looking to use them. I would like to know if it is possible to do the "On press send process code" without an SD card. Every example I've found so far requires the SD card and uses Ajax/js or something related.

You can build a simple webserver for the Arduino, and create an HTML page as the user interface to send commands to the Arduino from a webbrowser. If you want to go all the way, you can even have the Arduino host that webpage and communicate over a websocket, if you can get all of that to fit in the memory of an Arduino Uno. I have implemented such a thing, so it is doable, but it was on an Arduino Nano 33 IoT. BTW I don't get what the SD card has to do with it.

i am certain that you can find minimal ajax code that does not store javascript files locally .... your problem is that you are searching in the arduino realm ... the answers are in the html/javascript/ajax realm ... your question is not really about an arduino

I see, so this is the wrong place to ask such a question. Should I delete it or keep it up and wait for the vote to close?  The SD thing is just because I can only find examples that work on the SD directly

Well, you need to run a webserver on the Arduino, that bit belongs here, and questions about building a webinterface to control an Arduino don't bother me that much, but the opinions of the powers-that-be may differ.

Well, for now I will keep it up then, and if somehow I get a solution I'll self-answer it it remains open.

Yes, and it's not too hard, but do you do need to do string parsing in C to achieve it.
In your code you read the header of the HTTP request byte by byte and send it to serial, essentially discarding it.
Instead you need to read the header line by line (at least the first line) and parse the URL parameters.
The format of the first line should be something like:
GET / HTTP/1.1

or:
GET /?text=This+will+be+displayed HTTP/1.1

You need to parse that to get everything between = and the the space if they exist. You can then display it as you wish.
Next you also need to alter the code that is sending the web page content to also include a simple HTML form with the GET method and the destination of /, which contains a text field called text.

I followed your idea and, while googling on how to deal with the resulting strings, found your examples on how to use a Char array instead of a string. It worked pretty well! Thanks! I also followed your answer to convert the %20 to space and so on, but got stuck on the accented letter problem, because some chars are over the 127 (like Ã), but I guess I'll just remember not to use them.

@Feeds Accents are a nasty subject. There's no standard for how to fit them into 8 bit values and each language has its own arrangement. That's why UTF was created. And that gets really nasty to parse since there's multiple UTF standards...


text:
Arduino TFMini Lidar sensors and speaker
I have this code for the TFMini Lidar sensors and Speaker. I Need help figuring why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement? (see below plz).
And my code now it's only one sensor is working pins (4,5) I don't know why the three of them don't work together.   Thanks in advance.
I took this code from the internet My coding experience is basic .
rx[i] = TFMiniOne.read();
if (rx[0] != 0x59) {
  i = 0;
} else if (i == 1 && rx[1] != 0x59) {
  i = 0;
} else if (i == 8) {
  for (j = 0; j < 8; j++) {
    checksum += rx[j];
  }
  if (rx[8] == (checksum % 256)) {
    *distance = rx[2] + rx[3] * 256;
    *strength = rx[4] + rx[5] * 256;
  }
  i = 0;
} else {
  i++;
}

Here is the complete code:
#include "Talkie.h"
#include "Vocab_US_Large.h"
#include <SoftwareSerial.h>
#include "TFMini.h"
TFMini tfminiOne;
TFMini tfminiTwo;
TFMini tfminiThree;

Talkie voice;
const int Speaker = 3;

//Declaring variables and constants

SoftwareSerial TFMiniOne (4,5);    //(RX, TX)
SoftwareSerial TFMiniTwo (6,7);
SoftwareSerial TFMiniThree (8,9);

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];
  if (TFMiniOne.available()) {
    // Serial.println( "tfmini serial available" );
    rx[i] = TFMiniOne.read();
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) {
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if (rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else {
      i++;
    }
  }
}

void setup() {
  pinMode(Speaker, OUTPUT);

  //Initializing
  Serial.begin (115200);
  while(!Serial);                     //Wait for USB Serial Port to connect
  Serial.println("Initializing...");
  TFMiniOne.begin (TFMINI_BAUDRATE);

  //Initializing TFMini Sensors
  tfminiOne.begin(&TFMiniOne);
  tfminiTwo.begin(&TFMiniTwo);
}

void loop() {
  int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while (!distance) {
    getTFminiData(&distance, &strength);
    if (distance) {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
  }

  delay(100);

  if (distance > 30) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_F);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance > 20) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_L);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance < 15) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_R);
  } else {
    digitalWrite(Speaker,LOW);
  }
  delay(300);

Already asked on Stack Overflow: https://stackoverflow.com/questions/64886565/arduino-and-tfmini-lidar-sensors. Please do not cross post; remove either one.

I don't quite understand what you're asking. You seem to be asking "If I remove this code, why doesn't it work?" where the answer is simply "because you removed the code?"

I can't answer the first part of your question as I don't understand what you're asking.  However:

I don't know why the three of them don't work together.

That doesn't work for 2 reasons:

Your receiving routine specifically references only one TFMini serial port, and
It is impossible to receive from more than one SoftwareSerial port at a time.

If you want to use multiple units you really should choose a microcontroller that has enough hardware UARTs to do the job. The Uno is not a suitable board.
Try the Mega2560 or one of the myriad of 32-bit ARM or MIPS boards.

I don't know why the three of them don't work together.

I already answered that question in my answer to your previous question.

why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement?

That code part is reading the data from the first SoftwareSerial interface. If you don't read this data (by removing this code part) you are not reading any data from the TFMini, thus you don't have any measurement. If you want measurements from the lidar sensor, don't remove the code part, that actually reads the measurements.
Besides that I will explain the complete function here in comments to the code. Before that, you should understand what the static keyword means here. Normal variables, that get declared inside a function, (aka local variables) will get destroyed, when the code reaches the end of the function. Variables marked with the keyword static will continue to exist and hold their value also after the function ended. They act a lot like global variables, though their namespace is local to the function (thus you can declare other variables with that name in other parts of your code).
void getTFminiData(int* distance, int* strength) {
  static char i = 0; // this counter variable denotes the position of the next to be received byte in the buffer rx.
  char j = 0; // temporary counter variable
  int checksum = 0; // will be used to calculate the checksum, so that it can be compared to the one send with the data
  static int rx[9]; // this is the receive buffer, where the received data will be put

  if (TFMiniOne.available()) { // When data is available on the serial interface, read one byte
    // Serial.println( "tfmini serial available" );
    // read one byte into the current position in the buffer
    rx[i] = TFMiniOne.read();

    // A valid message starts with two bytes of the value 0x59, so we restart, if the current message doesn't have that. (checking the first two bytes with these two if statements)
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) { // if we received 9 bytes (positions 0 to 8 in the buffer), the message is complete --> process it

      // Calculating the checksum by adding all bytes together
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }

      // Comparing the calculated checksum with the last byte, that was received, (which is the checksum)
      // as the checksum is only one byte, we calculate the modulo with 256, thus only leaving the number range 0-255.
      if (rx[8] == (checksum % 256)) {
        // The checksums are equal, so the data is valid and we can proceed
        // The values for distance and strength have two bytes. Thus we need to put these bytes together into one value.
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }

      // reset the counter, since we have a full message and can now receive the next message
      i = 0;
    } else {
      // increment the counter variable to the next position, if we are currently receiving the bytes of a valid message
      i++;
    }
  }
}

I hope this makes the code clearer. As already said the my previous answer, it doesn't make much sense, to first use the TFMini library (declaring the corresponding objects) and then doing the communication yourself. I would suggest, that you look closer into the TFMini library. Try the examples, that surely come with the library. Use the libraries functions to communicate with the sensors. That will make it way easier for you, since the library will do the communications for you.


text:
Two LED Patterns Task Controlled by GUI
I am very new to Arduino and coding/programing. I set a task for myself to make a simple circuit of 5 LEDs controlled by pins 2, 4, 8, 11, 12. I want to be able to make two different pattern for the LEDs and be able to turn each pattern on or off with buttons in python. I was able to achieve this using millis and several if statements. I have one problem with the code I created and one question.
The problem:
When I run my upload my code and press the buttons on my python gui only one task can run at a time. I would like to be able to run both at the same time if I press both run buttons. I have spent hours trying to find where my code is blocking this from being possible. Any advice on how to solve this problem would be greatly appreciated.
The question:
During my research I stumbled across the possibility of using switch / case commands in stead of several if statements. I tried several times to get this to work but am not wise enough to get it to work. Any tips of how to make this work would be greatly appreciated.
Arduino code:
char serialData;

const int blue1 = 12;
const int blue3 = 8;
const int red1 = 4;
const int red2 = 2;

int blue1state = LOW;
int blue3state = LOW;
int red1state = LOW;
int red2state = LOW;

unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 0;

const long interval1 = 0;
const long interval2 = 2000;
const long interval3 = 4000;
const long interval4 = 3000;
const long interval5 = 6000;
const long interval6 = 9000;

void setup() {
  Serial.begin(9600);
  pinMode(blue1, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(blue3, OUTPUT);
  pinMode(red1, OUTPUT);
  pinMode(red2, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();

  //TASK ONE
  if (Serial.available() > 0) {
    serialData = Serial.read();
    Serial.print(serialData);
  }

  if (serialData == '1') {
    if (currentMillis - previousMillis1 >= interval1) {
      red1state = HIGH;
    }

    if (currentMillis - previousMillis1 >= interval2) {
      red1state = LOW;
      red2state = HIGH;
    }

    if (currentMillis - previousMillis1 >= interval3) {
      red2state = LOW;
      previousMillis1 = currentMillis;
    }
  }

  if (serialData == '3') {
    red1state = LOW;
    red2state = LOW;
  }

  //TASKTWO
  if (serialData == '2') {
    digitalWrite(11, HIGH);

    if (currentMillis - previousMillis2 >= interval1) {
      blue3state = HIGH;
    }

    if (currentMillis - previousMillis2 >= interval4) {
      blue3state = LOW;
    }

    if (currentMillis - previousMillis2 >= interval5) {
      blue1state = HIGH;
    }

    if (currentMillis - previousMillis2 >= interval6) {
      blue1state = LOW;
      previousMillis2 = currentMillis;
    }
  } else if (serialData == '4') {
    blue1state = LOW;
    blue3state = LOW;
    digitalWrite(11, LOW);
  }

  digitalWrite(blue1, blue1state);
  digitalWrite(blue3, blue3state);
  digitalWrite(red1, red1state);
  digitalWrite(red2, red2state);
}

Python code:
import tkinter as tk
import serial
import time

arduinoData = serial.Serial('COM3',baudrate = 9600, timeout=1)
def task_one():
    arduinoData.write(b'1')
def task_two():
    arduinoData.write(b'2')
def off_one():
    arduinoData.write(b'3')
def off_two():
    arduinoData.write(b'4')

HEIGHT=700
WIDTH=800

LED_Control_Window = tk.Tk()

canvas = tk.Canvas(LED_Control_Window, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(LED_Control_Window, bg='#80c1ff')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)

label = tk.Label(frame, text='LED Flash Patterns', bg='#beced4')
label.place(relx=0.34, rely=0.0, relwidth= 0.35, relheight=0.1)

button = tk.Button(frame, text="Task One", bg='#50bd57', command=task_one)
button.place(relx=.15, rely=0.25, relwidth= 0.25, relheight=0.15)

button = tk.Button(frame, text="Task Two", bg='#afbd3d', command=task_two)
button.place(relx=0.62, rely=0.25, relwidth= 0.25, relheight=0.15)

button = tk.Button(frame, text="Stop Task One", bg='#f03535', command=off_one)
button.place(relx=0.15, rely=0.6, relwidth= 0.25, relheight=0.15)

button = tk.Button(frame, text="Stop Task Two", bg='#f03535', command=off_two)
button.place(relx=0.62, rely=0.6, relwidth= 0.25, relheight=0.15)

LED_Control_Window.mainloop()

Can you have a look with PuTTY or something like that to see what the Python code is sending on COM3 when you press two buttons at the same time?

I will give that a shot to see. What happens now when I press the first button the pattern will begin. Then when I press the second button the first pattern pauses and the second one begins. Thank you for the tip!

you have a logic error in your code .... interval1 code always runs when interval1 passes ... then interval1 and interval2 both run ... etc. etc. .... reverse the order of if statements and use else if ... that way you check if interval3 passed .... if it did not, then check interval2 ... and so on ..... switch/case is same as a sequence of else if statements

use if (serialData == '1')  task1 = true; ... then run TASK ONE  if task1 is true ... if (task1) { .... make task1 false at the end of TASK ONE ... do similar for TASK TWO

Thank you both ocrdu and @jsotola for the tips I will comment my updated code when I finish it.


text:
Help solving "collect2.exe: error: ld returned 1 exit status" error in code
I just got an Elegoo UNO starter kit the other day and have been working my way through the little tutorials on all the parts it came with. I am using VSCode with Platform.io plugin and (after getting it set up) it has been working nicely.
The code I am currently struggling with is a sketch that is supposed to use the IR Remote and Receiver the kit came with, I keep getting the error: collect2.exe: error: ld returned 1 exit status
I have done some looking around online but haven't had much luck getting anything to work.
My full code is below:
char foo;

#include <Arduino.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <IR.h>

IRrecv irrecv(RECEIVER);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

void setup() {
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn();
}

void loop()
{
  int tmpValue;
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    for (int i = 0; i < 22; i++)
    {
      if ((keyValue[i] == results.value) && (i<KEY_NUM))
      {
        Serial.println(keyBuf[i]);
        tmpValue = results.value;
      }
      else if(REPEAT==i)
      {
        results.value = tmpValue;
      }
    }
    irrecv.resume(); // receive the next value
  }

//The implementation effect of the above program is
//the same as that of the following, but it is more concise

//    switch(results.value)
//  {
//  case 0xFFA25D: Serial.println("POWER"); break;
//  case 0xFFE21D: Serial.println("FUNC/STOP"); break;
//  case 0xFF629D: Serial.println("VOL+"); break;
//  case 0xFF22DD: Serial.println("FAST BACK");    break;
//  case 0xFF02FD: Serial.println("PAUSE");    break;
//  case 0xFFC23D: Serial.println("FAST FORWARD");   break;
//  case 0xFFE01F: Serial.println("DOWN");    break;
//  case 0xFFA857: Serial.println("VOL-");    break;
//  case 0xFF906F: Serial.println("UP");    break;
//  case 0xFF9867: Serial.println("EQ");    break;
//  case 0xFFB04F: Serial.println("ST/REPT");    break;
//  case 0xFF6897: Serial.println("0");    break;
//  case 0xFF30CF: Serial.println("1");    break;
//  case 0xFF18E7: Serial.println("2");    break;
//  case 0xFF7A85: Serial.println("3");    break;
//  case 0xFF10EF: Serial.println("4");    break;
//  case 0xFF38C7: Serial.println("5");    break;
//  case 0xFF5AA5: Serial.println("6");    break;
//  case 0xFF42BD: Serial.println("7");    break;
//  case 0xFF4AB5: Serial.println("8");    break;
//  case 0xFF52AD: Serial.println("9");    break;
//  case 0xFFFFFFFF: Serial.println(" REPEAT");break;
//  default:
//    Serial.println(" other button   ");

  }// End Case

This is code that was included with the tutorials, but I am not certain it is airtight as I have already had to do some tweaking of the code and header files included with the device.
The error I am getting is the following:
include/IR.h:29:0: warning: "REPEAT" redefined
 #define REPEAT 22
 ^
In file included from src\main.cpp:4:0:
include/IRremote.h:57:0: note: this is the location of the previous definition
 #define REPEAT 0xffffffff
 ^
In file included from src\main.cpp:6:0:
include/IR.h:36:78: warning: initializer-string for array of chars is too long [-fpermissive]
                   "UP","EQ","ST/REPT","0","1","2","3","4","5","6","7","8","9"};
                                                                              ^
Linking .pio\build\uno\firmware.elf
C:\Users\wiley\AppData\Local\Temp\ccDVm6mB.ltrans0.ltrans.o: In function `global constructors keyed to 65535_0_main.cpp.o.1820':
<artificial>:(.text.startup+0x60): undefined reference to `IRrecv::IRrecv(int)'
C:\Users\wiley\AppData\Local\Temp\ccDVm6mB.ltrans0.ltrans.o: In function `main':
<artificial>:(.text.startup+0x160): undefined reference to `IRrecv::enableIRIn()'
<artificial>:(.text.startup+0x16c): undefined reference to `IRrecv::decode(decode_results*)'
<artificial>:(.text.startup+0x1c6): undefined reference to `IRrecv::resume()'
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\uno\firmware.elf] Error 1

I don't understand the errors it is telling me are in the IR.h file. It says that REPEAT is redefined but it only defined once in the file. In regards to the undefined reference to IRrecv:: I dont understand, because I have all the encessary files in the 'Include' folder, and when I CTRL click those functions in the editor it takes me to the files and shows me the code... so why can't it find the code when I run it?
IR.h:
#ifndef _IR_H
#define _IR_H

#define RECEIVER 11

#define KEY_POWER (0xFFA25D)
#define KEY_FUNC_STOP (0xFFE21D)
#define KEY_VOL_ADD (0xFF629D)
#define KEY_FAST_BACK (0xFF22DD)
#define KEY_PAUSE (0xFF02FD)
#define KEY_FAST_FORWARD (0xFFC23D)
#define KEY_DOWN (0xFFE01F)
#define KEY_VOL_DE (0xFFA857)
#define KEY_UP (0xFF906F)
#define KEY_EQ (0xFF9867)
#define KEY_ST_REPT (0xFFB04F)
#define KEY_0 (0xFF6897)
#define KEY_1 (0xFF30CF)
#define KEY_2 (0xFF18E7)
#define KEY_3 (0xFF7A85)
#define KEY_4 (0xFF10EF)
#define KEY_5 (0xFF38C7)
#define KEY_6 (0xFF5AA5)
#define KEY_7 (0xFF42BD)
#define KEY_8 (0xFF4AB5)
#define KEY_9 (0xFF52AD)
#define KEY_REPEAT (0xFFFFFFFF)
#define KEY_NUM 21
#define REPEAT 22

unsigned long keyValue[]={KEY_POWER,KEY_FUNC_STOP,KEY_VOL_ADD,KEY_FAST_BACK,KEY_PAUSE,KEY_FAST_FORWARD,
                KEY_DOWN,KEY_VOL_DE,KEY_UP,KEY_EQ,KEY_ST_REPT,KEY_0,KEY_1,KEY_2,KEY_3,KEY_4,KEY_5,
                KEY_6,KEY_7,KEY_8,KEY_9,KEY_REPEAT};

char keyBuf[][10]={"POWER","FUNC/STOP","VOL+","FAST BACK","PAUSE","FAST FORWARD","DOWN","VOL-",
                  "UP","EQ","ST/REPT","0","1","2","3","4","5","6","7","8","9"};
#endif

I have searched online a lot, and this seems to be a common issue with this IR.h library, and none of the fixes proposed have got me anywhere. (I get the same outputs when trying to run this sketch within the Arduino IDE with all a libraries installed)
I have been developing with Java and Python for a while now, but I have almost no experience with C or C++ before the Arduino, so maybe this is a simple error I just don't understand. Super frustrating!! Any help or guidance would be appreciated! Thanks

The "real" error messages are the "undefined reference" lines. The compiler (linker in fact) can't find the code (.cpp) files for one of the libraries (IRremote probably). The Arduino IDE does some magic to take care of that automatically, but I'm not familiar with VSCode or Platform.io. Look for options to include libraries somewhere in your project settings or something like that.

BTW the warning before that is pretty deadly (memory corruption bug). The loop must be adjusted so that it doesn't go over keyValue's bounds.

I have made sure all the .h files and .cpp files I am using are in the "Include" folder of the project, which has worked with the previous header files. It's silly that it says it cant find the code because if I CTRL click on the methods in the editor it takes me right to the .cpp file it is in, inside the "Include" folder, so I dont get why it cannot find it at run time.

Also, I dropped the loop down to 22 and that issue regarding the loop dissapeared, but more appeared regarding the .h files. Will update OP

You don't include .cpp files, you need to compile (and then link) them. Again, I don't know your setup, but the .cpp files shouldn't be in include settings. See if you can add extra source files somewhere in the project settings.

I have figured it out. PlatformIO has a really convenient Library manager that helps with set up. You just select a library and it will automatically add it to the project you choose and make sure the correct dependencies are listed in the .ini file. Thank you for your help!

You can take your comment and post it an answer instead.

I had problem with the Serial library, which caused that problem.

I have figured it out.
The problem was I had not properly set up the project with the proper libraries. I thought I was doing it right manually but I was not. PlatformIO has a really convenient Library manager that helps with set up. You just select a library and it will automatically add it to the project you choose and make sure the correct dependencies are listed in the .ini file. I was trying to manually drop the files I needed into the correct directories, and was not doing the proper adjustments to the .ini file. Thanks for the help @Mat!


text:
Arduino Esp8266 Signal(TIMER0_COMPA_vect) can’t compile
Trying to compile a program containing the statement SIGNAL(TIMER0_COMPA_vect) written for arduino. But I want to use it on an esp8266 board. The code will compile  for Arduino uno. But I get an error “expected constructor, destructor, or type conversion before ‘(‘ token when I try to compile for a Wemos D1 board. Can anyone help me convert the statement to pass the compile test. Thank you

That instruction is for setting up an interrupt handler for the timer. It is very much specific to the AVR.
There's a lot more to do that just adjust that one statememt - you have to completely rewrite the whole of the timer code that you're using to operate with the ESP8266 SDK calls.
Without knowing what your code intends to achieve it's impossible to help you further, but this library may be of help to you.


text:
My circuit is being goofy with regards to my PIR sensor
Here is the code I've written so far. I am making a circuit with a couple of motors and 3 sensors. My plan is for the PIR Motion sensor, distance sensor, and photoresistor to tell the motors to stop when they're triggered. When I set the if proximity = LOW, the LED lights up whether I move the sensor or not. But when it's set to HIGH, the LED won't light up even if motion is detected. I've tested it separately from the rest of the code and it doesn't do this. Is there something wrong with how I've got my simultaneous loops?
int inches = 0;
const int ledPin1=11; // blue LED
const int ledPin3 = 9; // red LED
const int servoPin = 4; // blade motor
const int MOTION_PIN = 2; // Pin connected to motion detector
const int ledPin2 = 10; // green LED
const int photoPin = 3; // photoresistor connected to digital pin 2
const int motorPin = 13; // motor for the wheels connected to digital pin 13
int cm = 0;

long readUltrasonicDistance(int triggerPin, int echoPin) // setting up the distance sensor, this code is pre-set up along with the circuit
{
  pinMode(triggerPin, OUTPUT);  // Clear the trigger
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);
  // Sets the trigger pin to HIGH state for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);
  // Reads the echo pin, and returns the sound wave travel time in microseconds
  return pulseIn(echoPin, HIGH);
} // long

void setup()
{
  Serial.begin(9600); // loop time
  pinMode(ledPin1, OUTPUT); // sets the blue LED as an output
  pinMode(ledPin3, OUTPUT);
  pinMode(MOTION_PIN, INPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(servoPin, OUTPUT); // blade
  pinMode(photoPin, INPUT); // light sensor
  pinMode(motorPin, OUTPUT); // wheels
} // end setup

void loop() {

    dist();
    motion();
}

void dist()
{
  // measure the ping time in cm
  cm = 0.01723 * readUltrasonicDistance(7, 7);
  // convert to inches by dividing by 2.54
  inches = (cm / 2.54);
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.println("cm");
  if (cm<150) // if an object (another person) approaches within 1.5 meters
  {
  digitalWrite(ledPin1, HIGH); // turn on the blue LED, symbolically represents roomba reaction to go around or stop
  } // end loop
}

void motion()
{
  int proximity = digitalRead(MOTION_PIN);
  Serial.println(proximity);
  if (proximity == HIGH) // If the sensor's output goes high, motion is detected
  {
        Serial.println("Motion detected!");
        digitalWrite(ledPin2, HIGH);
  }

}

you are adding multiple layers of confusion to your code ...  ledPin2 refers to pin 10, not pin 2 ...     it makes more sense to name it something like greenPin

So, proximity is always LOW, which means MOTION_PIN is always 0. Maybe your PIR sensor isn't connected to pin 2, or maybe it needs a pull-up or pull-down resistor on its data pin.


text:
Arduino waits until button release to activate
I'm fairly new to arduino, and on my own I'm trying to move a servo to the left and right using 2 buttons.  I've got it working for the most part, however when I hold the button down nothing happens, and when I finally release the servo moves a certain amount based on how long I was holding the button down.  I would like the servo to move when the button is being held down though.  The servo also occasionally moves oddly and sporadically.  I'm thinking its most likely a logic error in the code, but I can't figure it out.  Could someone please tell me what they think I've done wrong?  Thank you.
code:
#include <Servo.h>
Servo servo;

#define right 9
#define left 8

int angle = 90;
int angStep = 5;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(right, INPUT_PULLUP);
  pinMode(left, INPUT_PULLUP);
  servo.attach(2);
  servo.write(angle);
  Serial.print("Begin");
  Serial.print('\n');
  Serial.print(angle);
  Serial.print(angle);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(left) == HIGH && angle < 180){
    angle += angStep;
    Serial.print(angle);
    Serial.print('\n');
    servo.write(angle);
    delay(50);
  }

  if (digitalRead(right) == HIGH && angle > 0){
    angle -= angStep;
    Serial.print(angle);
    Serial.print('\n');
    servo.write(angle);
    delay(50);
  }
}

check for the opposite signal level at the button pin

Connect the 'output' signals (that goes in the Arduino pin 8/9) instead to a resistor and a LED to see if it behaves like you expect. This rules out if there is a software or hardware problem.

I think it's because you are using a pullup resistor, so it's constantly HIGH instead of constantly LOW. Try changing HIGH and LOW to the opposite.

I tried swapping the HIGH and LOW and nothing happened, so I just switched back to high and changed input_pullup to just input.  Now the servo moves but just completely randomly and i don't know why it's so inconsistent.


text:
Custom PS4 joystick with arduino
I am acquiring a Logitech G29 for my PS4 and I want to have an external handbreak. The handbrake only needs an input when active, so no "pressure level" or something like that required, only "on" or "off".
I have come around a few answers such as this, but I am not sure how to make it work on PS4 (and even if it needs some changes what so ever).
I don't have enough knowlegde to ask the correct questions, so I am asking for directions on basically how to send an arduino signal so the PS4 interprets as a joystick command (which in game I will configure as the handbrake option).
I am somewhat aware about the necessity of a custom library, but nothing more than that, not even what that really means to be honest.
The drawing bellow is somewhat the scheme for my project. And it is based on what I understood from this post.

Thank you for your time!

Do right as the reddit post says: Buy an Arduino with native USB capability (Leonardo or Micro for example). Then read the input from the handbreak switch. Then send keystrokes with the Keyboard library to the computer. Would that answer your question? If not, where exactly lies the problem?

Thanks for the reply. It's a good start. I have access to an Arduino UNO, so I will check about this USB capability. About the Keyboard library, you said "send keystrokes ... to the computer"... I actually need to send it to my PS4, is the approach the same? Does the library change? Again, thanks for the repply

The Uno has no native USB capability. You need a different Arduino. And computer and PS4 are equivalent here. The PS4 seems to support normal USB keyboards, just like a computer. When using the keyboard library, the Arduinos USB interfaces behaves like a normal USB keyboard. Thats exactly the way, that the reddit post took.

Thanls for the directions, I think I'll be able to continue from here. If I may ask one last thing, since I currently only have UNO, any way to implement the USB componet? I am not sure it even is a component, i'm really new to this - or any other way around to use the UNO?

The ability of using the Arduino as a Keyboard/Mouse depends on the Chip. For example, the Arduino Leonardo has a AtMega32U4, which has the ability but the Arduino UNO has a AtMega328P that isn't able to wok as a USB input device.


text:
Serial.print skips or hangs inside a "if" statement. Trying to call a function VIA serial uart
I have two microcontrollers talking to each other using serial UART pins.
Now for some reason which I can not figure out why... doing a Serial.print() does not work in an "if" statement. And also assigning/declaring/initializing variables and values inside the "if" statement does not work... this is really weird. I can turn on the GPIO pins in the "if" statement but other than that nothing else works.
Microcontrollers are: Arduino Nano and WeMos D1 Mini.
Just want to note that both of the microcontrollers are talking to each other fine and arduino can determine the serial input but it can not "Serial.print" in the "if" statement of "strcmp", it is being skipped.
EDIT: I just woke up this morning, and magically "Serial.print" is working properly inside the "if" statement of "strcmp"... I guess the microcontroller needed some rest, I was testing it for 13+ hours...
Please view the code below:
    void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
      char a[5];
      delay(100);
      int i = 0;

      if (Serial.available() > 0)
      {
        while(Serial.available() > 0)
        {
            a[i]=Serial.read();
            i++;
        }

        a[i] = '\0';  //last character inserted with a "null char".
      }

     if(strcmp(a,"RGB_1") == 0)   //<----- "if" statement, comparing the string array buffer
     {
        int m = 1; //<---------------- declaring and initializing a variable
        //Serial.print(m); //<-------- Serial monitor will hang and skip the GPIO pins below to trigger.
        digitalWrite(12, HIGH);
        delay(1000);
        Serial.print(m); //<---------- "if" statement allows the GPIO pins to trigger but skips this serial print.
     }
   }

print the value of i

High likely you are exceeding your character array, see:
char a[5];

Which can hold 5 characters. However, you write:
if(strcmp(a,"RGB_1") == 0)

Which assumes you receive "RGB_1" which is 6 characters, because a string ends with a 0.
What also might happen is that you indeed receive only 5 characters without the ending newline, which means strcmp keeps searching until it finds a string end which may not happen.
So you can increase the array size a few just for testing purposes, and print i as jsotola proposes. Beyond that, also print each character you put into the array so you know how/if to handle a new line.
If you don't receive a string end, then use instead of the strcmp function, then use strncmp, which can search for exactly 5 characters, not checking until the end of the string.

@S-To: No. a[5] holds 5 values, indexed 0 to 4.

@ Michel Keijzers Thank You for quick comment.

@ocrdu Yes you're right, my bad.... just had a brain fart.


text:
My DHT22 module doesn`t work at all
I had bought this DHT22 module on AliExpress. The module looks fine, but it does not work at all. I had tried lots of sketches, I tried to change the pin, I tried to change the cables, but I always have the same result:
Failed to read from DHT22 sensor!.
That's what I get if I use the standard sketch DHTtester.ino:

That's what I get if I use the standard sketch DHT_Unified_Sensor.ino:

Can you help me? Or is the module corrupted?

The sensor wants a pull-up resistor of about 10kΩ between DATA en VCC; does your module have one? What voltage are you giving it? Some don't work properly at 3.3V.

@ocrdu, yes, it has a 103 10 kΩ SMD resistor. The voltage`s 5V since the module is connected to Arduino Uno R3 via Arduino Sensor Shield V5.0.

The product page you linked to has modules of different types.
Make sure you have uncommented the matching type in the this section of the example:
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

Also makers of these boards sometimes label them incorrectly or describe them incorrectly when selling them.  If you're unsure what you have, try them all.

I wonder that it is not my case. My sensor is truly not a DHT11, since the 11s have blue cases and mine has a white one. Though I'll  try to switch the code to the DHT21 option. Hope this one helps. But aren't the 21 and the 22 cross-compatible?

**edit: **Also, the Internet says that DHT21 has a black case, they truly cannot be messed up.

@Starter, I dunno how consistent the case is either, but it probably is useful indicator if not definitive.  I believe you are correct with respect to the DHT21 and DHT22.  Looking at the Adafruit library for them, they certainly seem to be treated the same way in every case.  If you wind up solving the problem yourself and the answer is something entirely different, you should probably make your own answer and mark it accepted.


text:
How to include a file from another (parent) directory
This is my structure
program/
  src/
    Makefile
    main.ino
    test.h
    ...
  lib/
    i2c.h

In main.ino I include test.h and in test.h I'm trying to include i2c.h but it is just not working, I keep getting:
make: *** No rule to make target 'i2c.h', needed by 'build-uno/main.ino.o'.  Stop.

I tried including like this
// test.h
#include "../lib/i2c.h"

I also tried making a symlink to my lib folder in arduino libraries and adding it as a library in Makefile
sudo ln -s /home/pi/program/lib /usr/share/arduino/libraries/GAVR
# Makefile
ARDUINO_DIR = /usr/share/arduino
BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyAMA0
ARDUINO_LIBS = GAVR
include /usr/share/arduino/Arduino.mk

I also tried making a symlink to lib inside the src directory
ln -s /home/pi/program/lib /home/pi/program/src/lib
None of the above had any effect, the error message stays the same.
How can I include a file from another directory in my program?

It's a make error not compilation error. If you have rule, for main.ino, where is that i2c.h listed as dependency and it's not in the same directory, it'll fail. Depends on Makefile directory it might be ../lib/i2c.h (or you can ommit this dependency, but if it changes, it won't get recompiled)

@KIIV I'm still quite new to c and I don't really know what I'm doing. My Makefile is in the src directory and I have posted the contents of it. I'm not aware how I must specify the lib directory as part of the build process. I found many examples that suggest adding -I to gcc but the arduino makefile does magic and I don't know how to add parameters to the compiler command.

I was using platformio (as there was no command line interface back then). 1. libraries are usually in it's own subdirectory, so it might need something like lib/i2c_lib/i2c.h and ARDUINO_LIBS=/home/pi/program/lib

If you don't know what you're doing with a Makefile (and Makefiles are black magic) then you really shouldn't be using one. If you must use the command line then use ardiuno-cli instead. Also be aware that building is not normally done in the source directory but in a separate build directory elsewhere.

@Majenko there are probably a lot of things I'm doing wrong, but all I care about is my program to work as I expect, everything else is noise. It's a hobby project on which I'm working alone so nobody is going to suffer from my ignorance and I'll likely never do any professional work with C, so it's fine. Guess I'll follow the advice if I can't figure out a way to make the Makefile work.

You may suffer the same problem with arduino-cli because of how Arduino building is done - not in the source directory. You will have to work out what the build directory's path is relative to where your file is. If you are using a proper library, though, then arduino-cli will know that and handle it all for you.

@Majenko I seem to have found a solution, following the symlink to /usr/share/arduino/libraries/GAVR I just had to create a GAVR.h file which includes my other files. That would probably make a proper C programmer cringe but it works for me, so I'm not sure whether I should put it as an answer or delete the question altogether.

Put it as an answer. It may help someone. And hey, if it works it works. In C there is more opinion than right and wrong.

This is definitely on the hacky side and not a proper solution to the problem, but it works nevertheless so I'm sharing it.
After making a symlink in the /usr/share/arduino/libraries directory you must make sure that there is a header file with the exact name of the directory, apparently that's how arduino is set up to include them.
In my case my symlink was named GAVR, so I had to create a GAVR.h file inside my lib directory, which would then go ahead and include my i2c.h file and possibly any other file that I'd need.
Also in test.h or anywhere I need to use i2c.h I must include <GAVR.h> instead.
Turns out Also 1 is false, you just need to include <GAVR.h> once in the .ino file and its members will be available everywhere, just like any other library.
Also 2, now that ARDUINO_LIBS is not empty in the Makefile you will need to manually declare all libraries that your code is using.


text:
Does the compiled binary of a sketch include uncalled functions from a library?
I am writing a GUI using a TFT display and the Adafruit GFX library and its default font on Arduino Nano.
I want to be memory efficient and I assumed that the 'optimise for size' default setting of the compiler would not compile and include all functions from all included libraries if those functions are never called in the sketch.
However I was reading this memory management guide which advises (on pager 20) to remove 'unused libraries' and 'unused functions' from your sketch to save memory.
So I have 2 related questions:

Does the Arduino IDE compiler include all the compiled binary from these library functions even if they are never called in the source sketch (I know that any global variables in a library will take space even if unused but I am specifically asking about unused functions)?

If that is the case would making my own modified, trimmed down, version of the standard libraries save space?

Thanks.

In general only the functions actually used by your code are included in the final linkage of the binary.
However it's not always possible for the compiler to know what is used and what isn't.
In the case of simple functions and classes there's no problem - the linker is intelligent enough to work it out and only link in the functions that are actually used.
However when it comes to more complex systems with polymorphism or when working with function pointers there are times when the compiler won't really know what is needed and what isn't so sometimes some code gets included that isn't actually wanted.
As the compiler advances those times are getting fewer and farther between, so unless you really have a dire need to reduce your code size there's really nothing much to gain. If you do have that need then you would gain more by reducing the complexity of the code in general and collapsing any polymorphism rather than removing unused functions.
BTW: the "optimize for size" has nothing to do with what code is included / excluded. Instead it controls such things as which function are selected for inline, and what loops are unrolled or not, amongst other things.

some Arduino cores don't use LTO. for example for the STM32 core by STM the LTO option never produces a working application binary

@Juraj It will still only include what is needed. LTO is more for pruning polymorphism. That's the "As the compiler advances..." bit - LTO improves it a massive amount, but there has always been selective inclusion and -ffunction-sections --gc-sections etc.


text:
What are a few good ways to connect multiple I2C busses?
I have an issue with a project. I have a backplane with an Atmega328P based microcontroller controlling an I2C bus with multiple peripheral devices. One such peripheral is a removable card with another Atmega328P based microcontroller as the peripheral. I have a TCA4311ADR I2C hotswap buffer on the backplane connected to the port that connects to the card. The card is supposed to be a peripheral device that sends processed data from a sensor to the backplane.
Here’s my issue: one of the sensors I intend to use on the card is an I2C breakout board. To control it, the microcontroller on the card needs to act as a controller, but it also needs to be a peripheral to communicate with the backplane controller. Every time I try to make this work and the card tries to communicate with the sensor, it tries to start a new I2C bus and everything starts glitching.
I’ve tried a few options. Software used to turn normal digital pins into I2C pins didn’t work since the libraries don’t seem compatible. I can’t seem to get the card peripheral to wait until the controller starts the bus before trying to control the sensor to avoid a conflict.
I had an idea to use an I2C multiplexer like the TCA9543A to create two busses but I don’t know if that would work. I also don’t wanna just use SPI or Serial to connect the microcontrollers cause I’d have to undo months of work on coding and custom PCBs. Also using Serial would complicate the connection to the computer and using SPI wouldn’t work if I use an SPI sensor breakout later.
Is there any other way to make this system work?

I2C allows for multiple masters. So you could (indirectly) connect the breakout board to the main I2C bus. Then have the ATMega on the removable card change between master, and slave mode. You'd have to add a way to prevent collisions, as the ATMega doesn't support this part of I2C. Or gracefully deal with with them when they occur.

In an ideal world you would have your other sensor on a separate I2C bus. It can be done with software, but chances are you will have to re-write the library that supports it to use bit-banged I2C.
Yes, you could use an I2C MUX to share the single hardware I2C channel, however that will both be awkward and the results will be sub-optimal anyway.
Most I2C MUX chips, including the TCA9543A, are controlled themselves by I2C, so you can't really use them in your environment, since you really need to switch it to isolate your main bus from the MCU before you switch it from slave to master, which you can't do until after you have switched it from slave to master. If you switch to master before isolating the bus you risk a collision with the main master on the bus and everything going horribly wrong.
These MUX chips are really designed for allowing one master to talk to multiple slaves that share the same addresses.
And on top of that when you've isolated the bus the main master will no longer be able to communicate with that slave board, which will either cause the whole bus to lock up or other strange and unwanted things to happen.
So have another go at using software I2C to communicate with your sensor. Most I2C communication to sensors is pretty straightforward and follows the same rough format, so it really shouldn't be too hard to implement.
Either that or consider replacing the ATMega328P with a more capable microcontroller that has multiple I2C busses.


text:
Uno Wifi Rev2 Programming via Uno R3 ArduinoISP
I'm attempting to program Atmega4809 (Uno Wifi Rev2) via the ICSP pins on the board by connecting in this manner:
The difference is that I have a Uno Wifi Rev2 on the right instead of a Uno R3. I've uploaded the ArduinoISP sketch onto the Uno R3 on the left. Here is the avrdude command that I am using:
$ avrdude -v -patmega4809 -cavrisp -P /dev/ttyACM1 -b19200 -U program.elf

...

avrdude: AVR device initialized and ready to accept instructions

Reading |                                                    | 0% 0.00savr_read(): error reading address 0x0000
    read operation not supported for memory "signature"
avrdude: error reading signature data for part "ATmega4809", rc=-2
avrdude: error reading signature data, rc=-2

Full log: https://pastebin.com/LUfhsYeD
I am wondering if I am missing some difference between the UnoR3 and Uno Wifi Rev2... there doesn't seem to be much documentation about external programming of the Uno Wifi Rev2's Atmega 4809.
If it helps, my usecase for trying to program my Uno Wifi Rev2 externally is a need to reprogram the 32u4 as a HID. Once I program the 32u4, I won't be able to program the 4809 via USB (afaik).
If anyone knows what I'm doing wrong or the proper way to program the Uno Wifi Rev2 externally, your help would be greatly appreciated.

those are not ICSP pins. there is only SPI. the USB chip (32u4) programs the ATmega over UDPI

The new generation of AVR chips created by Microchip no longer use the same ICSP protocol as the old ones. Instead they use a new protocol called updi.
You need to use a different sketch and wiring to turn your Arduino into a suitable programmer.  More information can be found here about how to do that.

Do the 6 pins labeled ICSP really use UDPI? Is the programming still over these pins? In the schematic, I see a UDPI pin that goes from the 4809 to the 32u4...

You will have to check the schematics and datasheet for the chip to know what pins to use.


text:
How do i make my DC motors run simultaneously?
Im coding an adafruit motor shield for  3 DC motors to go forward & backwards, and so my concern is why only my motor3 is running the whole time and motors 1 & 2 are switching off meaning 1 goes than 2 goes and on and on? My code is below if you see where my mistake is in the code can you just tell me what it is and what to do to make them run simultaneously?
#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor(3);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");
  // turn on motor
  motor1.setSpeed(300);
  motor2.setSpeed(200);
  motor.setSpeed(500);
  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  //third motor
  Serial.print("tick");
  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  //second motor
  Serial.print("tick");
  motor2.run(FORWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }
  Serial.print("tack");
  motor2.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");
  motor1.run(FORWARD);
  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
  Serial.print("tack");
  motor1.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
}

well I haven't ran it yet because I don't know what to put in my code to make the motors run for a certain amount of time!

My question is how would I make my motors run a certain way for a certain amount of time? For an example, motor moves  Forward for 2 seconds!!!

@jstola I did what you said to do and start off with one motor going one direction, than I finished that motor and then I did the two other motors. And everything is working great except the exception that only motor 3 is running the whole time, and  for motor 1 and 2, they switch off meaning like 1 does its runs s than 2 does its runs, how do I make it so they all run simultaneously?

referring to the sketch above ... do the motors move the way you want them to? .... right now, they take 2 1/2 seconds to ramp up in speed and 2 1/2 seconds to ramp down to stop ... have you tried larger increments between steps?

The simplest approach to include a delay in your sketch is to call the Arduino delay() function.  Pass this function a delay value in milliseconds.  For example, a 1 second delay is 1000 milliseconds.
As simple as this method is, it is not recommended if your sketch is required to accomplish tasks during the delay.  This is a common requirement and frustrates many new programmers.
In order to accomplish tasks while waiting for an arbitrary period of time, do not use the Arduino delay() function.  Instead use the Arudino millis() function.  The millis() function will return the number of milliseconds passed since the Arduino board began running the current program.  Record this number, execute the desired action then enter an infinite loop until millis() return a number which indicates the desired number of seconds have passed.  While in the infinite loop the program can execute other tasks as long as they take small amounts of time relative to the desired delay.  Such as testing for a switch closure and turning on an LED.
Essentially, this new program is now a simple finite state machine.

What you're searching for is called "non-blocking programming", a technique in which you frequently test or evaluate whether something needs to be done, and either do it or not, but move on immediately. For one motor, you could block successfully (do nothing else while you wait for something to happen): start/wait/stop/reverse/wait/stop/... etc.
But for two more more motors that need to run independently, your code must not block but decide quickly whether to do a particular thing now or not (start or stop a motor, f/ex), and move on to the next decision.
This article describes how to do that in more detail
(full disclosure: it's one of mine).

Start with the BlinkWithoutDelay example code and make modifications to suit your needs.
This is the original code.
    /*
  Blink without Delay

  Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Here are the changes that cause the LED to light up for 500 ms, then go dark for 5000 ms.
The changes are marked by // *************.
Hopefully, this will get you the idea about how to use millis() to control a device at desired intervals.
        /*
          Blink without Delay
          http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
        */

        const int ledPin =  LED_BUILTIN;                        // the number of the LED pin

    //  int ledState = LOW;                    // ************* // change this assignment as follows

        int ledState = 0;                      // ************* // ledState used as a state counter

        unsigned long previousMillis = 0;

    //  const long interval = 1000;            // ************* // change the interval as follows

        const long interval =  500;            // ************* // use a 500 ms interval

        void setup() {
          pinMode(ledPin, OUTPUT);
        }

        void loop() {
          unsigned long currentMillis = millis();

          if (currentMillis - previousMillis >= interval) {

            previousMillis = currentMillis;    // ************* // program arrives here every 500 ms

    //      if (ledState == LOW) {             // ************* // this code is not needed
    //        ledState = HIGH;                 // *************
    //      } else {                           // *************
    //        ledState = LOW;                  // *************
    //      }                                  // *************

    //      digitalWrite(ledPin, ledState);    // *************

            if (ledState == 0 ) {              // *************
                digitalWrite(ledPin, HIGH);    // ************* // turn on LED at start of cycle
            }                                  // *************
            else if (ledState == 1 ) {         // *************
                digitalWrite(ledPin, LOW);     // ************* // turn off LED at end of 500 ms
            }                                  // *************

            ledState++;                        // ************* // increment state counter
            if (ledState > 10 )  ledState = 0; // ************* // reset ledState when it has reached end of cycle

          }                                                     // end of if
        }                                                       // end of loop


text:
NRF24l01 Channel switching
I have a NRF24L01 radio module. The description indicates that it can work in the ISM frequency range of 2.400 ... 2.525 GHz. The channel step is 1 MHz, and there are 125 channels in total.

The channel number can be set using
radio.setChannel (0x125);
The maximum number is supposedly 125. However, I examined the signal spectrum in Sdrsharp using a radio tuner and it turned out that the frequency at the maximum channel is very low.

I started increasing the number and got to 180 radio.setChannel (125); the frequency was 2525 MHz as stated. It turns out that the number of channels of the radio module is not 125, but 180? I determined the 180 number experimentally. The literature says that it has 125 channels 1 MHz wide.
The most interesting thing is that the Arduino IDE does not give errors when entering a large number of channels. Tell me how you can speed up the process of switching channels in order to understand how they switch. To manually reflash it for a long time when changing each channel.
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

RF24 radio(9, 10); // use 9 и 10 pin arduino uno
byte address[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node", "6Node"};
byte counter = 1;

void setup() {
  Serial.begin(9600);

  radio.begin(); //activate module
  radio.setAutoAck(0); //confirmation mode, 1 on 0 off
  radio.setRetries(0, 15); //(time between attempts to reach out, number of attempts)

  radio.setPayloadSize(32); //packet size, in bytes

  radio.openWritingPipe(address[0]); //we are pipe 0, we open a data channel
  radio.setChannel(125); //select a channel (in which there is no noise!) 0 ... 125

  radio.setPALevel (RF24_PA_MIN); //transmitter power level. To choose RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX
  radio.setDataRate (RF24_2MBPS); //exchange rate. To choose RF24_2MBPS, RF24_1MBPS, RF24_250KBPS
  radio.powerUp(); //get started
  radio.stopListening(); //do not listen to radio broadcasts, we are a transmitter
}

void loop(void) {
  while (1)
  {
    radio.write(&counter, 1);
    //Serial.println(counter);
  }
}

Is it possible to toggle the channel number radio.setChannel (0x180) sequentially in a void loop?
thanks!
I tried to do this:
void loop (void) {
     for (int n = 0; n <126; n ++)
     {
       radio.setChannel (n); // select a channel (in which there is no noise!) 0 ... 125
       radio.write (& counter, 1);
       delay (1000);
     }
}

However, radio.write (& counter, 1) should work separately from any loops to avoid delays. Otherwise, it doesn't work correctly.

181 != 0x181 - learn your bases.

setChannel expect an single byte value, so your 0x180 get truncated to 0x80 (which is 128 in decimal). The library then lowers this to 125, because it's too high a value.

You're getting confused with number bases. A number prefixed with 0x is hexadecimal. That's base 16 - not base 10.
0x125 is actually 293. If you try squeezing 293 into an 8-bit register it will truncate to 37.
Channel 125 is 0x7D in hexadecimal.
I can't recall off hand how big the register is for the channel number, but either 7 or 8 bits would suffice (probably only 7 bits actually used) so the highest channel number you could possibly enter would be 127, which is 0x7F, after which it will start at channel 0 again for 128 or 0x80.

Thank you, but how can you switch the channels in order automatically?

In the way you are already - but you may need to power down before changing channels.

Is it possible to remove the 0x prefix and enter the channel number from 0 to 125 as a decimal number?  After all, this is much clearer and more convenient.

Of course. It's just a human representation of the number. You could even go as far as to use 0 to 0175 and use octal if you wanted. It's just numbers.

Ultimately it is up to you to follow the rules and regulations set forth by your country’s wireless spectrum regulatory agency. If you are in the RF band, appropriately licenced and at legal power you are OK. From your post you can do that with your Sdrsharp.