text:
Unable to find arduino on device manager
I have just got a new Arduino robot for Christmas and I have plugged my robot into my computer and I have read the instructions from the manual that the robot was provided with and told me to go to the device manager in the control panel and look under unknown devices, unfortunately I was unable to find it. However I looked under ports and I found that there were 3 ports, I eventually found out that if I took the Arduino plug in and out of my PC that port COM5 was the Arduino, the problem I am having now is to know how to get this port to recognise my Arduino

one error that always comes up when trying to upload the code onto COM5 is this:
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa1

This is what the arduino looks like

Link for where I brought the arduino kit from:
https://www.amazon.co.uk/ELEGOO-Tracking-Ultrasonic-Intelligent-Educational/dp/B01M6YHRJ4/ref=sr_1_1_sspa?keywords=elegoo+robot&qid=1577982862&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyVjVXTk9VMDlUTTg1JmVuY3J5cHRlZElkPUEwMjc4NjYwOEVGNEoxM1Y0QzIwJmVuY3J5cHRlZEFkSWQ9QTA4OTA1NzAzTTNBVFJMV09aVjJRJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==

This is what shows up on the arduino IDE when I select COM5 (which should be my arduino)

@jsotola how come when I try to load it onto my arduino it comes up with the error: (shown above)

what device do you have? ... add a link to your post .... upvote for adding info about avrdude to the post instead of putting in comments

Try a few random things. Unplug your arduino and reboot your computer. Plug it back in before starting the Arduino interface, look in the menu to be sure the right Arduino device is selected. Look for the serial port and be sure the right one is selected - it might have changed.

It is likely that this is a driver issue. I have encountered similar errors, and by updating/installing the drivers, it fixes itself

It seems your computer recognize the serial port of the Arduino device, but doesn't know how to 'talk to it'.
In most USB to TTL devices (that are included in Arduino and ESP8266 boards) you need to install their driver (like CH341 driver) BEFORE you plug in your device.
Please try to find/identify the 'USB to Serial' chip you have on the board, and install its drivers.
Good Luck!

I am only a teenager and do not have much knowledge on arduino itself. Can you possibly guide me on how I can do this please.

You're totally welcome (and after I upvoted your question, you have upvote privileges too...). Let's start by finding the exact model number of the Arduino you have. Can you put a link to where it was bought? or a picture of the board itself?

I can firstly start off by saying that it is an Arduino Uno. I got it as a christmas present, so I am not 100% sure about it fully.(A picture of the arduino is shown above). The links for where I brought it from is also shown above as well

sorry if my webcam is not very clear

Good you've updated more details about the board. The picture is good. This is not a solution, but just found this: https://forum.arduino.cc/index.php?topic=521632.0 about the board you're using. Also - This search brings many answers and tutorials that make sense to me: https://www.google.com/search?q=elegoo+uno+r3+usb+driver . Would you try to look into this available information and update us what makes sense to you? GoodLuck!

Oh yeah, there was one more thing I forgot to mention was that the arduino IDE does see COM5 but doesn't see it as being an arduino though. (shown above)

Totally understood. It was clear from your first screen capture, and my answer stays the same. Please make some more investigation using the resources I've mentioned, and let's know what have you discovered.


text:
using multiple hc-05 with one arduino mega
please anyone help me build my project, i want to connect multiple smart phones to arduino mega using blutooth module hc-05 , I am working on real life home automation project and i don't have idea that can i use 4 Bluetooth modules with arduino mega . Requirement is max 4 smart phone connect to system , please anyone knowing about arduino please help ,i will be grateful . if u have any other suggestions tell me .

start with the example blink sketch ... try several of the example sketches that you can find in the Arduino IDE .... work your way up to bluetooth modules

do you know how to use one HC-05 module?

Yes i do , please help me to connect 4 Hc 05 in one Arduino mega, i need to connect 4 smartphones to one Arduino mega

I am making home automation project so it needs to connect 4 smartphones , looking forward for your help

This SE is for Q/A, not a project help service!

HC-05 modules use Serial (UART) for communication with the Arduino. Thus you need 4 Serial interfaces for 4 HC-05 modules. The Arduino Mega has 4 hardware Serial interfaces, so just connect once HC-05 to each Serial interface. Then handle each module in your code the same just with a different Serial interface. If you already know, how to use one HC-05, then it should be rather easy to implement the same with all 4 modules.

can't one HC-05 communicate any number of smartphones (one at the time)?

Sure it can. But as I read the question the 4 smartphone should be connected at the same time

source: Stack Exchange

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

sort: votes


text:
op amp circuit single sourced from arduino power
Getting an audio signal from a 3.5mm jack amplified (non-inverted) and fed into analog in pin on a Mega 2560. I am having problems using a potentiometer as a variable resistor to adjust gain. I'm also getting a lot of noise (+/-10 units on the 0-1023 scale)
Circuit:
- The audio is from a mono 3.5mm jack, playing from my laptop (with audio split to my speakers).
- Audio goes through an op amp TL071, single sourced shared with arduino 5V
- The potentiometer is wired with 2 pins as a variable resistor. The pins are connected to ground and the inverting input (VCC-)
- Output signal from the op-amp is biased by 2.5V and seems to work fine.

I'm closely following the instructions here (https://www.instructables.com/id/Arduino-Audio-Input/) but with a TL071 op amp as a single sourced from the Arduino 5V power supply.
The potentiometer doesn't seem to make much difference; I can even unplug it and I still get some readings on A0. I'm misunderstanding how to 'rewire' the op-amp for a single supply, but I can't figure out what else I can do.

I've also tried moving the variable resistor to bridge the output and inverting input (swap with the 100k resistor)

In case anyone is looking for a solution, I followed the TL071 manual (texas instruments) for an op-amp instead of using the diagram posted above. That signal then links into a bias.
The noise was coming from having 5V shared with the LED lights (WS2812B). Once I put them on a different circuit (shared ground) it was ok.

The TLO series don't work with 5v supply. They have also a reversal phase : that meens, when used in follower, it's output will go high when intut is lower than 3v...
One can use an old LM324 or LM358, but output is not going up to VCC...
OPA140 is a correct choice.
Also, may be a link capacitor of 100µF between input and potentiometer is necessary : this avoids amplification of DC, gives a centered output, and will reduce noise due to DC paht in potentiometer.

What I read from other posts was that the TL0 series is ok to use with 5V because I'm only trying to amplify a very small audio input.

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


text:
Arduino ESP8266 Ticker interrupted by DallasTemperature/OneWire?
I have been using the Ticker to blink a led successfully.
However, now I am fetching temperature from a DS18B20 in the main loop (which is using the OneWire library) and the blink is now erratic.
Is the Ticker suspended by the DallasTemperature/OneWire library?
It this suspending interrupts or something?
Maybe using the same interrupt?

Ticker does not interrupt your code. It is a OS-timer and will call your function once the time is elapsed.
The Tiker callback can be interrupted by a "real" interrupt or another Task with higher priority and does not provide any reliability - it will just be called.
A solution (not the best) would be to disable manually all interrupts, if you can't solve it in another way.
If you just want a blinking led, you should use a Timer interrupt as your callback is short and fast. Maybe with the ICACHE_RAM_ATTR attribute.

OS-timer means it's get called after the loop() or during a yield() is that correct?

@HixField sorry, I didn't wrote it correctly. It is called during the loop. It will "interrupt" the loop, but not another interrupt and not an important operation (like an access to the SPIFFS). It will for example executed once the SPIFFS-transaction is over or once the SPI/OneWire-interrupt is over. (A HW-Timer can interrupt also a SPIFFS-access).

Hmm ok. It is strange though because I just changed my DS18B20 implementation to a non blocking one (in the loop) and now everything is working fine. I checked the DS18B20 lib and the only thing it does to "block" was a while(...) {} (without any yield). I do have the impression that the ticker can be inrerrupted by blocking functions...

I ran into a problem using libraries with sensor DS18B20 in ticker. If I request the temperature through millis(), then everything is fine. When I request the temperature in the ticker, I get "Panic core_esp8266_main.cpp:137 __yield". Unfortunately I can't explain it.

This doesn't really provide an answer to the question. To ask another question, just click Ask Question above. If you wish, include a link to this question to help provide context.

You're right: this is not an answer, just more information. I made a mistake: I posted this text in the wrong place. Should have been in the comments.


text:
Piezo buzzer with PWM on arduino uno with atmega328p in C on registers + analogRead on registers
I have a little project at the university where I have to use the timers to generate a pwm signal and get it into a piezo buzzer when something else turns over a certain value by using the registers, the thing is that we have worked on some other microcontrollers so I don't really know the libraries for arduino uno with atmega328p and I would require some help on that. Also I have to use the registers instead of the function analogRead() that is reading from a temperature sensor.
Having the following code that works for my setup:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Digital pins to which you connect the LCD
const int inPin = 0;
const int buzzer=9;// A0 is the sensor
void setup()
{
  pinMode(buzzer,OUTPUT); // DDRA=0b00000001;
  lcd.begin(16,2);
}
void loop()
{
  int value = analogRead(inPin); // read the value from the sensor <= to be written on registers
  lcd.setCursor(0,1);
  float millivolts = (value / 1024.0) * 5;
  float celsius = (millivolts-0.5)*100;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(celsius);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print((celsius * 9)/5 + 32); //turning the celsius into fahrehait
  lcd.print("F");
  delay(1000);
  if(celsius>30.0){tone(buzzer,1000);delay(1000);noTone(buzzer);delay(1000);} //<= on registers
}

Step one: read the ATMega328P datasheet. That has all the information you need.

So is your question; how to convert the above code to use registers instead?

In fact all the mentioned function calls are using the Special Function Registers (SFR) and thus the hardware peripherals of the Arduino in the background to work. But I guess this is an exercise to learn how to configure and use these peripherals yourself. Doing this for the whole code is a rather big task for a single question on this site. So I will give you hints and will point you to the corresponding registers. Then the datasheet of the Atmega328P (the microcontroller on the Arduino Uno) is a must read for you. It contains detailed descriptions for almost every function and SFR of the microcontroller.

PWM: I think you want to use PWM for creating a tone from your buzzer. This is not the classical PWM use case (as you don't need to change the duty cycle but the frequency to get different tones). Nonetheless you reach it with the same hardware. For hardware PWM you need to configure a Timer. The Uno has 3 Timers, where Timer0 is already configured by the Arduino IDE for functions like delay(), millis() and such. So I suggest you use Timer1. It has 3 control registers called TCCR1A to TCCR1C. You want the timer to be in CTC Mode (Clear Timer on Compare Match)(Waveform Generation Mode Bits set to 4, CTC mode for OCR1A). The timer will count up with the set frequency (will describe this later) until it gets to the value, that you wrote into the OCR1A register (Compare Match). Then it will reset. If you have set the COM1Ax bits in the TCCR1A register to the correct values, you can set it up to toggle the OC1A pin on a Compare Match).
So in this mode, the timer will reset at a counter value that you set and will toggle the OC1A output pin for you. Thus it generates a square wave with variable frequency, that you can control by writing different values to the OCR1A register.
But we also need to configure the frequency with which the timer will count up. This is done by the clock selection bits CS10 to CS12 in the TCCR1B register. A value of 0 for all bits means the timer is stopped. Look at the corresponding table in the Timer1 register descriptions in the datasheet. You want to connect the timer to the internal system clock. With these bits you can set the prescaler. This determines how many clock pulses it needs to let the timer count 1 up. With no prescaler the timer will count at every clock pulse. With the bit values 0 1 1 you will get a prescaler of 64, so the timer will count up 1 every 64 clock pulses. This sets the frequency range, that you have with the counter. The internal system clock runs at 16MHz on the Uno (you can do the math with the prescaler to calculate for the wanted frequency).
analogRead aka ADC: For reading an analog voltage the ADC (Analog Digital Converter) is used. It has the SFRs ADMUX, ADCSRA, the convertion result registers ADCL and ADCH, and ADCSRB. First we want to set the reference voltage for our conversion. When we set the REFS1 and REFS0 bits in the ADMUX register to 01 we use Vcc as voltage reference, which is sufficient most of the time. The bits MUX3 to MUX0 in the same register select one of the ADC pins for AD Conversion (We have only 1 ADC in the Atmega328P, but we can connect it to multiple ADC pins one after another). Now on the ADCSRA register: The ADEN bit will enable the ADC, with ADSC we can start a conversion. With the bits ADPS2 to ADPS0 we can select a clock prescaler for the ADC. This determines how fast the ADC runs. For maximum resolution you should keep the frequency between 50 and 200kHz.
You can start a conversion by writing 1 to the ADSC. Then you can poll the ADIF bit in the same register. It will be set to 1, when the ADC has completed the conversion. Then you can read the conversion result from the ADCL and ADCH registers (for the Low byte and the High byte of the 10bit result). You should reset the ADIF bit after that by writing a 1 to it.
LCD: I don't know, if you also need to replace the LiquidCrystal library by your own code, since it does not use special peripherals (just digital pins). Digital pins are controlled via the DDRx, PORTx and PINx registers. Google "arduino port manipulation" for more information. And then you can resemble the functions from the library with it.


text:
Read battery voltage from battery which is powering arduino
I have a 5V arduino pro micro. I want to power it with a 3.7V lipo.

Should I use a step up module to convert it to 5V?

I also want to measure the voltage of the battery.

How can I do this?

Because I read that the power source also the reference voltage is so I cant measure it with an analog pin right?
I also use a lipo charging module to charge the battery.
Thanks for helping!

You can read the Arduino's supply voltage see here How to measure the supply voltage of Arduino without using an analog pin Alternatively use the internal 1.1V reference and a suitable voltage divider to read the lipo's voltage

I was just thinking if I use a step up module wouldn't the supply voltage be alwast 5V so I could use a analog pin without problems?

Yes, if the output of said module is always 5V, best would be to use one of those charger boards with over-current and over-discharge protection. Or use a reference design.

Do you recommand a specific charger?

Because I don't know any, I've never seen or used them.

You could use https://arduino.stackexchange.com/a/50771/521 trick to calibrate the supply voltage, then measure the LIPO voltage on an analog pin and scale it appropriately.

Yes, you should use a boost converter to convert the 3.7V from your battery to the 5V that the Arduino requires.
As I understand it, measuring voltage to determine charge level does not work well with lithium chemistry batteries since they hold a nearly constant voltage until they are almost completely depleted. Generally lithium batteries include a chip that measures current in and out and lets you query their charge level.

I don't think my battery has it. I bought this battery https://www.banggood.com/nl/Mobius-2-Camera-3_7V-820mAh-1S-LiPo-Battery-p-1105886.html?rmmds=myorder&cur_warehouse=CN and this charging module https://www.banggood.com/nl/TP4056-1A-Lipo-Battery-Charging-Board-Charger-Module-Mini-USB-Interface-p-1027027.html?rmmds=myorder&cur_warehouse=CN. I was thinking to buy this converter https://banggood.com/DC-DC-Step-Up-Step-Down-Module-2_5V-15V-To-3_3V-5V-Output-For-RC-Drone-FPV-Racing-Multi-Rotor-p-1303385.html?rmmds=wishlist

Yeah, you need a smart charging module then, as Paul says in a comment on the other answer.

What do you mean?

I mean that you should not use a dumb charger to charge a lipo battery. You need an intelligent charge controller.

I'm sorry but what has the charger to do with reading the lipo's voltage with the arduino?

What do you hope to accomplish by reading the battery voltage? It won't change until the battery is dead.

I will connect a screen where I want to display the battery level so I can seen when I need to recharge it. I thought I could do this by comparing the battery voltage to its minimal (3.7V) and it's maximal (4.3V).

That's the problem. It's my understanding that lithium chemistry batteries maintain a nearly constant voltage until they are almost completely exhausted, so measuring the voltage is not useful for gauging charge level.

On this website the show the percentage of capacity in function of the voltage read from the lipo so it should be possible? https://www.google.com/amp/s/blog.ampow.com/lipo-voltage-chart/


text:
i can't work toggle for my small project

i build my small project from a few component as this photo
after finish code and project . i work run for Proteus and then the project not run perfectly because my code need toggle for data entered . i cant work toggle for data .i want help .please
this my code arduino
#define CLK 10
#define CLKI 9
#define LD 8
#define SO 11
#define SER 12

byte ledstates;
byte copy=0;
int rec=0;
unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void setup(){
Serial.begin(9600);
pinMode(CLK,OUTPUT);
pinMode(CLKI,OUTPUT);
pinMode(LD,OUTPUT);
pinMode(SO,INPUT);
pinMode(SER,OUTPUT);
}

void loop(){
if (Serial.available()>0){
message();
}
if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
ledstates &= ~bt_leds_activated;
shift_out(ledstates);
bt_leds_activated = 0;
}
shift_In();
shift_out(ledstates);
}

void message(){
if(Serial.available()){      // Send data only when you receive data:
char data = Serial.read();        //Read   the incoming data & store into data
Serial.print(data);          //Print Value inside data in Serial monitor

switch (data){
  case 'A' :
    bt_leds_activated |= 1;
    break;
  case 'B' :
    bt_leds_activated |= 2;
    break;
  case 'C' :
    bt_leds_activated |= 4;
    break;
  case 'D' :
    bt_leds_activated |= 8;
    break;
  case 'E' :
    bt_leds_activated |= 16;
    break;
  case 'F' :
    bt_leds_activated |= 32 ;
    break;
  case 'G' :
    bt_leds_activated |= 64;
    break;
  case 'H' :
    bt_leds_activated |= 128;
    break;
  default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();

  }

  void shift_out (byte copy){
  digitalWrite(LD, LOW);
  shiftOut(SER,CLK,MSBFIRST,copy);
  digitalWrite(LD, HIGH);
  delay(100);
  }

  void shift_In(){
  digitalWrite(CLKI,HIGH);
  digitalWrite(LD,HIGH);
  digitalWrite(LD,LOW);
  digitalWrite(LD,HIGH);
  digitalWrite(CLK,HIGH);
  digitalWrite(CLKI,LOW);
  byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
  digitalWrite(CLKI,HIGH);
  for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
    if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
        ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
    }
  }
  copy = buttonstates;
  delay(10); // delay for debouncing
   }

what does toggle mean?

For ex when run this code and then press first button the led not save state high . But the led state high and then low quickly . I want save state led when press click

@jsotola did you understand me

i understand that you are using a shift register for input and a shift register for an output .... you expect to read the state of a switch and affect the state of a corresponding LED .... you want to be able to press a switch, have an LED light up, and release the switch and have the LED stay lit

@jsotola Yes, it is true that you started to understand what I want. Don't forget to that I used Bluetooth as you see in the picture to do the same button work

you need to realize that reading the state of a switch and receiving data over bluetooth is totally separate from lighting the LED ... you are trying to combine the input and output functions into one and it does not work because the light follows the state of the switch .... you need to separate the switch/bluetooth and the LED lighting into two separate functions with a message going between .... continued

think of two rooms ... in first room, a person answers the phone and also checks the position of 8 levers ... there is also a tray with 8 compartments ... the person looks at each lever, and if it is raised, then he/she puts a black marble into the corresponding compartment in the tray ... the person also checks for messages on the phone ... the messages are a single letter ... he/she puts a black marble into one of the compartments in the tray depending on the message ... then the person passes the tray to the other room ....

the person in the other room looks at each compartment in the tray and turns on one of 8 lights if the compartment contains marbles

the first room could be 20 rooms, each one adding marbles to the tray

now, to expand the scenario ... the person that watches the levers could be instructed to empty the compartment in the tray if the lever is down ... that would make the light follow the position of the lever ... or the person could be instructed to watch the levers and act only when the lever moves ... put marble into compartment if it is empty and remove marble from compartment if it contains one ..... i think that this last scenario is what you want

Currently you are shifting in the button states and directly shifting them out again to the LEDs. Thus the state of the LEDs follows exactly the state of the buttons.
As jsotola explained in the comments, you need to seperate what you get as input (buttons and serial) from what you set as output. For this you need 1 or more variables to hold the state of the LEDs (your output) and the state of each input (for example each button). The last is what you have in the copy variable. It resembles the state of the buttons input. Now create a new variable byte ledstates;. The shift_out() function has to be called with this variable instead of with copy.
Now that input and output are seperated, you can look at the desired behavior for the input. As 1 button press (pressing and releasing) should toggle the state of the corresponding LED, you have to look for a LOW-to-HIGH transition. A common way is to save the current state of the buttons in a variable. Then, in the next execution of shift_in() you can check, if the previous state (as saved in the variable) and the new measured state do a LOW-to-HIGH transition (previously LOW, now HIGH). This is a button press, that you can use to toggle the corresponding LED bit in the newly created ledstates variable. Save the new measured state in the copy variable. (Btw: You should rename the copy variable to something more describing)
Also you need to consider a mechanism, that you haven't had to bother with the previous code: Button bouncing. A mechanical switch or button will not make one single clean transition, when being pressed. The mechanical contact will bounce a bit, resulting in very fast HIGH-LOW transitions, until the button is settled. If you don't consider that in your program, you will get many transitions and thus toggling the LED many times with only one button press. There are many ways to tackle this (and all of them can be easily googled). I would go with the "don't sense any further transitions after the first for a fixed time" way. This can be done by a simple delay() call at the end of your shift_in() function (not so elegant with some caveats) or by using millis() to create a non-blocking timeout (in the best case for each button individually) (Look at the BlinkWithoutDelay example, that comes with the Arduino IDE. It is worth learning this principle).
So you have something like this (not the full code, just some hints):
byte copy;
byte ledstates;

void loop(){
    if (Serial.available()>0){
        message();
    }
    shift_In();
    shift_out(ledstates);
}

void shift_in(){
    digitalWrite(CLKI,HIGH);
    digitalWrite(LD,HIGH);
    digitalWrite(LD,LOW);
    digitalWrite(LD,HIGH);
    digitalWrite(CLK,HIGH);
    digitalWrite(CLKI,LOW);
    byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
    digitalWrite(CLKI,HIGH);
    for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
        if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
            ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
        }
    }
    copy = buttonstates;
    delay(10); // delay for debouncing
}

As mentioned above we have seperated input and output. Now it is easy to also implement a fitting bluetooth control. You want the corresponding light go on on serial input (through bluetooth) and go out after a specific time automatically. For such a thing using millis() with a timestamp is the best option. First we take the message() function. We define 2 variables at the global scope (outside of any function at the start of the program) to hold the timestamp of our last serial communication and a byte to hold the LEDs, that where activated via serial. In the message() function we now set the corresponding bit in this last variable. If the serial data was not valid, we simply return from the function (this makes the code shorter). At the end of the function we ensure, that every LED that was set in our variable gets also set in our ledstates variable, which then will be shifted out. And lastly we save a timestamp with the millis() function, which returns the number of milliseconds since the startup.
unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void message(){
  if(Serial.available()){      // Send data                   only when you receive data:
    char data = Serial.read();        //Read   the incoming data & store into data
    Serial.print(data);          //Print Value inside data in Serial monitor

    switch (data){
      case 'A' :
        bt_leds_activated |= 1;
        break;
      case 'B' :
        bt_leds_activated |= 2;
        break;
      case 'C' :
        bt_leds_activated |= 4;
        break;
      case 'D' :
        bt_leds_activated |= 8;
        break;
      case 'E' :
        bt_leds_activated |= 16;
        break;
      case 'F' :
        bt_leds_activated |= 32 ;
        break;
      case 'G' :
        bt_leds_activated |= 64;
        break;
      case 'H' :
        bt_leds_activated |= 128;
        break;
      default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();
}

Now the corresponding LEDs get turned on, but not off. So we need to put the following code in the main loop() function:
if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
  ledstates &= ~bt_leds_activated;
  shift_out(ledstates);
  bt_leds_activated = 0;
}

This code checks, if any LED was activated via bluetooth (the first part of the if condition evaluates to true, if bt_leds_activated is different than zero) and if a certain time (here 2s aka 2000ms) has passed since the timestamp was taken. When the time has come, then the LED bits from bt_leds_activated, which we set earlierare cleared inledstatesto turn the LEDs off. Then this is shifted out to set the actual state of the LEDs for us to see. Finally we resetbt_leds_activated` to zero, since we don't have any more LEDs to turn of automatically, until new data arrives.
This has 1 caveat: When you send new data over bluetooth within these 2s, the timeout for the LEDs previously activated via bluetooth will also be resetted, so that they will light longer. The way around that is to use 1 timestamp for each LED, but I thought this as to complicated for now. Don't want this, you can implement that part yourself just like I did with all of them together.
Note: I haven't tested this code in any way.

Comments are not for extended discussion; this conversation has been moved to chat.

firstly : now done edit my code in this question in the top page . after run the new code by Bluetooth when send A the LEDs get turned on, but not off. after send A what is the mean (main loop())?? i but in (if condition) in the [void loop () ]as in top code in this if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){ ledstates &= bt_leds_activated; shift_out(ledstates); bt_leds_activated = 0; }

Please use the chat for further communication. All the comments clutter up the comment space

@chrisl when use millis() function im main loop the leds turn on just 2 sec and then turn off not perfect ansewr

@KhalidAbu-Khadija What are you talking about? I don't understand. Please rephrase your comment


text:
NeoMatrix Button Troubles
I am creating a 20x15 LED Matrix using and Arduino Nano. My goal is to switch between different "scenes," if you will, using 4 buttons (I just need to run different code to make it display something different). The four buttons share a ground, and they go into digital pins (I don't have resistors on the ground because of this article). Then in the code (under void loop) there is one big if-then tree. For example,  if (button1State == HIGH) {} else {if (button2State == HIGH)} and so on and so forth.
When I connect the buttons, the lights flicker and glitch. Without the buttons, it goes to the last else completely fine, so I know my light code works. To me, the code looks fine, but I want to see if there is something that I am doing wrong. I wonder if putting the code in voids instead of them in the if-thens in the loop would be better, but I don't know how I would invoke them.
If anyone could figure out what I am doing wrong or something that could make my code better, I would be super grateful.
Here is my full, current code (ignore all of the comments, I am designing the code so someone with no coding knowledge could understand it)
//   HEY! LOOK UP HERE! I know it looks confusing, but don't worry, I'll help you! I'm Clippy!
//    _________________
//   < I can help you! >
//    -----------------
//    \
//     \
//        __
//       /  \
//       |  |
//       @  @
//       |  |
//       || |/
//       || ||
//       |\_/|
//       \___/

//As you know, there are 4 buttons. When they are pressed, they display something different. We can make them display text as well.
//Below are VARIABLES, which control what text is displayed when buttons are pressed. Put what you want them to display between the
//quotation marks. If you don't want anything in a button, just put a space inbetween them.

//Note: only button 1 and 3 can display text, so lets only put text in those :)
String buttonText1 = " "; //Again, put what you want button 1 to display in text
//String buttonText2 = " ";
String buttonText3 = " ";
//String buttonText4 = " ";
String defaultText = "   Text for the panel"; //This is what will show up when you first start it up

//Here we can adjust what the brightness of the panel is. We use a switch to do this. You can use values from 0 (lowest) to 255 (highest)
int switchLevel1 = 10;
int switchLevel2 = 200;

//Here we can control how many colors are on the backgrounds at one time. We can customize this to get some variety in our displays.
int colorsOnscreen1 = 5; //For button 1
//int colorsOnscreen2 = 3
int colorsOnscreen3 = 10; //For button 3
//int colorsOnscreen4 = 5;
int colorsOnscreenDefault = 3; //For when you start it up

int lastButton = 0; //Last button pressed stuff, gets fed to buttons

//----------------------------------------------------------------You Probably Don't Have To Worry About The Rest----------------------------------------------------------------

//This stuff you don't have to worry about, its for the board
#include <Adafruit_NeoPixel.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SPITFT.h>
#include <Adafruit_SPITFT_Macros.h>
#include <gfxfont.h>
#include <Adafruit_NeoMatrix.h>
#include <gamma.h>
#include "RGB.h"
#ifndef PSTR
 #define PSTR
#include smileytongue24.h
#include yellowsmiley24.h
#endif

#define PIN 3 // This is the pin where the data is coming out (you don't have to worry about this)

const int button1 = 4;     // the number of the arcade button pins
const int button2 = 5;
const int button3 = 6;
const int button4 = 7;
const int brightnessSwitch = 8;

// variables will change:
int button1State = 0;         // variable for reading the pushbutton status
int button2State = 0;
int button3State = 0;
int button4State = 0;
int switchState = 0;
int panelBrightness = 0;

//This stuff tells the board how the lights are arranged. In our case, it starts at the top left, and
//the signal goes right, and zigzags the rest of the way. It also tells it that it is 20 by 15 LEDs
Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(20, 15, PIN,
  NEO_MATRIX_TOP     + NEO_MATRIX_RIGHT +
  NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
  NEO_GRB            + NEO_KHZ800);

void setup() {
  // initialize the buttons as inputs:
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);
  pinMode(brightnessSwitch, INPUT);
  matrix.begin();
  matrix.setTextWrap(false);
  Serial.begin(9600);
  Serial.print("The LED Matrix has started. Default will be activated soon");
}

String panelText = buttonText1; //This is what text gets fed to the panel

int x    = matrix.width();
int pass = 0;

void loop() {
  matrix.setBrightness(panelBrightness); //This sets the overall brightness. 255 is the highest, while 0 is the lowest
  // read the state of the button:
  button1State = digitalRead(button1);
  button2State = digitalRead(button2);
  button3State = digitalRead(button4);
  button4State = digitalRead(button4);
  switchState = digitalRead(brightnessSwitch);
  if (switchState == HIGH){panelBrightness = switchLevel1;} else {panelBrightness = switchLevel2;} //Brightness Logic

  // if-then statements
  if (button1State == HIGH){ //BUTTON 1 CODE START
      static int i = 0;
  i++;
  for(int y = 0; y < 15; y++)
    for(int x = 0; x < 20; x++)
      if(y & 1)
        matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreen1 + i * 128 * 2)));
      else
        matrix.setPixelColor(x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreen1 + i * 128 * 2)));

  matrix.setTextColor(matrix.Color(255, 255, 255)); //This determines the text color. If you want to set a text color, search in google "Color Picker" and use the RGB values in place of the numbers in (a,a,a)
  matrix.setCursor(-((millis() / 40) & 127), 4);
  matrix.print(buttonText1);
  matrix.show();
}
//BUTTON 1 CODE END
   else {
      if (button2State == HIGH){ //BUTTON 2 CODE START
          //PUT WHAT HAPPENS FOR BUTTON 2 HERE
          //BUTTON 2 CODE END
      } else {
          if (button3State == HIGH){ //BUTTON CODE 3 START
                    static int i = 0;
  i++;
  for(int y = 0; y < 15; y++)
    for(int x = 0; x < 20; x++)
      if(y & 1)
        matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x - y) * 200 * colorsOnscreen3 + i * 128 * 2)));
      else
        matrix.setPixelColor(x + y * 20, matrix.gamma32(matrix.ColorHSV((x - y) * 256 * colorsOnscreen3 + i * 128 * 2)));

  matrix.setTextColor(matrix.Color(255, 255, 255)); //This determines the text color. If you want to set a text color, search in google "Color Picker" and use the RGB values in place of the numbers in (a,b,c)
  matrix.setCursor(-((millis() / 40) & 127), 4);
  matrix.print(buttonText3);
  matrix.show();
}
              //BUTTON 3 CODE END
           else {
              if (button4State == HIGH){ //BUTTON 4 CODE START
                  //PUT WHAT HAPPENS FOR BUTTON 4 HERE
                  //BUTTON 4 CODE END
              } else {
                  //WHAT HAPPENS UNTIL A BUTTON IS PRESSED

   static int i = 0;
  i++;
  //matrix.fillScreen(0);
  for(int y = 0; y < 15; y++)
    for(int x = 0; x < 20; x++)
      if(y & 1)
        matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreenDefault + i * 128 * 2)));
      else
        matrix.setPixelColor(x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreenDefault + i * 128 * 2)));

  matrix.setTextColor(matrix.Color(255, 255, 255)); //This determines the text color. If you want to set a text color, search in google "Color Picker" and use the RGB values in place of the numbers in (a,b,c)
  matrix.setCursor(-((millis() / 70) & 127), 4);
  matrix.println(defaultText);
  matrix.show();

}}}}

    }

Again, Thank You
-Micah

Do you have just the IO pin -> wire -> button -> wire -> ground? Nothing else connected to the button or IO pin?

@Majenko Yup. I'm going to change it, but that is what I was doing. If it makes a difference, I also had all the grounds of the buttons tied together to one ground because my only other ground is being used to provide a ground consistent with the power supply for the data out.

I think your main problem is how you read the buttons.

You simply connected the buttons with ground and the corresponding digital input pin on the Arduino without any extra components, just like the linked forum entry states. But you missed a very important part: The pullup resistor. When your button is pressed, the Arduinos pin will be pulled to ground. But if it is not pressed, there is nothing connected to the pin. Such a pin is called floating, as it does not have a fixed reference value. It will pick up whatever noise is floating around at it's location (often the state of other electronic parts or pins near it). It will change it's state erratically. You need to pull the pin to Vcc (5V in case of the Nano), so that the pin has a clear fixed state, when the button is not pressed. This can be done by either an external or the internal pullup resistor of the Atmega328P (the chip on the Nano). In the forum post the internal pullup is activated by doing a digitalWrite(pin, HIGH); after setting the pin to INPUT. But I think it is more speaking code to just use pinMode(pin, INPUT_PULLUP); which will do the same in one single step.
In your code you check for the button pins to be HIGH, as if a button press would make the pin HIGH. But this is not the case, if you connect the button to ground. If pressed, the button will pull the pin to GROUND, thus a value of LOW. You need to check for the buttons to get LOW.

Thank you for your fast and insightful response. Just to make sure I am interpreting your comment correctly, you are saying that if I use the internal pull up on the chip (using pinMode(pin, INPUT_PULLUP); , then I do not need to use an external pull up resistor because my button with already be not floating? Just trying to make sure I am interpreting this right. Again, thank you for the helpful response!

Yes, correct. You don't need an external pullup resistor, when you are activating the internal one. If nothing is connected to the pin, it will have the state HIGH, since the internal pullup will pull it to Vcc. When the button is pressed, the pin is connected to ground, thus has a state of LOW. A very little current will flow through the internal pullup resistor.

You should always comment your code, so that you will know what your code does when you look at it 6 months from now.
For beginners, you should not leave out the braces {} from any part of the code as you did in the for loops.
Here is your code correctly formatted, followed by a more cleaned up version which may be easier for beginner to follow.
Main question is whether the for loops are written as you intended.
Also, the use of if {} else { if {}} makes the code listing somewhat convoluted.
The second listing shows the if {} else if {} version.
//   HEY! LOOK UP HERE! I know it looks confusing, but don't worry, I'll help you! I'm Clippy!
//    _________________
//   < I can help you! >
//    -----------------
//    \
//     \
//        __
//       /  \
//       |  |
//       @  @
//       |  |
//       || |/
//       || ||
//       |\_/|
//       \___/

// As you know, there are 4 buttons. When they are pressed, they display something different. We can make them display text as well.
// Below are VARIABLES, which control what text is displayed when buttons are pressed. Put what you want them to display between the
// quotation marks. If you don't want anything in a button, just put a space inbetween them.

//Note: only button 1 and 3 can display text, so lets only put text in those :)
String buttonText1 = " "; //Again, put what you want button 1 to display in text
//String buttonText2 = " ";
String buttonText3 = " ";
//String buttonText4 = " ";
String defaultText = "   Text for the panel"; //This is what will show up when you first start it up

//Here we can adjust what the brightness of the panel is. We use a switch to do this. You can use values from 0 (lowest) to 255 (highest)
int switchLevel1 =  10;
int switchLevel2 = 200;

//Here we can control how many colors are on the backgrounds at one time. We can customize this to get some variety in our displays.
int colorsOnscreen1 = 5;           // For button 1
//int colorsOnscreen2 = 3
int colorsOnscreen3 = 10;          // For button 3
//int colorsOnscreen4 = 5;
int colorsOnscreenDefault = 3;     // For when you start it up

int lastButton = 0;                // Last button pressed stuff, gets fed to buttons

//----------------------------------------------------------------You Probably Don't Have To Worry About The Rest----------------------------------------------------------------

//This stuff you don't have to worry about, its for the board
#include <Adafruit_NeoPixel.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SPITFT.h>
#include <Adafruit_SPITFT_Macros.h>
#include <gfxfont.h>
#include <Adafruit_NeoMatrix.h>
#include <gamma.h>
#include "RGB.h"
#ifndef PSTR
 #define PSTR
#include smileytongue24.h
#include yellowsmiley24.h
#endif

#define PIN 3 // This is the pin where the data is coming out (you don't have to worry about this)

const int button1          = 4;     // the number of the arcade button pins
const int button2          = 5;
const int button3          = 6;
const int button4          = 7;
const int brightnessSwitch = 8;

// variables will change:
int button1State           = 0;     // variable for reading the pushbutton status
int button2State           = 0;
int button3State           = 0;
int button4State           = 0;
int switchState            = 0;
int panelBrightness        = 0;

                                                                        // This stuff tells the board how the lights are arranged.
Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(20,                      // In our case, it starts at the top left,
                                               15,                      //   and the signal goes right, and zigzags the rest of the way.
                                               PIN,                     // It also tells it that it is 20 by 15 LEDs
                                               NEO_MATRIX_TOP + NEO_MATRIX_RIGHT + NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
                                               NEO_GRB + NEO_KHZ800);

void setup() {
  pinMode(button1, INPUT);                                              // initialize the buttons as inputs:
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);

  pinMode(brightnessSwitch, INPUT);

  matrix.begin();
  matrix.setTextWrap(false);

  Serial.begin(9600);
  Serial.print("The LED Matrix has started. Default will be activated soon");
}

String panelText = buttonText1;                                         // This is what text gets fed to the panel

int x    = matrix.width();
int pass = 0;

void loop() {
  matrix.setBrightness(panelBrightness);                                // This sets the overall brightness. 255 is the highest, while 0 is the lowest

  button1State = digitalRead(button1);                                  // read the state of the buttons
  button2State = digitalRead(button2);
  button3State = digitalRead(button4);
  button4State = digitalRead(button4);

  switchState = digitalRead(brightnessSwitch);

  if (switchState == HIGH) { panelBrightness = switchLevel1; }          // Brightness Logic
  else                     { panelBrightness = switchLevel2; }

  // if-then statements
  if (button1State == HIGH) {                                           // BUTTON 1 CODE START
    static int i = 0;
    i++;
    for(int y = 0; y < 15; y++)
      for(int x = 0; x < 20; x++)
        if(y & 1)
          matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreen1 + i * 128 * 2)));
        else
          matrix.setPixelColor(     x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreen1 + i * 128 * 2)));

    matrix.setTextColor(matrix.Color(255, 255, 255));                   // This determines the text color.
    matrix.setCursor(-((millis() / 40) & 127), 4);                      //     If you want to set a text color, search in google "Color Picker"
                                                                        //     and use the RGB values in place of the numbers in (a,a,a)
    matrix.print(buttonText1);
    matrix.show();
  }                                                                     // BUTTON 1 CODE END

  else {
    if (button2State == HIGH) {                                         // BUTTON 2 CODE START
                                                                        //    PUT WHAT HAPPENS FOR BUTTON 2 HERE
    }                                                                   // BUTTON 2 CODE END
    else {
      if (button3State == HIGH) {                                       // BUTTON CODE 3 START
        static int i = 0;
        i++;
        for(int y = 0; y < 15; y++)
          for(int x = 0; x < 20; x++)
            if(y & 1)
              matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x - y) * 200 * colorsOnscreen3 + i * 128 * 2)));
            else
              matrix.setPixelColor(     x + y * 20, matrix.gamma32(matrix.ColorHSV((x - y) * 256 * colorsOnscreen3 + i * 128 * 2)));

        matrix.setTextColor(matrix.Color(255, 255, 255));
        matrix.setCursor(-((millis() / 40) & 127), 4);

        matrix.print(buttonText3);
        matrix.show();
      }                                                                 // BUTTON 3 CODE END
      else {
        if (button4State == HIGH){                                      // BUTTON 4 CODE START
                                                                        //    PUT WHAT HAPPENS FOR BUTTON 4 HERE
        }                                                               // BUTTON 4 CODE END
        else {                                                          // WHAT HAPPENS UNTIL A BUTTON IS PRESSED

          static int i = 0;
          i++;
//        matrix.fillScreen(0);
          for(int y = 0; y < 15; y++)
            for(int x = 0; x < 20; x++)
              if(y & 1)
                matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreenDefault + i * 128 * 2)));
              else
                matrix.setPixelColor(     x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreenDefault + i * 128 * 2)));

          matrix.setTextColor(matrix.Color(255, 255, 255));
          matrix.setCursor(-((millis() / 70) & 127), 4);

          matrix.println(defaultText);
          matrix.show();
        }
      }
    }
  }
}

    //   HEY! LOOK UP HERE! I know it looks confusing, but don't worry, I'll help you! I'm Clippy!
    //    _________________
    //   < I can help you! >
    //    -----------------
    //    \
    //     \
    //        __
    //       /  \
    //       |  |
    //       @  @
    //       |  |
    //       || |/
    //       || ||
    //       |\_/|
    //       \___/

    // As you know, there are 4 buttons. When they are pressed, they display something different. We can make them display text as well.
    // Below are VARIABLES, which control what text is displayed when buttons are pressed. Put what you want them to display between the
    // quotation marks. If you don't want anything in a button, just put a space inbetween them.

                                                  // Note: only button 1 and 3 can display text, so lets only put text in those :)
    String buttonText1 = " ";                     // Again, put what you want button 1 to display in text
//  String buttonText2 = " ";
    String buttonText3 = " ";
//  String buttonText4 = " ";

    String defaultText = "   Text for the panel"; // This is what will show up when you first start it up

    int switchLevel1 =  10;                       // Here we can adjust what the brightness of the panel is.
    int switchLevel2 = 200;                       // We use a switch to do this. You can use values from 0 (lowest) to 255 (highest)

                                                  // Here we can control how many colors are on the backgrounds at one time.
                                                  // We can customize this to get some variety in our displays.
    int colorsOnscreen1 =  5;                     // For button 1
//  int colorsOnscreen2 =  3;
    int colorsOnscreen3 = 10;                     // For button 3
//  int colorsOnscreen4 =  5;

    int colorsOnscreenDefault = 3;                // For when you start it up

    int lastButton = 0;                           // Last button pressed stuff, gets fed to buttons

    //----------------------------------------------------------------You Probably Don't Have To Worry About The Rest----------------------------------------------------------------

    //This stuff you don't have to worry about, its for the board

    #include <Adafruit_NeoPixel.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SPITFT.h>
    #include <Adafruit_SPITFT_Macros.h>
    #include <gfxfont.h>
    #include <Adafruit_NeoMatrix.h>
    #include <gamma.h>
    #include "RGB.h"
    #ifndef PSTR
      #define PSTR
      #include smileytongue24.h
      #include yellowsmiley24.h
    #endif

    #define PIN 3 // This is the pin where the data is coming out (you don't have to worry about this)

    const int button1          = 4;     // the number of the arcade button pins
    const int button2          = 5;
    const int button3          = 6;
    const int button4          = 7;
    const int brightnessSwitch = 8;

    // variables will change:
    int button1State           = 0;     // variable for reading the pushbutton status
    int button2State           = 0;
    int button3State           = 0;
    int button4State           = 0;
    int switchState            = 0;
    int panelBrightness        = 0;

                                                                        // This stuff tells the board how the lights are arranged.
    Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(20,                  // In our case, it starts at the top left,
                                                   15,                  //   and the signal goes right, and zigzags the rest of the way.
                                                   PIN,                 // It also tells it that it is 20 by 15 LEDs
                                                   NEO_MATRIX_TOP + NEO_MATRIX_RIGHT + NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
                                                   NEO_GRB + NEO_KHZ800);

    void setup() {
      pinMode(button1, INPUT);                                          // initialize the buttons as inputs:
      pinMode(button2, INPUT);
      pinMode(button3, INPUT);
      pinMode(button4, INPUT);

      pinMode(brightnessSwitch, INPUT);

      matrix.begin();
      matrix.setTextWrap(false);

      Serial.begin(9600);
      Serial.print("The LED Matrix has started. Default will be activated soon");
    }

    String panelText = buttonText1;                                     // This is what text gets fed to the panel

    int x    = matrix.width();
    int pass = 0;

    void loop() {
      matrix.setBrightness(panelBrightness);                            // This sets the overall brightness. 255 is the highest, while 0 is the lowest

      button1State = digitalRead(button1);                              // read the state of the buttons
      button2State = digitalRead(button2);
      button3State = digitalRead(button4);
      button4State = digitalRead(button4);

      switchState = digitalRead(brightnessSwitch);

      if (switchState == HIGH) { panelBrightness = switchLevel1; }      // Brightness Logic
      else                     { panelBrightness = switchLevel2; }

      // if-then statements
      if (button1State == HIGH) {                                       // BUTTON 1 CODE START

        static int i = 0;
        i++;
        for (int y = 0; y < 15; y++) {
          for (int x = 0; x < 20; x++) {
            if (y & 1) {
              matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreen1 + i * 128 * 2)));
            }
            else {
              matrix.setPixelColor(     x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreen1 + i * 128 * 2)));
            }
          }
        }

        matrix.setTextColor(matrix.Color(255, 255, 255));               // This determines the text color.
        matrix.setCursor(-((millis() / 40) & 127), 4);                  //     If you want to set a text color, search in google "Color Picker"
                                                                        //     and use the RGB values in place of the numbers in matrix.Color(r,g,b)
        matrix.print(buttonText1);
        matrix.show();
      }                                                                 // BUTTON 1 CODE END

      else if (button2State == HIGH) {                                  // BUTTON 2 CODE START
                                                                        //    PUT WHAT HAPPENS FOR BUTTON 2 HERE
      }                                                                 // BUTTON 2 CODE END

      else if (button3State == HIGH) {                                  // BUTTON CODE 3 START

        static int i = 0;
        i++;
        for (int y = 0; y < 15; y++) {
          for (int x = 0; x < 20; x++) {
            if (y & 1) {
              matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x - y) * 200 * colorsOnscreen3 + i * 128 * 2)));
            }
            else {
              matrix.setPixelColor(     x + y * 20, matrix.gamma32(matrix.ColorHSV((x - y) * 256 * colorsOnscreen3 + i * 128 * 2)));
            }
          }
        }

        matrix.setTextColor(matrix.Color(255, 255, 255));
        matrix.setCursor(-((millis() / 40) & 127), 4);

        matrix.print(buttonText3);
        matrix.show();
      }                                                                 // BUTTON 3 CODE END

      else if (button4State == HIGH) {                                  // BUTTON 4 CODE START
                                                                        //    PUT WHAT HAPPENS FOR BUTTON 4 HERE
      }                                                                 // BUTTON 4 CODE END

      else {                                                            // WHAT HAPPENS UNTIL A BUTTON IS PRESSED

        static int i = 0;
        i++;
//      matrix.fillScreen(0);
        for (int y = 0; y < 15; y++) {
          for (int x = 0; x < 20; x++) {
            if (y & 1) {
              matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreenDefault + i * 128 * 2)));
            }
            else {
              matrix.setPixelColor(     x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * colorsOnscreenDefault + i * 128 * 2)));
            }
          }
        }

        matrix.setTextColor(matrix.Color(255, 255, 255));
        matrix.setCursor(-((millis() / 70) & 127), 4);

        matrix.println(defaultText);
        matrix.show();
      }
    }

Thank you for cleaning up my code! You're right, it does make it easier to understand. Again, thanks for your help!


text:
How can an Arduino do multiple actions in parallel without interfering with each other?
I am working with my son (9) and we are having a great time learning. But, we've run into a problem and could use your help.
We have two separate loops that we want to run without interfering with the other. Currently we have two LEDs that are blinking in a sequence that has delays built in to keep them on/off.
We also have a Photocell circuit that turns another LED on/off depending on the light.
The problem is, the photocell circuit is lagging 1/2 second due to the light sequence from the other loop.
How do we fix this?
// this is declans photo cell and led program

const int photoCell    =  0;  // photo cell variable
const int ledLightButt = 11;  // Led light variable assignment

int lightCal;                 // idk what dis iz
int lightVal;                 // this is the reading from photo cell I think

void setup() {
    pinMode(13, OUTPUT);
    pinMode(12, OUTPUT);

    pinMode(ledLightButt, OUTPUT);
    lightCal = analogRead(photoCell);
}

void loop() {

    lightVal = analogRead(photoCell);

    if (lightVal < lightCal - 50) {
        digitalWrite(ledLightButt, HIGH);
    }
    else {
        digitalWrite(ledLightButt, LOW);
    }

    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
    delay(250);

    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
    delay(250);

}

this may help ... https://www.norwegiancreations.com/2017/09/arduino-tutorial-using-millis-instead-of-delay/

tip: format your code properly so that the blocks of code are clearly defined .... i formatted your existing code as an example .... proper formatting is important in if-else bloks and in function blocks

The root of this behavior is that when the program runs delay() function - nothing else could run (digitalwrites, checks, conditions, etc.) until the delay() time is passed.
The effective solution for this is avioding the delay() function, and getting the same results (without the side-effect) using timers (like millis()) or other ways.
Googling "How to avoid delay()" will give you lot of information about how-to do it, one example can be found here:
Arduino Playground - How and Why to avoid delay() function.
Good luck with that, and enjoy your programming experience!

we found some other code that helped us avoid the delay() functions. Now we are able to use the timestamp "Millis" to run our blinking lights AND have another if statement running the photocell & third LED.
Making progress! Thanks for the suggestions! Here is the code and it works great to turn the LED on and off based on the photocell, and have the other LED's flashing on their own.
const int photoCell =0;
const int ledPin = 13;
const int led2Pin = 12;
const int led3Pin = 11;
int lightCal;
int lightVal;
int ledState = LOW;
int led2State = HIGH;
long previousMillis = 0;
long interval = 250;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(led3Pin, OUTPUT);
  lightCal=analogRead(photoCell);
}

void loop() {
unsigned long currentMillis = millis();
lightVal = analogRead(photoCell);

if(currentMillis - previousMillis >= interval)
{
  previousMillis = currentMillis;
  if (ledState == LOW)
  ledState = HIGH;
  else
  ledState = LOW;
  if (ledState == LOW)
  led2State = HIGH;
  else
  led2State = LOW;

  digitalWrite(ledPin, ledState);
  digitalWrite(led2Pin, led2State);
}
if (lightVal < lightCal - 50)
{
  digitalWrite(led3Pin, HIGH);
}
else {
  digitalWrite(led3Pin, LOW);
}
}

I think that timing might be too hard for 9year old, So :
I will give an alternative:
Synchronizing two Arduino's using main or software serial. this can be used to teach Server client (master/slave) architecture where client is set to finish loop quicker and wait for syncing data from server (master) to start next one.
Note that if you are sending numbers over serial to another Arduino use Serial.write() (rather then Serial.print(); it saves you from dealing with asci and char to int (no fun for kid only trouble)
There is a third option of a library which tries to imitate parallel syncing, but that is too much trouble and not a good habit to gain

You can use the library that support blink without delay.
For example, You can refer to this example code:
#include <ezOutput.h> // ezOutput library

ezOutput led1(7);  // create ezOutput object that attach to pin 7;
ezOutput led2(8);  // create ezOutput object that attach to pin 8;
ezOutput led3(9);  // create ezOutput object that attach to pin 9;

void setup() {
  led1.blink(500, 250);       // 500 milliseconds ON, 250 milliseconds OFF. start immediately
  led2.blink(250, 250, 1000); // 250 milliseconds ON, 250 milliseconds OFF. start after 1000 milliseconds
  led2.blink(100, 100, 2000); // 100 milliseconds ON, 100 milliseconds OFF. start after 2000 milliseconds
}

void loop() {
  led1.loop(); // MUST call the led1.loop() function in loop()
  led2.loop(); // MUST call the led2.loop() function in loop()
  led3.loop(); // MUST call the led3.loop() function in loop()

  // DO OTHER WORK HERE

}

The tutorial is available here

There's a rather nice Adafruit tutorial on how to implement this (beyond the one listed already): https://learn.adafruit.com/multi-tasking-the-arduino-part-1
I disagree with the approach given, since it requires that all tasks be polled manually and that you implement it to each task, but the design itself is really clever.
You may also want to check out Makuna's Task library (https://github.com/Makuna/Task), or try my own solution: https://github.com/rdragonrydr/CoRTOS (which is designed to be as efficient and easy-to-use as possible). It's still a work in progress (more optimizations coming soon) but is definitely usable for nearly anything I can think of.


text:
My millis() code doesn't work
I am doing a project with bluetooth and an LED. I wrote a code which supposed to turn on an LED after it receives a byte of value 1 after 5 seconds, unless it receive another byte of value 1 (which make it need to wait another 5 seconds) so that if it receive the byte periodically, the LED doesnt turn on, and only turn on if byte value sending is stopped/bluetooth disconnected. I wrote this code and it doesn't seem to work. It doesn't even turn on the LED after 5 seconds. Can you help me spot the mistake here?
unsigned long timebetween=5000;
unsigned long lastreceivedtime;
int value;
bool timerReady = false;

void setup() {
  pinMode (11,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();
  if( Serial.available() >0){
    value = Serial.read();
  }
  if ( value ==1 ){
    lastreceivedtime = currentMillis;
    timerReady = true;
  }

  if(timerReady) {
    if((unsigned long)(currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
      delay(90);
    }
  }
}

how do you know what value Serial.read() returns?

I don't think anything in your code is going to work.
First,
 you are asking the serial.Read to return an integer if it is working.  You might want to change that to a Boolean.
Second,
You are asking for a 1 and only a 1 to make your next if statement true.  If the serial.Read is working the chance it will only return a one, I think is very low
Third,
On the IF statement for setting timerReady. You will set that at a new number each time the program runs through, with the 90ms delay in the last IF statement, it looks like your timer will reset at about every 95-100ms
Fourth,
I think your last 2 IF statements are wrong, I think you want
if(timerReady==true) {
    if((currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
      delay(90);

If you do get this working you might need to set the Boolean back to false and move pin 11 to low at some point.

Thanks a lot! I modified some of the lines and it worked.

Why is it a problem to save the return value of Serial.read() in an int variable? That is actually the type, that gets returned by this function, so why using a boolean here?

Because the only reason he is looking at the serial.Read is to see if it is there and working, he doesn't really care whats there, just that it is working.  The serial.Read is being used as a light switch, on or off, TRUE or FALSE


text:
6v between vin and pin even though pin is off
I have a arduino uno and i am trying to make a lightstrip work.
i have made a program for this but when i turn off the pins to make the light
strip turn off it still glows.
red the reason is that there is still 6v between vin and the port even though there should be 0v.
here is my code
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
}

void loop() {
}

any way to fix this

Please show us your circuit, so that we can see, how the lightstrip is connected. The problem must lie there

A low output is (almost) the same as ground. Between VIN and GND you will get VIN. Between VIN and an IO pin set to LOW you will get VIN - since LOW and GND are the same.

That would be the correct reading.
If (LOW) 0 is near GND.
All your measurements should be from(against) GND
Never connect any pins into voltage before regulator(V-in) or voltage over 5v (I usualy target 4.6v as MAX voltage to give myself a margin of error) and even that should only be done in the event of input or high (1) mode.
You are lucky if your multi-meter had big enough resistance and did not damage your Arduino yet.
Arduinos pins have no real protection and very little resistance when in output mode.
Even though pro's keep saying that it is pointless I find that when connecting items sensitive to even tiny current using NPN transistor i tend to use pull-down 10K-ish resistor against GND


text:
Question about RGB LEDs
I think many people know about the staircase lights, which will get triggered by 2 PIR-sensors (1x upstairs and 1x downstairs).
Here is my code - which works well.  It's not cleaned up - as i don't know how i can simplify it. I think there'll be a much nicer way of getting the same output. :)
#include "FastLED.h"
#define NUM_LEDS 300
CRGB leds[NUM_LEDS];
#define PIN 3
int sensorUP = 5;
int sensorDOWN = 7;
int state = LOW;
int valUP = 0;
int valDOWN = 0;

void setup()
{
  FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(20);
  pinMode(2, INPUT_PULLUP); // internal pull-up resistor
  pinMode(sensorUP, INPUT);
  pinMode(sensorDOWN, INPUT);
  Serial.begin(9600);
}

void loop() {
  valUP = digitalRead(sensorUP);
  valDOWN = digitalRead(sensorDOWN);

  if (valUP == HIGH) {
    colorWipeUP(0x55, 0xFF, 0x00, 2);
    delay(600);
    colorWipeUP(0x00, 0x00, 0x00, 2);
    delay(100);
  }
  if (valDOWN == HIGH) {
    colorWipeDOWN(0x55, 0xFF, 0x00, 2);
    delay(6000);
    colorWipeDOWN(0x00, 0x00, 0x00, 2);
    delay(100);
  }
}

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}
void colorWipeDOWN(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 299; i < NUM_LEDS; i--) {
    setPixel(i, red, green, blue);
    FastLED.show();
    delay(SpeedDelay);
  }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
  leds[Pixel].r = red;
  leds[Pixel].g = green;
  leds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
  for (int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}

At the moment the LEDs just go on and after a delay off again (one-by-one).
QUESTION: I wish for a little smoother effect by fading them on and off.
So i reached the actual output by using different snippets and trying to understand. What i don't understand atm is how to add fading.

look up analogWrite and pulsed width modulation, or PWM, for how to fade LEDs.

Your code is currently written as blocking, so we can leave it that way and add another blocking nested loop. Let's take the colorWipeUP() function as example:
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}

You go through all leds, lighting them up one after another with the provided color, delaying between the LEDs. The brightness of an LED is controlled by the overall RGB value. If you just multiply the RGB components red, green and blue with a number between 0 and 1, you (mostly) keep the color and only control the brightness. For example like this:
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    for(uint8_t brightness = 0; brightness <= 100; brightness++){
      setPixel(i, red*brightness/100, green*brightness/100, blue*brightness/100);
      FastLED.show();
      delay(fadeDelay);
    }
    delay(SpeedDelay);
  }
}

For every LED we are now going from zero brightness to 100% brightness in a loop, showing each individual step on the LED strip.  fadeDelay determines, how fast this fade in should be. You will have to tune both delays to fit your expectations. You can use the same principle for the wipe down.
You may be asking yourself, why I count from 0 to 100 and then dividing by 100 instead of directly counting from 0 to 1 in steps of 0.01. I've done this, because on AVR based microcontrollers you don't have native floating point calculations. This means, that every floating point calculation needs many instructions to execute (because the floating point math is implemented in software instead of hardware). Here I'm counting with integers and when calculating the brightness also only integer math is involved (dividing by 100 is an integer division, which will automatically cut all digits after the decimal point. We don't need them).
Note: With 300 LEDs, the call to FastLED.show() will take some time. I haven't tested the code, but depending on your needs the fading might be too slow, even when you remove the delay call. Then you can simply increase the increment of the for loop, for example to use 10 steps instead of 100:
for(uint8_t brightness=0; brightness<100; brightness+=10)

something like a fade over 10 LEDs

For this I would use a totally different approach. If you view it mathematically, the brightness of each LED is a function of position and time. So we can implement a function much like a mathematical function, that returns the brightness for a given position and a given time. As I understood, you want the a function, that is first constantly zero, then it grows linearly with time and position and then it is constantly full brighntess. We can count the time from the moment, that the sensor is triggered, where we then start with zero brightness and let it rise linearly. Something like this:
int fadeBrightness(int position, unsigned long time){
    int brightness = m_p*position+m_t*time;
    if(brightness > 100) return 100;
    if(brightness < 0) return 0;
    return brightness;
}

m_p and m_t are constants, that you would need to define and fine tune. For fading over 10 LEDs, m_p has to be -10. time is provided as milliseconds. I'm currently not sure about the value of m_t, but you can simply try some values and use one that's fitting.
Then in your colorWipeUP() function you can loop through all LEDs and set their pixel just like in the code above, but this time you use the newly created function.
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  unsigned long timestamp = millis();
  while(millis()-timestamp < duration){
    for (uint16_t i = 0; i < NUM_LEDS; i++) {
      setPixel(i, red*fadeBrightness(i, millis()-timestamp)/100, green*fadeBrightness(i, millis()-timestamp)/100, blue*fadeBrightness(i, millis()-timestamp)/100);
    }
    FastLED.show();
  }
}

You need to define the duration according to how long the fading will take with your m_t. If you set it longer, the loop will just loop longer, holding the brightness at 100%.
In the function we first create a timestamp from the millis() function. Then we loop, while the duration of the effect hasn't passed. In each while loop iteration, we set the color components of each LED pixel with the brightness according to our fadeBrightness() function. Then we show this on the LED strip. The function is constantly updating the strip at max speed. The actual speed of the animation is determined by the fadeBrightness() function.
This version is also blocking code, but it can easily be transformed to non-blocking code, that you would call repeatedly until the animation is done.

Hey chrisl, thank you very much for this detailed explanation. As im trying to get something out of it, i started to struggle with "fadeDelay" and it seems like still one by one LED will be turned off - but with a slightly fade this time. :)
What i try to accomplish is something like a fade over 10 LEDs. Don't know how to explain it better - but i found a video which will explain it maybe better. [link]https://www.tweaking4all.com/wp-content/uploads/2015/11/LEDEffect-Fire.mp4?_=1[link]

@AxelKummerlöwe I added this to my answer, keeping the old answer intact, since it might be useful for someone.

Hey Chrisl,
thank you very much for your feedback - AGAIN! :)
As i becoming a dad today, maybe tomorrow - i'll be back to this post asap. But i think i'm able to work with your help.
Thanks again and a happy new year <3

You could do something like this. (not tested)
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (int i = -5; i < NUM_LEDS + 5; i++) {
    setPixel(i    ,      red, green, blue);   // example only
    setPixel(i + 1, .8 * red, green, blue);   // change the green and blue also
    setPixel(i + 2, .6 * red, green, blue);
    setPixel(i + 3, .4 * red, green, blue);   // successive pixels have lower brightness
    setPixel(i + 4, .2 * red, green, blue);
    FastLED.show();
    delay(SpeedDelay);
  }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {

  if (Pixel < 0 || Pixel >= NUM_LEDS) return;        // do not set color of non-existent pixels

  leds[Pixel].r = red;
  leds[Pixel].g = green;
  leds[Pixel].b = blue;
}


text:
Arduino Mega Speaker can't play music but noise
I'm struggling that my Arduino doesn't play music. Here is my circuit.
It proforms normally when I only connect this circuit to Arduino UNO. But when I change the whole circuit to Arduino Mega the music trues into noise. I've followed the tutorial to change the SD card adapter pin to the suggested pin.

Is there any possibility that the circuit is obstructed by servo motor which also connected to this Arduino mega? Here's my code.
#include <PS2X_lib.h>
#include <Servo.h>

#include "SD.h" //Lib to read SD card
#include "TMRpcm.h" //Lib to play auido
#include "SPI.h" //SPI lib for SD card

#define SD_ChipSelectPin 53 //Chip select is pin number 53
TMRpcm music; //Lib object is named "music"

Servo MG996;
Servo MG90B;
Servo MG90F;
PS2X ps2x;
int error;

const int enA = 7;
const int In1 = 39;
const int In2 = 41;
const int enB = 6;
const int In3 = 43;
const int In4 = 45;

int MG90B_pos = 90;
int MG90F_pos = 90;

void setup() {
  //music.speakerPin = 4; //Auido out on pin 4
  Serial.begin(9600);

  do {
    //GamePad(clock, command, attention, data, Pressures?, Rumble?)
    error = ps2x.config_gamepad(11, 9, 10, 8, true, true);
    if (error == 0) { Serial.print("Asian Big Cannon is activated!");break; }
    else { delay(100); }
  } while (1);

  pinMode(enA, OUTPUT);
  pinMode(In1, OUTPUT);
  pinMode(In2, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(In3, OUTPUT);
  pinMode(In4, OUTPUT);

  MG996.attach(32);
  MG90B.attach(31);
  MG90F.attach(30);

  MG996.write(90);
  MG90B.write(MG90B_pos);
  MG90F.write(MG90F_pos);

 /*
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}
music.setVolume(3);   //   0 to 7. Set volume level
music.quality(2);
*/
}

void mfront(){
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  Serial.println("front");
}
void mstop(){
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  //Serial.println("stop");
}
void mback(){
  digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
  digitalWrite(In3, LOW);
  digitalWrite(In4, HIGH);
  Serial.println("back");
}
void mright(){
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, HIGH);
  Serial.println("right");
}
void mleft(){
  digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  Serial.println("left");
  }

void loop(){

  music.play("JC.wav");
  Serial.println("playing....");
  delay(10000);
}

Please include your full code or a working minimal example, that shows your problem. This code wouldn't even compile. 2.  Yes, the servo can interfere with the library, if it also uses Timer1 as the TMRpcm library as default on the Mega

I've updated my code. This is a machine controlled by the PS2 handle. I delete some codes that refer to servo motor control. If it is the TMRpcm library problem, how can I solve it? Thanks!

Where's the circuit? It doesn't show up.

It's not clear whether your arduino UNO is actually plugged into the breadboard, or not.  If it is, then you are shorting all of the pins - not a good idea!

and do you wire it to SPI pins 50, 51, 52 on Mega?


text:
How to obtain the real and imaginary signal parts using Arduino FFT
How do you obtain the real and imaginary parts of a signal using FFT in arduino?
I could not find a particular tutorial with code for this purpose in the internet.

Probably not.  The Arduino isn't exactly the tool of choice for digital signal processing.  All you need is any FFT implementation in C, and you should be able to port it to the Arduino pretty easily.  The problem is getting a steady, fast sampling rate on the Arduino - that, and processing it fast enough on a slow, general purpose processor.

There are some implementations around such as https://www.arduinolibraries.info/libraries/arduino-fft - whether it extracts the real and imaginary parts I do not know.

@PeterSmith Good hint, and it should return a imaginary part too! The Compute-Method takes two double pointers  one to the real part samples and one to an array of 0.0 initialized imaginary part samples. Both arrays must have the same size. After computation the imaginary array is filled with the imaginary parts of the FFT. The library also provides examples.

Most libraries will either take one array of samples as input and then fill two other arrays of real and imaginary data, or it will take one array of samples and one empty array as input, and the sample data will be replaced by the real data and the empty array filled with the imaginary data.
You will have to first choose a library to use and then read the examples or documentation to see what the format of the functions are.


text:
SoftwareSerial Stopped Working
I have been browsing the internet for about 3 hours now, it appears other people have had the same problem but I can't find a solution for it.
Basically yesterday I received my first GSM module and I was playing around with some AT commands in the serial monitor and it was working absolutely fine, today I'm getting nothing.
It's not related to the module though, even the basic SoftwareSerial example doesnt work now. All that's printed is "Goodnight moon!" and it never prints "Hello, world?". It's like it's not able start the serial communication or something.
Any help would be much appreciated!
 #include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Where do you expect to see "Hello world"? It's being sent to your GSM module, so how can you possibly see it on serial?

@Majenko it was probably echoed back in command mode, buffered and sent back in the main loop. But the question isn't clear, user1796225 even though that didn't work did you try pressing enter a few times and typing "ATI" or a similar command to see if you get something back?


text:
Convert C string to C++ string
My program is running on ESP32. I'm retrieving some data from Bluetooth, and the Bluetooth string is a C string. I need to save that data in an RTC_DATA_ATTR String, which is a C++ string.
Just doing c++string = cstring.c_str(); won't work, since it will just save a pointer to the location in the memory of the C string, and the purpose is to save the data in the RTC memory, so the ESP32 can go to deep sleep without losing the data.
All other data than RTC gets wiped on deep sleep, so there would just be a pointer, pointing to nothing.
How do I get the data copied from the C string to the C++ string?
Any help would be appreciated. A bit of extra info: this is how it is set up at the moment:
RTC_DATA_ATTR String ssid;

BLECharacteristic *cSsid = NULL;

ssid = cSsid->getValue().c_str();

you mixed it up. you want a C string from String? .c_str() of String returns a constant pointer to the internal C string (zero terminated char array) of String which is in heap. but to save it to RTC memory something must copy it to the RTC memory. it is not neccessary to copy it into 'C string' in memory.

yes, my question is: how do i copy the c string to my rtc memory

I agree with  @Juraj . I believe you misused the terms cstring and c++ strings. As I understand your question, you have a class  RTC_DATA_ATTR that allocates its content memory (string typed) from the RTC EEPROM. Now you ask how you are able to initialize that Class with content from a "cstring". (as you use .c_str() I believe this is also a c++ string) Because I don't know the library RTC_DATA_ATTR is from I can not say how to copy text into a string of that type. You should at least add the library name to the question or give us some information what that type is like.

Your code would lead to a null pointer exception, which will be silently skipped..

i have no idea what library the RTC is apart of, I haven't #include any library which it is in

it doesnt give any error, when i compile it, but in the serial monitor, it println(rtcstring)  just prints clear line, as if rtc string was = null

i would guess the RTC and Deep_sleep commands come from the installed board in ArduinoIDE

but all im looking for is a way to copy the value of the string from bluetooth into the RTC string, which in my head the solution should just be todo: =

RTC_DATA_ATTR char ssid[33]; strcpy(ssid, cSsid->getValue().c_str());

A null pointer is a runtime error, which you can not see at compile time. In the arduino context you will not recognize the null pointer exception. But I'm sure you get one as you initialized the BLECharacteristic *cSsid = NULL; and then used the null pointer cSsid->getValue(). Or did I missed something and NULL is an option object? Can C++ handle option objects in the meantime? But anyway whithout knowing the library I can not help you. If you just want to make your string persistent you could probably write it to the FLASH memory. https://randomnerdtutorials.com/esp32-flash-memory/

solution found, using the strcpy, thanks

Sorry, now I understand what you tried. Yes it's part of the ESP32 software. And you might not want to store the date in EEPROM, just make it persistent while deep sleep. (I think I should go to sleep now ;-) ) https://randomnerdtutorials.com/esp32-timer-wake-up-deep-sleep/ @Juraj gave you the solution. But the null pointer problem is still there. Or is this not all of the code.

simply, using strcpy, and using a char with a given length, works
RTC_DATA_ATTR char ssid["dedicated length"];
strcpy(ssid, cSsid->getValue().c_str(), "dedicated length");


text:
RF24 code not working:
I watched this video and used his transmitter code and receiver code. However, it's not working. There's no response from the receiver.
The transmitter stuck at the loop:
if (!radio.write( &data, sizeof(unsigned char) )) {
Serial.println("No acknowledgement of transmission - receiving radio device connected?");
}

and the receiver never received anything and only printed:
  Serial.println("THIS IS THE RECEIVER CODE - YOU NEED THE OTHER ARDUINO TO TRANSMIT");

I've been stuck here for hours. I checked the hardware, there's no issue there. I also tried to adjust the code couple of times, and it looked decent but not helping. Could you help me to check what went wrong with the code please?

Try moving the transmitter and receiver further apart.

Check your wiring thrice, 99% of issues are there. Make sure the 3.3V bus is decoupled with at least 10mF of capacitance, noise on the 3.3V bus is an enormous no-no for nRF24L01+.

After that is done, find the RF24 examples from Arduino IDE, upload those to your boards with the right configuration and see if those work - it's a battle-tested piece of code.

@Avamander I saw your post in Arduino forum. However, it did not work for me. I went the expansive way. I tried the multiple noise filter, but it did not help. Eventually I got a special adapter with onboard regulator, it still didn't work. Turns out, it has to do with the communication device itself. The one I got had an antenna that strength singal the distance and penetration. But somehow it made the device very unreliable, possibly because it's receiving single within a mile. Once I switched to a weaker chip, it worked out immediately and the data was guaranteed.  Though less sensitive.

Even the modules with PA+LNA should work fine closer-range or in noisy environments. The most usual problem is that the power usage is underestimated, instead of the usual 14mA during transmission it could take hundreds, and that is above what onboard and could be above what small 3.3V regulators can provide. A few millifarads attached between GND and 3.3V should already improve reliability if it's the power that's the issue.

@Avamander There's nothing wrong with power. The single is very clean and I got maximum output of over 10W. I'm more and more sure it's the single receiving of that range-extended model. It's perpetuation ability was too good.  Does nRF24 library has any built in code to filter the single noise?(from the environment) I think the device is boosting every single received from the entire building. So it was not affected by the power supply, but the fact that the environment was so noise troubled actual single received.

@Avamander With weaker cheap, it's only able to receive the strongest single above certain threshold, thus a better communication quality and shorter range. i.e. it does not have the powerful LNA module.

Does nRF24 library has any built in code to filter the single noise? No, that can't be done.

The single is very clean and I got maximum output of over 10W. Are you within legal limits? The 2.4GHz band is for everyone to use.

@Avamander I set it to be min after the test.  and the channel I googled and used the channel that's not used by states providers

It's perpetuation ability was too good. [...] think the device is boosting every single received from the entire building. A nearby source will still most certainly overpower any far away noise source, receiving should work. The fact that a weaker module works still indicates a power supply issue rather than noise issue. However it's also possible that you have stumbled upon a counterfeit nRF24L01+, by any chance is it under a blob of epoxy?


text:
A problem with measuring time in a for loop
I am familiar with timing using millis() function, but it seems that I have run into a problem with a for loop.
The thing is, I am comparing encoder readings with a value entered via 4x4 keypad. Since I have to enter more than one value, i placed all values from the keypad into an array. Then I created a for loop that will cycle through that array and compare each value with encoder readings, when encoder reached the entered keypad value an LED should light up for 2 seconds. This is where the problem occurs. When it reaches the set value the LED seems to light up for like a fraction of a second. My guess is that the loop is creating some trouble here. Maybe because the loop cycles so fast the LED doesn't have enough time to stay lit. What do you think?
When I tried this program without a for loop (with only one value entered from a keypad), it works fine.
The code below has two arrays with values already entered, so no need or keypad. I used it just for testing. When I solve this problem I will add a keypad.
Please ask if you need any clarification of the code , and thank you in advance
#include <Encoder.h>
#include<Wire.h>
#include<LiquidCrystal_I2C.h>

int led1=14;
int led2=15;
unsigned long encoder;
unsigned long prev_value;
int array1[]={100, 200, 300, 400, 500, 600};
int array2[]={150, 250, 420};
int i,j,k,l;
int brV=6;
int brM=3;
int tolerance=10;
unsigned long oldTime=0.0;
unsigned long newTime;
int dt=2000;
bool testRange=true;
bool testRange2=true;

Encoder myEnc(2,3);
LiquidCrystal_I2C lcd1(0x27, 16, 2);

void setup() {
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
lcd1.init();
lcd1.backlight();
}

void loop() {
  newTime=millis();
  lcd1.setCursor(0,0);
  encoder=myEnc.read()*446/400;
  if(encoder!=prev_value){
    lcd1.clear();
    delay(10);
    prev_value=encoder;
  }
  lcd1.print(encoder);
  digitalWrite(led1,LOW);
  digitalWrite(led2,LOW);

  k=brV+brM;

  for(l=0;l<k;l++){
     for(i=0;i<brV;i++){
        if(encoder>=array1[i] && encoder<=(array1[i]+tolerance) && testRange){
           oldTime=newTime;
           digitalWrite(led1,HIGH);
           testRange=false;
         }
         else if(oldTime-newTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }
         if(encoder>(array1[i]+tolerance){
          testRange=true;
         }
     }
      for(j=0;j<brM;j++){
         if(encoder>=array2[j] && encoder<=(array2[j]+tolerance) && testRange2){
           oldTime=newTime;
           digitalWrite(led2,HIGH);
           testRange2=false;
         }
         else if(newTime-oldTime >= dt){
          oldTime=newTime;
          digitalWrite(led2,LOW);
         }
         if(encoder>array2[j]+tolerance){
          testRange2=true;
         }
      }
  }

  }

how long do you think it takes to execute the for loops until the LED is switched off in loop()?

I imagine it takes a couple of milliseconds for the for loop to execute

I guess it is less then a millisecond and that is how long the LED is lit. plus the LCD code

Could the problem be solved if I use timer interrupts?

what else is allowed to happen in the 2 seconds while the LED is on?

This program is just for testing. In the main program there will be another LED that will be lit all the time, but it will turn off for those 2 seconds, and turn back on again when 2 seconds have passed

move the handling of the LED timeout out of the for loops, directly to loop()

But the LED need to light up only when encoder value is greater than array[i] . Will the program know when to turn the LED on?

in loop() replace
digitalWrite(led1,LOW);

with
if (newTime - oldTime >= dt){
   digitalWrite(led1,LOW);
}

and you can remove the
else if(oldTime-newTime >= dt){
   oldTime=newTime;
   digitalWrite(led1,LOW);
}

from the for loop

Now it works, the LED turns on for 2 seconds, and then turns off. But only for the first iteration, it works for the first value form the array, when comparing to the other values it behaves the same as before

you want to lit the LED for 2 seconds so many times how many values match? then count the matches first and then do the blinking

I have tried that. I added a counter that counts how many times those two values match. And then, in my IF  I added that whenever the newTime-oldTime >= dt && i<counter it should turn the LED off, and increment i by 1 (i++) , but it still behaves the same. For some reason it looks like it only recognizes the first iteration of the for loop

Old time and new time are wrong way round on a part where the LED'd are switched off
else if(oldTime-newTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

When simple processors reach the max or min value and continue counting, they overflow and start counting from far end: So 5-8=maxint(largest number)-3
Result is that the difference is a massive number greater then 2000 except every few weeks when millis() overflows and become larger then Unsigned large int can store and starts counting from zero. (many codes fail working on that occasion, your would only works then ;-)
Correct version:
else if(newTime-oldTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

Although I have noticed that testrange (both) only returns its value onto true on limited circumstance if input from encoder increased considerably very quickly to catch-up with growing inputs, so the next values will never pass condition to switch them on
if(encoder>=array1[i] && encoder<=(array1[i]+tolerance) && testRange)
will never return true because testRange stays false. Add
testRange=true;
testRange2=true;
at the end of the loop otherwise it does return into true for next loop()iteration. I guess question is if you want other functions to run while LEDs are on or not.
It is a bad habit to make unnecessary variables like i,j,k,l global as they waste memory even when not needed you can define them within structure itself Eg: for(int i=1;... this way as soon as for, while etc loop (brackets close)finishes you get your memory back and you can use variable again

You  are right, a stupid mistake. I've changed it now, but it still doesn't seem to work