text:
RGB Matrix flickering every ~5 seconds when paired with SoftwareSerial
I'm running an RGB matrix through an Uno and trying to run it alongside SoftwareSerial so that I can integrate an ESP8266 into things. The trouble is, when I start introducing the SoftwareSerial into things, the screen flickers every few seconds, consistently. For example, with this function, it flickers exactly every 10 seconds. Any ideas what might be causing this or how to fix it?
Below is the arduino code. The RGB matrix is configured like this.
#include <RGBmatrixPanel.h>
#include <SoftwareSerial.h>

#define CLK  8   // USE THIS ON ARDUINO UNO, ADAFRUIT METRO M0, etc.
//#define CLK A4 // USE THIS ON METRO M4 (not M0)
//#define CLK 11 // USE THIS ON ARDUINO MEGA
#define OE   9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2
#define setDelay 500

RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);

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

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

  Serial.println("Start Serial!");

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

  matrix.begin();
}

void loop() {

  // draw a pixel in white
  matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
  delay(setDelay);

  // fix the screen with green
  matrix.fillRect(0, 0, 32, 16, matrix.Color333(0, 7, 0));
  delay(setDelay);

  // draw a box in yellow
  matrix.drawRect(0, 0, 32, 16, matrix.Color333(7, 7, 0));
  delay(setDelay);

  // draw an 'X' in red
  matrix.drawLine(0, 0, 31, 15, matrix.Color333(7, 0, 0));
  matrix.drawLine(31, 0, 0, 15, matrix.Color333(7, 0, 0));
  delay(setDelay);

  // draw a blue circle
  matrix.drawCircle(7, 7, 7, matrix.Color333(0, 0, 7));
  delay(setDelay);

  // fill a violet circle
  matrix.fillCircle(23, 7, 7, matrix.Color333(7, 0, 7));
  delay(setDelay);

  // fill the screen with black
  matrix.fillScreen(matrix.Color333(0, 0, 0));

  // draw some text!
  matrix.setCursor(1, 0);  // start at top left, with one pixel of spacing
  matrix.setTextSize(1);   // size 1 == 8 pixels high

  // print each letter with a rainbow color
  matrix.setTextColor(matrix.Color333(7,0,0));
  matrix.print('1');
  matrix.setTextColor(matrix.Color333(7,4,0));
  matrix.print('6');
  matrix.setTextColor(matrix.Color333(7,7,0));
  matrix.print('x');
  matrix.setTextColor(matrix.Color333(4,7,0));
  matrix.print('3');
  matrix.setTextColor(matrix.Color333(0,7,0));
  matrix.print('2');

  matrix.setCursor(1, 9);  // next line
  matrix.setTextColor(matrix.Color333(0,7,7));
  matrix.print('*');
  matrix.setTextColor(matrix.Color333(0,4,7));
  matrix.print('R');
  matrix.setTextColor(matrix.Color333(0,0,7));
  matrix.print('G');
  matrix.setTextColor(matrix.Color333(4,0,7));
  matrix.print("B");
  matrix.setTextColor(matrix.Color333(7,0,4));
  matrix.print("*");
  }

Does it coincide with when data arrives on the software serial pins?

Oh come to think of it, it sure does!

Welcome to the world of SoftwareSerial. Nothing (and I mean nothing) else can happen when data is being either sent or received.

This should be a fairly easy fix, though. I wonder if there's a way to sync the ESP8266 clock with the Uno receiving so I can basically say "do this every 10 seconds, but not when the ESP8266 is sending!"

It all depends on what the ESP8266 is doing. If you have your own firmware on there you could make it call-and-response so it never sends anything unless asked to by the Arduino.

That makes sense. But in that short period where the Uno asked for something from the ESP8266 and the ESP8266 returned it, the Uno still wouldn't be able to display anything to the matrix without flickering, right? Would this be a problem if I were using the hardware serial? I would go that route but it seems like it makes debugging a lot harder!

Hardware serial will do way better. Then only the processing of the received data needs time, not the receiving itself. Also you can ditch the delays and use millis() like in the BlinkWithoutDelay example, so that you can do other things (for example serial), while waiting for the time to pass.


text:
SPIMemory does not write always correctly
I'm using a WinBond 25Q128FVIQ (Flash 128 mbit, 3.3V) in combination with the Marzogh SpiMemory library on my Arduino Nano (also 3.3V).
After using the default example, I found out what was read, did not always fully match what I wrote. So I created a slightly alternative example writing 16 bytes:
#include<SPIMemory.h>

uint32_t address;

#define BAUD_RATE 115200
#define RANDPIN A0

//SPIFlash flash(SS1, &SPI1);       //Use this constructor if using an SPI bus other than the default SPI. Only works with chips with more than one hardware SPI bus
SPIFlash flash;

bool readSerialStr(String &inputStr);

void setup() {
  Serial.begin(BAUD_RATE);
#if defined (ARDUINO_SAMD_ZERO) || (__AVR_ATmega32U4__)
  while (!Serial) ; // Wait for Serial monitor to open
#endif

  flash.begin();
  Serial.println(F("Flash Test"));
  Serial.print(F("Capacity: "));
  Serial.println(flash.getCapacity());

  char writeBuffer[16] = "0123456789ABCDEF";
  char readBuffer[17];

  for (int n = 0; n < 5; n++)
  {
    memset(readBuffer, 17, 0);
    randomSeed(analogRead(RANDPIN));
    address = random(0, flash.getCapacity() - 16);
    bool err = flash.writeAnything(address, writeBuffer, true);
    delay(50);
    Serial.print(F("Write: "));
    Serial.println(err);
    for (int m = 0; m < 10; m++)
    {
      if (flash.readAnything(address, readBuffer, true))
      {
        Serial.print(m);
        Serial.print(F(", read: "));
        Serial.print(readBuffer);
        Serial.print(F(", from address: "));
        Serial.println(address);
      }
      delay(50);
    }
  }
}

void loop() {

}

//Reads a string from Serial
bool readSerialStr(String &inputStr) {
  if (!Serial)
    Serial.begin(115200);
  while (Serial.available()) {
    inputStr = Serial.readStringUntil('\n');
    Serial.println(inputStr);
    return true;
  }
  return false;
}

Short explanation: 5 times I write a string (hex numbers), and I read this 5 times. The result is: (one example, differs every time):
 Flash Test
Capacity: 8388608
Write: 1
0, read: 0123456789ABCDEF, from address: 6252204
1, read: 0123456789ABCDEF, from address: 6252204
2, read: 0123456789ABCDEF, from address: 6252204
3, read: 0123456789ABCDEF, from address: 6252204
4, read: 0123456789ABCDEF, from address: 6252204
5, read: 0123456789ABCDEF, from address: 6252204
6, read: 0123456789ABCDEF, from address: 6252204
7, read: 0123456789ABCDEF, from address: 6252204
8, read: 0123456789ABCDEF, from address: 6252204
9, read: 0123456789ABCDEF, from address: 6252204
Write: 1
0, read: 0123456789ABCDEF, from address: 5680766
1, read: 0123456789ABCDEF, from address: 5680766
2, read: 0123456789ABCDEF, from address: 5680766
3, read: 0123456789ABCDEF, from address: 5680766
4, read: 0123456789ABCDEF, from address: 5680766
5, read: 0123456789ABCDEF, from address: 5680766
6, read: 0123456789ABCDEF, from address: 5680766
7, read: 0123456789ABCDEF, from address: 5680766
8, read: 0123456789ABCDEF, from address: 5680766
9, read: 0123456789ABCDEF, from address: 5680766
Write: 0
0, read: , from address: 5277398
1, read: , from address: 5277398
2, read: , from address: 5277398
3, read: , from address: 5277398
4, read: , from address: 5277398
5, read: , from address: 5277398
6, read: , from address: 5277398
7, read: , from address: 5277398
8, read: , from address: 5277398
9, read: , from address: 5277398
Write: 0
0, read: , from address: 4941258
1, read: , from address: 4941258
2, read: , from address: 4941258
3, read: , from address: 4941258
4, read: , from address: 4941258
5, read: , from address: 4941258
6, read: , from address: 4941258
7, read: , from address: 4941258
8, read: , from address: 4941258
9, read: , from address: 4941258
Write: 0
0, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
1, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
2, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
3, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
4, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
5, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
6, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
7, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
8, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
9, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153

Conclusion: The write seems to be the problem as the read consequently returns the same value (either garbage or the correct string).
What do I wrong?
Actually, I even don't want the 50 ms delay (and when I remove it, the result is the same).

I made a stupid mistake; I accidentally removed the next line at the end of the application which takes care of erasing the sector. If this is omitted, then the next time write actions will fail (or fail sometimes):
flash.eraseSector(address);

source: Stack Exchange

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

sort: votes


text:
Arduino PWM 1kHz and 10-bit resolution
As the title says, I need 1khz frequency signal with 10-bit resolution. But I am not good with uControllers and complicated programming.
I need a simple code for this task.
I tried using this Interactive PWM from arduinoslovakia.eu but I dont know what the frequency is at 10-bit resolution and how to set frequency in this code.

Are you talking about a square wave? In what way would it have 10-bit resolution? Either it is 1 kHz or not, yes? Are you talking about an error factor? Like, 1 kHz +/- 5% ?

@NickGammon The "10-bit resolution" will refer to the resolution of the duty cycle parameter. i.e., a duty cycle between 0 and 1023 instead of the normal 0 to 255.

Perhaps but the rather brief question does not mention duty cycles.

@NickGammon No, but it does mention PWM, and PWM has a duty cycle (which is what makes it PWM).

I see you are talking about using the 16-bit timer, which is Timer 1 on the Uno.
Assuming you are using a Uno this code will do it:
// Clock frequency divided by 1 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 1000;

const byte outputPin = 10;  // Timer 1 "B" output: OC1B

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

  // set up Timer 1
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  (timer1_OCR1A_Setting / 2) - 1;           // 50 % duty cycle
  }  // end of setup

void loop()
  {
  }

You can change the 1000 in the calculation for timer1_OCR1A_Setting, within reason, to get other frequencies.
See my page about timers for more background information.

On a 16Mhz Arduino you'd get around 14 bits of resolution, using this code. It is however impossible to get exactly 14-bit (or 10-bit) of resolution without changing the frequency (to around 0.9765kHz).

To explain that comment, OCR1A would be set to 16000 using the above code, and that is log(16000)/log(2) bits, namely 13.97 bits roughly. Therefore your duty cycle (OCR1B) could be in the range 0 to 15999 giving at least 10 bits of resolution.

Thanks for the answer.

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


text:
Using ESP32-CAM (with ov2640 camera image sensor) to send image via USB
I was trying to obtain image from ESP32-CAM (with ov2640 camera image sensor).
I obtained the image through camera web server by connecting the ESP32-CAM and PC to same wifi network. A USB to TTL module was used to interface ESP32-CAM to PC.
Program was uploaded to ESP32-CAM using arduino IDE
Reference video: https://www.youtube.com/watch?v=U5uvl6kDFJY
ESP32-CAM development board and ov2640 CMOS image sensor: https://i.stack.imgur.com/0Fa2W.jpg
CP2102 USB to TTL module:  https://i.stack.imgur.com/Zr0YV.jpg
Since this system involved wifi I had some serious trouble in obtaining the image:

Entering wifi credentials
Connecting the ESP32-CAM and PC to same wifi network
with variations in wifi speed image display lags which is the main problem

So I was hoping to transfer the image from ESP32-CAM to PC via USB just like connecting a USB webcam to PC.
Can anyone please help to find a solution?

You would have to write some special software for your PC to receive the camera data over the USB UART connection - then send it over the USB UART connection from the ESP32 in the format that you have decided upon.  It can never be a webcam, since the CP2102 is a UART adaptor.

Why not just use a webcam?

Thank you for your suggestion.

I'am not using webcam since its form factor and cost is not reasonable. Do you have any suggestion regarding the special software that you mentioned?

Did you make it out eventually?


text:
LED fader function freezes and becomes unresponsive after a few cycles
My LED controller has a color fader mode that I am making. The controller's loop() function grabs incoming serial data to set the amount of colors, fade speed, mode, and other info then runs the correct mode with the colors that it read from the serial port
When in color fader mode, the controller "freezes" at a certain color and becomes unresponsive to further input until I unplug it and plug it back in or reupload the code (the latter means that it still responds to something).
For testing purposes I am using red, green, and blue in that order. This stopping color can happen anywhere from in the middle of the transition from red to green in the first cycle to going through multiple cycles and stopping on blue depending on the fade speed. This only became a problem after I switched from using delay() to millis(). Why is that and what can I do to fix it?
The reason I switched to using millis is because the delays would stack infinitely and the arduino would become unresponsive to commands
Here is my relevant code:
#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 60
#define DATAPIN    4
#define CLOCKPIN   5

Adafruit_DotStar strip(NUMPIXELS, DOTSTAR_BRG);

// Variables
int mode;
int numColors;
int fadeSpeed;
int BBCC;
int R[100];
int G[100];
int B[100];
int Bright[100];

int currColor;

void setup() {

#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
  clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
#endif
  strip.begin(); // Initialize pins for output
  strip.show();  // Turn all LEDs off ASAP

  currColor = 0;
}

void loop() {
  strip.show();                     // Refresh strip
  delay(20);                        // Pause 20 milliseconds (~50 FPS)

  getData();

  switch (mode)
  {
    case 1:                  // Mode 1: Solid Color
    {
      for (int i = 0; i < NUMPIXELS; i++)
      {
        if (i % 2 == 0)
          strip.setPixelColor(i, G[0], R[0], B[0]);// Sets whole strip to Color 1
      }
      strip.setBrightness(Bright[0]);
      strip.show();
      break;
    }
    case 2:                  // Mode 2: Multi Color Fader
    {
      colorFade();
      break;
    }
    case 3:                  // Mode 3: Multi Color Pattern
    {
      int j = 0;
      for (int i = 0; i < NUMPIXELS; i++)
      {
        if (i % 2 == 0)
        {
          strip.setPixelColor(i, G[j], R[j], B[j]); // sets a repeating pattern
          if (j == (numColors - 1))
            j = 0;
          else
            j++;
        }
      }
      strip.setBrightness(Bright[0]);
      strip.show();
      break;
    }
    case 4:                  // Mode 4: Music-Reactive Wave Form
    {

      break;
    }
    case 5:                  // Mode 5: Music-Reactive Color Jump
    {

      break;
    }
    default:                 // Default Mode: Incandecent Simulation
    {
      for (int i = 0; i < NUMPIXELS; i++)
      {
        if (i % 2 == 0)
          strip.setPixelColor(i, 150, 200, 40); // Sets whole strip to default value
      }
      strip.setBrightness(255);
      strip.show();
      break;
    }
  }

}

void colorFade()
{
  int del = 100;     // 100 milisecond
  if (currColor >= numColors - 1)
  {

    int steps = fadeSpeed * del;
    int Rdiff, Gdiff, Bdiff, BrightDiff;

    Rdiff = R[0] - R[currColor];
    Gdiff = G[0] - G[currColor];
    Bdiff = B[0] - B[currColor];
    BrightDiff = Bright[0] - Bright[currColor];

    for (int i = 0; i <= steps + 5; i++)
    {
      for (int j = 0; j < NUMPIXELS; j++)
      {
        if (j % 2 == 0)
          strip.setPixelColor(j, (G[currColor] - (Gdiff * i)), (R[currColor] - (Rdiff * i)), (B[currColor] - (Bdiff * i))); // Sets whole strip to value
      }
      //strip.setBrightness((Bright[currColor] - (BrightDiff * i)));
      strip.show();
      //delay(del);
      int timer = millis() + del;
      while(millis() < timer)
      {

      }
    }
    currColor = 0;
  }
  else
  {
    int steps = fadeSpeed * del;
    int Rdiff, Gdiff, Bdiff, BrightDiff;

    Rdiff = R[currColor + 1] - R[currColor];
    Gdiff = G[currColor + 1] - G[currColor];
    Bdiff = B[currColor + 1] - B[currColor];
    BrightDiff = Bright[currColor + 1] - Bright[currColor];

    for (int i = 0; i <= steps + 5; i++)
    {
      for (int j = 0; j < NUMPIXELS; j++)
      {
        if (j % 2 == 0)
          strip.setPixelColor(j, (G[currColor] - (Gdiff * i)), (R[currColor] - (Rdiff * i)), (B[currColor] - (Bdiff * i))); // Sets whole strip to value
      }
      //strip.setBrightness((Bright[currColor] - (BrightDiff * i)));
      strip.show();
      //delay(del);

      int timer = millis() + del;
      while(millis() < timer)
      {

      }
    }
    currColor++;
  }
}

start debugging by running only the fade selection ... preset mode to 2 ....  comment out getData(); in loop()

how would I debug this in arduino IDE? I can't find any command for breakpoints and I don't know what I would need to look at if i used serial.println() to read values

There is no debugging in the normal embedded firmware sense WRT Arduino programming.  That is why you need to start small and not add anything more complex until the small thing works.

it is not "Arduino" ... it is "C++" .... insert mode = 2; in  setup() ...  replace getData(); with // getData();

After looking elsewhere, you can debug arduino by sending something to serial monitor via Serial.println(). That would have been helpful to mention since I could check the values of timer and millis() using this command. timer was overflowing because of the int data type, and millis() would eventually roll over and stop at an upper limit. That was causing the problem

@BoatHouse Please write an answer to your question, so that others can profit from it. Thank you

The problem with the above code lies with overflow. timer should be an unsigned long, because millis() outputs an unsigned long. This causes the freeze because after timer hits its upper limit, This setup works better:
unsigned long timer = (unsigned long)millis() + del;
      while((unsigned long)millis() < timer)
      {
        //wait for as long as del says to
      }

This setup should be able to run for a long time without overflowing


text:
strcat parameters throwing pointer errors in my tcp server / parser application
I am attempting to use an Arduino Uno WiFi Rev2 board to integrate some lonely data. I will use the NINA WiFi chipset and associated libraries to start a server that will periodically request and receive client information hosted on multiple types of devices that will run concurrently; thus it's pretty much divided in 2 sections:
1.) Manage the client connections and their character arrays
2.) Parsing the information and responding accordingly from a control aspect
This is what I have so far, and what I was just compiling the other day:
#include <stdlib.h>
#include <SPI.h>
#include <WiFiNINA.h>

char ssid[] = "***";                // House -- Network SSID (name)
char pass[] = "***";              // House -- SSID password (WPA2-PSK)

#define MAX_CLIENTS 5
#define MAX_LINE_LEN 50
char inputs[MAX_CLIENTS][MAX_LINE_LEN] = {0}; // Instantiate 2D array of
client/received data
int msg_array[] = {0,0};
int net_status = WL_IDLE_STATUS;              // The Wifi radio's status
WiFiServer server(80);           // Create server object on port of WiFi
                                 // server, which will be used to
                                 // respond to commands

WiFiClient *clients[MAX_CLIENTS] = {NULL};    // Create client objects
                                              // limited to size of
                                              // MAX_CLIENTS

byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED}; // Arduino's physical MAC
byte ip[] = {192,168,9,25};              // IP of this controller
byte gateway[] = {192,168,0,1};          // Router address (internet)
byte subnet[] = {255,255,0,0};           // Subnet mask

unsigned long wd_Dside, wd_Cside = millis();   // Gather current tstamp
unsigned long wd_Delap, wd_Celap = 0;          // Create an elapsed time
                                               //counter

void setup(){

   pinMode(4, OUTPUT);                 // pin selected to control D SIDE
   pinMode(5, OUTPUT);                 // pin selected to control C SIDE

   //enable serial data print
   Serial.begin(9600);
   while (!Serial){
       Serial.println("No serial.");
   }

      Serial.println("Serial.begin was initiated.");

   if (WiFi.status() == WL_NO_SHIELD) {  // check for the WiFi module:
      Serial.println("Wi-Fi: Communication with NINA has failed!");
      // do nothing here
      while (true);
   }

   String fv = WiFi.firmwareVersion();
   if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
      Serial.println("Please upgrade the firmware");
   }

   while (net_status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(ssid);

      // Connect to WPA/WPA2 network:
      net_status = WiFi.begin(ssid, pass); // Attempt to join this SSID

      // wait 5 seconds for connection:
      delay(5000);

      listNetworks();

      server.begin();                      // Start Wi-Fi server
      Serial.print("Server started on ");
      Serial.println(WiFi.localIP());
    }
}

void loop() {

    delay(5);

    WiFiClient newClient = server.available(); // Begin listening for
                                               // client messages
    if (newClient) {
        Serial.println("New client discovered."); // Could use this as
                                                  // an ACK/handshake on
                                                  // client-side host
        for (int i=0; i<MAX_CLIENTS; i++) {
          if (clients[i] == NULL) {
            clients[i] = new WiFiClient(newClient);
            break;
      }
   }
}

    for (int i=0; i<MAX_CLIENTS; i++){      // Check client for data
      if (clients[i] != NULL && clients[i]->available()){
         // If the data isn't garbage and the data is available..

        char newChar = clients[i]->read();
        // Read the data

        if (newChar == 'x') {
        // Check for a termination character for separation

        // Now parse with strtok in order to get parameterization
          char delimiters[] = ",";
          char* valIndex;
          valIndex = strtok(inputs[i], delimiters);
          for (int j=0; j < 2; j++){
            // Expand later to largest anticipated character count
            msg_array[j] = atoi(valIndex);
            Serial.print(msg_array[j]);
            valIndex = strtok(NULL, delimiters);
          }

          switch(msg_array[0]) {
          // Determine type of message received (Character 0 parsed as
          // Message Type)

            case '3':
            // Examine string for client cmds to turn sides on or off.
            if(msg_array[1] == '1')
            // Msg type 3, Instruction 1: Turn D side ON
              {
                digitalWrite(4, HIGH);
                // Set pin 4 high
                Serial.println("Dside started.");
                wd_Delap = 0;
                // Reset elapsed time watchdog time value for D side.
                wd_Dside = millis();
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '2')
            // Msg type 3, Instruction 2: Turn D side OFF
              {
                digitalWrite(4, LOW);
                // Set pin 4 low
                Serial.println("Dside stopped");
                wd_Delap = 0;
                // Reset elapsed time watchdog time value for D side.
                wd_Dside = millis();
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '3')
                // Msg type 3, Instruction 3: Turn C side ON
              {
                digitalWrite(5, HIGH);
                // Set pin 5 high
                Serial.println("C side started.");
                wd_Celap = 0;
                // Reset elapsed time watchdog time value for C side.
                wd_Cside = millis();
                // Last good heartbeat from client device on C side.
              }
            if(msg_array[1] == '4')
                // Msg type 3, Instruction 4: Turn C side OFF
              {
                digitalWrite(5, LOW);
                // Set pin 5 low
                Serial.println("C side stopped.");
                wd_Celap = 0;
                // Reset elapsed time watchdog time value for C side.
                wd_Cside = millis();
                // Last good heartbeat from client device on C side.
              }
            break;

            case '6':

                // Examine string for another message type TBD
            break;

            default:
              Serial.println("Default break. Received crap.");
            break;

          }

        inputs[i][0] = '\0';
        // Clear out this array element for the next message
        // clients[i]->stop();
        // By default, kill client session, just wait for new TCP open
        // delete clients[i];
        // Remove client element's data
        // clients[i] = NULL;
        // Reset to NULL

        }

        else {

           if (strlen(inputs[i]) > MAX_LINE_LEN) {
                // First check for size compliance
           Serial.println("Max line length exceeded from client.");
           inputs[i][0] = '0';
                // Clear out this array element for the next message
           }
           else {
           **strcat(inputs[i], newChar);**
                // Add character to the received string
           }

          Serial.println();
          Serial.println(newChar);
        }
      }

    // Update watchdog timers

    wd_Delap += (millis()-wd_Dside);
    wd_Celap += (millis()-wd_Cside);

    if (wd_Delap>=60000)
          {
            Serial.print("Elapsed time on watchdog, D side: ");
            Serial.println(wd_Delap);
            Serial.print("Last message received: ");
            Serial.println(wd_Dside);
            digitalWrite(4, LOW);    // set pin 4 low
            Serial.println("D side didn't hear from a client in 60s;
                           defaulting to OFF.");
          }

    if (wd_Celap>=60000)
          {
            Serial.print("Elapsed time on watchdog, C side: ");
            Serial.println(wd_Celap);
            Serial.print("Last message recieved: ");
            Serial.println(wd_Cside);
            digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("C side didn't hear from a client in 60s;
                            defaulting to OFF.");
          }

   }
}

I previously had this compiling and running, though with issues that I intedned on iteratively troubleshooting. Now it won't compile because of the following error:

arduino:302:37: error: invalid conversion from 'char' to 'const char*' [-fpermissive]
strcat(inputs[i], newChar);   // Add character to the received string

..which I have attempted to bold above in the final else clause. I realize these parameters require pointers, but it seems like some of the other functions like strtok and strlen which ask for pointers as well seem to work okay in my code.
Are there any suggestions or alternatives to strcat() as to how I could make this work? I have mostly stuck with character arrays instead of declaring String objects. I am also obviously pretty rusty at C(++) as I haven't been actively working with it in a while.
Thank you

strcat is a function to concatenate strings. It expects a char array as second parameter. You have only a single char newChar to add to your string.
size_t l = strlen(inputs[i]);
inputs[i][l] = newChar;
inputs[i][l + 1] = 0;

Note: It would be better to track the length of the inputs then use strlen. strlen iterates over the array until terminating zero.

Thank you. I think this will work. Question, is the third line necessary? Wouldn't that just add a character '0' at the end, or are you saying that's the character for termination, which I thought was '\0'

the next strlen would not work without the terminating zero. ascii code of '\0' is 0. some use NULL, which is 0 too


text:
BLDC motor control
I want to control a BLDC motor with Arduino board and a circuit with some transistors and other elements, the input of this board will be flight control. my question is that is it possible to connect a flight control with an Arduino board? if it is possible do you have any idea?

Yes it is possible

You should also check https://electronics.stackexchange.com/questions/169398/bldc-motor-without-esc and https://electronics.stackexchange.com/questions/355167/how-does-a-hobby-esc-drive-a-bldc-motor . Making your own ESC or " a circuit with some transistors ..." as you have said is no easy task.

You do you even want to build your own ESC? I don't think, that this will be cheaper than simply buying one.

Tnx ,i know uts better to buy a ESC but i wanna  have exprience in building a ESC  for a quad.i will make it with a arduino board and push_pull transistors in this circuit i control the arduino board with two  micro swiths but now l wanna control this with flight controller by giveing the flight control signal to arduino how can i do it?


text:
Understanding datasheet of a HCHO gas sensor
I have a gas sensor whose datasheet is attached:
DS-HCHO
Now it says that UART communication is needed (P2P) where it (module) waits for Data Frame before tx the data frame to host which I need.
All i know is that I can send start bit in I2C but how shall I proceed.
Also if I have multiple sensors how shall I connect them to ESP-32?

UART is used for rs232 type communication ... it is not I2C

Datasheet says sensor waits for bytes before sending, show shall I proceed with the coding. I could not receive data values.

Step 1: Send the correct data bytes. Step 2: Receive the data from the module. Step 3: Profit.

https://www.arduino.cc/reference/en/language/functions/communication/serial/

First, you need to be communicating by UART, not I2C.  That means using Serial or some similar object (On ESP32 you can define your own on whatever pins you want).  However, the datasheet omits one vital piece of information: the baud rate it communicates at - so you will have to guess that and try various different standard baud rates until you find the one that works.
Then you have to send the "Give me the data" instruction.  The module then responds with the data.
For example (untested):
HardwareSerial mySerial(1);

#define PIN_RX 21
#define PIN_TX 22

void setup() {
    Serial.begin(115200);
    mySerial.begin(9600, SERIAL_8N1, PIN_RX, PIN_TX); // This is the one you need to guess since the DS omits it...
}

void setup() {

    // Once a second send the request to get the data

    static uint32_t ts = millis();
    if (millis() - ts > 1000) { // Once a second
        ts = millis();
        // "Give me the data"
        mySerial.print("\x42\x4d\x01\x00\x00\x00\x90");
    }

    // When 10 or more bytes have arrived then assume that they are correctly
    // framed and print them.  Really it should read one byte at a time and
    // look for the correct start sequence of 0x42 0x4d 0x08 and read only
    // from there, but this will server for demonstration purposes.

    if (mySerial.available() >= 10) { // We expect 10 bytes returned
        uint8_t packet[10];
        mySerial.readBytes(packet, 10);
        Serial.print("ID:   ");
        Serial.println(packet[3]);
        Serial.print("UNIT: ");
        Serial.println(packet[4]);
        Serial.print("VH:   ");
        Serial.println(packet[5]);
        Serial.print("DHH:  ");
        Serial.println(packet[6]);
        Serial.print("DLL:  ");
        Serial.println(packet[7]);
        Serial.print("LRCH: ");
        Serial.println(packet[8]);
        Serial.print("LRCL:   ");
        Serial.println(packet[9]);
    }
}

Thanks. Well it helped a lot.


text:
How to connect LED lights for 3D Printed Robot
I'm new here and a newbie in electronics. I have a project to create a 3d printed robot with lights. I came across neopixels led's and the ardruino microcontrollers recently and find it to be a great possible sollution for what I need.
For my project, the 3d printed toy will have several parts that would need lights and I plan to use roughly over 40 LEDs connected to one source. I' m thinking of using the WS2812B LEDs.
I plan to use one neopixel ring for the robot's chest similar to Iron-Man's arch reactor.. While the head head will have 2x LEDs for the eyes, a smaller neopixel ring for the headpiece, another 2x LEDs for on the side of the robot mouth and 3x LEDs inside each vents on both sides of the robots head.
I need all the LEDs to turn on with a white light with a switch and turn red with another button. Although, I'd still be happy if they can only work with white.
For the power source, I was thinking about using a small powerbank or 2x 18650 batteries as the power source.
As mentioned, I'm very new to electronics and based on my research so far, i get confused really fast from all the jargons used and I'm not sure how to proceed.
Hopefully, i can get some answers here.
So.... My question is, is it possible to connect all the LEDs i plan to use on one microcontroller (ie: Ardruino Uno or Nano)
Most of the examples I can see on youtube are projects using LED strips. Are they diffrences in the way they are connected?
Another problem is coding for the ardruino..i'm totally clueless.
Any suggestions or help would be very much appreciated.

all of the LEDs on your robot are just one LED strip as far as connection and programming go

The key point for WS2812B LEDs is, that they can be daisy chained. This means, that everyone of them has one data input and 1 data output. If you connect the data output of one LED to the data input of the other, you created a short strip with 2 LEDs. Doing this multiple times creates a bigger LED strip. It's not relevant, if the LEDs are arranged into a physical strip, or arranged into complex forms. The LEDs are addressed by their position in the strip. The microcontroller sends a data stream to the first LED. It will read the first 3 bytes (1 byte per color) and forward the rest of the stream to it's data output, so to the next LED.
So you can wire all the LEDs on your robot in a way, that you basically only have 1 LED strip. In this case you only need 1 pin on your Arduino (plus Vcc and ground of course).
Or, if it's to cumbersome to wire all LEDs together, you can make multiple strips, divided by zones on your robot (like 1 strip for the face, 1 strip for the chest, ...). Every strip will need it's own pin on the Arduino.
Which way you go is your decision and also depends on how many pins you have free.

My question is, is it possible to connect all the LEDs i plan to use on one microcontroller (ie: Ardruino Uno or Nano)

Yes, one microcontroller is plenty enough for this. As I wrote, for 1 strip you only need 1 data pin.

Most of the examples I can see on youtube are projects using LED strips. Are they diffrences in the way they are connected?

This depends on what strips they have. If they use WS2812B strips, it is all the same. As said, the physical arrangement of the LEDs doesn't matter. But there are also other types of strips, for example the not-individually-addressable-single-color types, or the not-individually-addressable-RGB types (which often have one PWM line per color).

Another problem is coding for the ardruino..i'm totally clueless.

Have a look at the Adafruit Neopixel library or the FastLED library (both on github). They are libraries, that will hide most of the complexity from you and will make it easy to control the LEDs. They both have examples, that you can use to get started. Adafruit also has good tutorials for this. You can google them.

For the power source, I was thinking about using a small powerbank or 2x 18650 batteries as the power source.

I don't know, how much current these batteries can give you. I will leave that to you for your research. But be sure, that you can always provide the needed current. One WS2812B LED can draw up to 60mA (20mA per color), if you set them to full brightness white. So 40 WS2812B LEDs, can draw up to 2.4A. I guess, that your robot also has motors, which can also draw a big amount of current. So keep the total current draw in mind and don't ever try to draw this current through the Arduino (since this might fry the voltage regulator).


text:
to increase the reading and writing/printing speed of data from Arduino Nano to Raspberry Pi 3B+
In my project, I have to read the input pin number(send by RPi), where 8 sensors are attached to Arduino Nano, after reading Arduino Nano send the real-time values of all sensors through serial USB communication. All is fine, but my problem is that I need to speed up the sending of data since it takes to long to read from Rasberry pi.
I put the delay of 70 milliseconds but if I try to reduce more than that, I encounter a problem i.e data overwrites. My baud rate is 115200.
Kindly help me with the code to make it fast.
int analogInputPin;
float voltage;

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(115200);
}

void loop() {
  // if any data on the serial port are available
  // read it and try to update the analogInputPin
  // based on the number that was read on the serial
  if (Serial.available() > 0) {
    analogInputPin = Serial.parseInt();
  }

  // read the analog value:
  int analogInputPinValue = analogRead(analogInputPin);
  voltage=(5./1023.)*analogInputPinValue;

  // print the results to the serial port:
  // the output should have the following form: INPUTPIN:VALUE
  // followed by a newline character
  Serial.print(analogInputPin);
  Serial.print(":");
  Serial.print(voltage);
  Serial.println("");

  // wait 50 milliseconds before the next loop
  delay(50);
}

Hint: Look at the source code for Serial.parseInt(). Consider reading to a buffer instead.

Don't use parseInt. Ever. It's rancid. Read serial properly : https://majenko.co.uk/blog/reading-serial-arduino

parseInt reads digits and stops after a non-digit characters occurs or the function times out because no next characters arrives. The timeout is at default 1 second. So this is where you loose time.
Simplest solution for your code is to send some non-digit character after the number sent from Raspberry. This will terminate parseInt immediately. Usual is to send a new line character. It will separate the numbers nice if you debug the communication with prints to serial terminal.
Not a very good option, but I mention it, is to set the timeout of blocking read functions like the parseInt to a smaller time with Serial.setTimeout(ms).
To really speed up the communication you would send the numbers in binary form and not as text like you do now.


text:
How to delegate code compilation to a remote machine?
Sometime I write Arduino code on a slow Windows laptop that I use for controlling hardware projects and 3D printing.
My main Windows computer and also my Linux home server are located somewhere else but are much faster and I would like to use those for compilation.
Remote Desktop or equivalent are not practical due to different screen resolutions. Also, my main Windows machine is not always on, only the server is, but it has no GUI installed.
The sources are already located on a shared network folder and I use an external editor for the code. Arduino IDE just does compilation and sometimes upload (which often I could do via OTA).
How to delegate compilation of Arduino projects to a remote machine?

How about using Arduino-CLI at the server and invoking it via ssh?

And using vi as your "IDE" ;)

@chrisl I wasn't aware of Arduino-CLI. You could expand and write an answer

Sound a bit like "continuous integration". Maybe look at Jenkins to run Arduino CLI when it detects changes in the samba share. Note that you also need some way to provide feedback, in case the compilation failed.

If you don't have a GUI, you can still compile and upload sketches by using the Arduino CLI. With it you can do most things, that you can do with the Arduino IDE. I'm using this myself to upload new code to a Nano, that is connected to a Raspberry Pi in a project in use.
You can connect via ssh to the remote server and let it compile/upload the sketch. I wrote a simple bash script to first copy the source to the server (since you are using a network share, this is not necessary for you) and invoke the compilation and upload.
Note: Before you can actually compile with the Arduino CLI, you have to download the correct core for your chip. This is described in the README of the linked github project.


text:
Wemos D1 won't work with MH-Z19B (CO2 sensor)
I would like to connect a CO2 sensor to the Wemos D1. I would like it to work via UART (RX, TX) and not the PWM pin. I've encountered numerous libraries on Github, but I can't seem to get it working. I've connected the following things:

I've tried a lot of snippets from all over the internet, and a lot of libraries on Github, but I can't seem to get it working. For the sake of this question, I am going to use this advanced library.
This is my code:
#include <Arduino.h>
#include "MHZ19.h"                                         // include main library
#include <SoftwareSerial.h>                                // Remove if using HardwareSerial or non-uno library compatable device

#define RX_PIN D1                                          // Rx pin which the MHZ19 Tx pin is attached to
#define TX_PIN D2                                          // Tx pin which the MHZ19 Rx pin is attached to
#define BAUDRATE 9600                                      // Native to the sensor (do not change)

MHZ19 myMHZ19;                                             // Constructor for MH-Z19 class
SoftwareSerial mySerial(RX_PIN, TX_PIN);                   // Uno example
//HardwareSerial mySerial(1);                              // ESP32 Example

unsigned long getDataTimer = 0;                             // Variable to store timer interval

void setup()
{
    Serial.begin(9600);                                     // For ESP32 baudarte is 115200 etc.
    mySerial.begin(BAUDRATE);                               // Uno example: Begin Stream with MHZ19 baudrate
    //mySerial.begin(BAUDRATE, SERIAL_8N1, RX_PIN, TX_PIN); // ESP32 Example
    myMHZ19.begin(mySerial);                                // *Important, Pass your Stream reference
    myMHZ19.autoCalibration();                              // Turn auto calibration ON (disable with autoCalibration(false))
}

void loop(){
    if (millis() - getDataTimer >= 2000)                    // Check if interval has elapsed (non-blocking delay() equivilant)
    {
        int CO2;                                            // Buffer for CO2

        /* note: getCO2() default is command "CO2 Unlimited". This returns the correct CO2 reading even
        if below background CO2 levels or above range (useful to validate sensor). You can use the
        usual documented command with getCO2(false) */

        CO2 = myMHZ19.getCO2();                             // Request CO2 (as ppm)
        Serial.print("CO2 (ppm): ");
        Serial.println(CO2);

        int8_t Temp;                                         // Buffer for temperature
        Temp = myMHZ19.getTemperature();                     // Request Temperature (as Celsius)
        Serial.print("Temperature (C): ");
        Serial.println(Temp);

        getDataTimer = millis();                            // Update interval
    }
}

I am constantly getting this:
19:39:59.750 -> !Error: Timed out waiting for response
19:39:59.784 -> !ERROR: Failed to verify connection(1) to sensor. Failed to stablise
19:39:59.853 -> !ERROR: Initial communication errorCode recieved
19:40:00.272 -> !Error: Timed out waiting for response
19:40:00.758 -> !Error: Timed out waiting for response
19:40:00.792 -> CO2 (ppm): 0
19:40:01.280 -> !Error: Timed out waiting for response
19:40:01.315 -> Temperature (C): -17

Am I connecting something wrong or what am I doing wrong?
EDIT:
Version using only the serial instead of library that also doesn't work:
#include <SoftwareSerial.h>
SoftwareSerial co2Serial(3, 1);
unsigned long startTime = millis();

void setup() {
  Serial.begin(9600);
  co2Serial.begin(9600);
  pinMode(9, INPUT);
}

void loop() {
  Serial.println("------------------------------");
  Serial.print("Time from start: ");
  Serial.print((millis() - startTime) / 1000);
  Serial.println(" s");
  int ppm_uart = readCO2UART();
  delay(5000);
}

int readCO2UART(){
  byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
  byte response[9]; // for answer

  Serial.println("Sending CO2 request...");
  co2Serial.write(cmd, 9); //request PPM CO2

  // clear the buffer
  memset(response, 0, 9);
  int i = 0;
  while (co2Serial.available() == 0) {
    Serial.print("Waiting for response ");
    Serial.print(i);
    Serial.println(" s");
    delay(1000);
    i++;
  }

  if (co2Serial.available() > 0) {
      co2Serial.readBytes(response, 9);
  }

  // print out the response in hexa
  for (int i = 0; i < 9; i++) {
    Serial.print(String(response[i], HEX));
    Serial.print("   ");
  }
  Serial.println("");

  // checksum
  byte check = getCheckSum(response);
  if (response[8] != check) {
    Serial.println("Checksum not OK!");
    Serial.print("Received: ");
    Serial.println(response[8]);
    Serial.print("Should be: ");
    Serial.println(check);
  }

  // ppm
  int ppm_uart = 256 * (int)response[2] + response[3];
  Serial.print("PPM UART: ");
  Serial.println(ppm_uart);

  // temp
  byte temp = response[4] - 40;
  Serial.print("Temperature? ");
  Serial.println(temp);

  // status
  byte status = response[5];
  Serial.print("Status? ");
  Serial.println(status);
  if (status == 0x40) {
    Serial.println("Status OK");
  }

  return ppm_uart;
}

byte getCheckSum(byte *packet) {
  byte i;
  unsigned char checksum = 0;
  for (i = 1; i < 8; i++) {
    checksum += packet[i];
  }
  checksum = 0xff - checksum;
  checksum += 1;
  return checksum;
}

You do know you need to cross RX and TX with UART communications, don't you?  TX connects to RX, and RX connects to TX.

I know, tried it both ways (drew it wrong in this picture), neither works

did you try to send the commands without using a MHZ19 library?

Yes, also no response, see the edit

I know it is rather late to respond. What worked for me working with a WEMOS D1 mini and  the MH-Z19C was reassigning the Software Pins used SoftwareSerial co2Serial(D1, D2);
In that case the second sketch posted works atleast for me.
The problem might be that the ESP8266 uses the hardware serial lines for connection to the USB-to-Serial bridge (usually a CH340 or CP2102 in most designs) which means you might encounter problems if you want to use the same serial line for more than one device.


text:
How to return Char Array Value in Arduino IDE Function?
Function
char* getConnectDetail(int starting){
  String data;
  for(int i=0;i< 1024 ;i++) {
    if(EEPROM.read(i+starting) != 0){
    data += char(EEPROM.read(i+starting));
    }
   }

   int str_len = data.length() + 1;
  char char_array[str_len];
  data.toCharArray(char_array, str_len);
  return char_array;
}

When I call it I get the garbage value... without creating the function there isn't any error.. Kindly solve it.
I just want to know whats wrong with my returning method.

for future help with your internet searches, it is not an Arduino IDE function ... it is a C++ function

char char_array[str_len]; is local to the function - it is created on function entry and its memory is released on function exit. The contents of that memory are undefined once it has been released and its data may or may not be valid.
If the caller creates data and passes it to the function, it survives the entire function call-and-return, and the caller will find the correct data in it. Another (less elegant) way to do it is to make data a global object, which again, gives it a lifetime greater that that of the function, but globals are subject to accidental over-writes and abuse by other functions, so they are not recommended unless they are truly the best solution in a given situation.

Good answer. Another alternative is to have the function malloc memory for the array and return that. Then the caller would be responsible for freeing it when it was done with it.

Also note that the OPs function will have to return the length of the string array somehow.

Since it no longer has to return the array (caller owns it), the return value is available to return a count or error code.


text:
Why Won't my Serial Read value stay the same
I am trying to write to serial to control the brightness of an LED. When I initially type in a value such as '50' or '100', the LED lights up, but then the 'ppm' value drops down to '10' and just stays there (regardless of what I enter in initially. Any idea why this is occurring?

int ledpin1 = 3;
int pwm = 0;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(ledpin1, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // reads input to serial monitor
  if (Serial.available() > 0) {
    pwm = Serial.read();
  }

  analogWrite(ledpin1, pwm);
  Serial.print("PWM value is: ");
  Serial.println(pwm);
  delay(1000);

}

When you type "100" you aren't sending the number 100. You're sending the characters "1", "0", "0", and whatever selected line ending you have (CR, LF, or CR and LF).
So if you have CR+LF for your line ending you're reading the numbers 49, 48, 48, 13 then 10.
You need to read the characters as they arrive and group them into a representation of the number (up until you get the line ending), then convert that representation into an actual number.

Reading Serial on the Arduino

"You need to read the characters ..., then convert that representation into an actual number." - Or send just a single byte of value 100 over the serial port, effectively moving the conversion from the arduino to the PC. Which is more appropriate depends on the situation.


text:
How to stop the screeching noise that comes from buzzer?

I use sfm-27 dc 3-24v Buzzer. It sounds fine if i close the buzzer using my palm but if i doesn't close it, it will make a screeching noise. I play melody using the buzzer so the sound is important. This is the code that i use.

    const int buzzer = 4; //Define pin 13, can use other PWM pins  (5,6 or 9)
                       //Note pins 3 and 11 can't be used when using the tone function in Arduino Uno
const int songspeed = 1.5; //Change to 2 for a slower version of the song, the bigger the number the slower the song
//*****************************************
#define NOTE_C4  262   //Defining note frequency
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_G5  784
#define NOTE_A5  880
#define NOTE_B5  988
//*****************************************
int notes[] = {       //Note of the song, 0 is a rest/pulse
   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
   NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
   NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_D5, NOTE_E5, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
   NOTE_C5, NOTE_A4, NOTE_B4, 0,

   NOTE_A4, NOTE_A4,
   //Repeat of first part
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
   NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
   NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_D5, NOTE_E5, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
   NOTE_C5, NOTE_A4, NOTE_B4, 0,
   //End of Repeat

   NOTE_E5, 0, 0, NOTE_F5, 0, 0,
   NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
   NOTE_D5, 0, 0, NOTE_C5, 0, 0,
   NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4,

   NOTE_E5, 0, 0, NOTE_F5, 0, 0,
   NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
   NOTE_D5, 0, 0, NOTE_C5, 0, 0,
   NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4
};
//*****************************************
int duration[] = {         //duration of each note (in ms) Quarter Note is set to 250 ms
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 125, 250, 125,

  125, 125, 250, 125, 125,
  250, 125, 250, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 375,

  250, 125,
  //Rpeat of First Part
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 125, 250, 125,

  125, 125, 250, 125, 125,
  250, 125, 250, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 375,
  //End of Repeat

  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 125, 125, 125, 375,
  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 500,

  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 125, 125, 125, 375,
  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 500
};

void setup() {
  for (int i=0;i<203;i++){              //203 is the total number of music notes in the song
  int wait = duration[i] * songspeed;
  tone(buzzer,notes[i],wait);          //tone(pin,frequency,duration)
  delay(wait);}                        //delay is used so it doesn't go to the next loop before tone is finished playing
  //You can click reset on Arduino to replay the song
}

void loop() {

}

you probaby cannot ... most likely the buzzer is not for playing music ... apply DC voltage and it buzzes ... apply AC voltage and you hear rhe buzz modulated at the frequency of the voltage

ok thank you so much.


text:
Callback functions when using a class
This question is somewhat similar to How to pass non-static class member to callback?, but there are a few differences, especially since a lot of my uses have "interesting" additional complexities. I'd like to understand better my options in using them, since I have not gained enough understanding from other answers (and I need to write both the callback and the function that calls it).
I have a number of libraries that produce "events" that I'd like to be able to write separate classes or functions to respond to (so I don't need to customize every library every time I develop something). The annoying part is that I've long-since discovered the this pointer that's hidden in class method calls, which prevents me from passing currentgui.leftbutton as a function to menu.leftbuttonpressed(void (*callbackfuncptr)(void)).
I'm also using the ESP8266 web server library, which needs a callback in the context of the server object that can call the server as a global to actually get the data sent to it! (Unless the server passes its own this as a parameter to the callback, which I don't know since the documentation consists almost solely of a small number of "examples" which don't show the majority of the actual features of the web server, rather than a real explanation.)
I could use some variant of a pointer to a class method, but the syntax for that is eye-gouging and I'm using more than one class to provide callbacks to (especially for the task scheduler), so this would require customizing the library to handle pointers to every class I use again. I can't use polymorphism, either, since some classes contain multiple scheduler callbacks to be done on different times/conditions.
How do I handle these callbacks? My current method is to write a function that wraps the method's function, but that relies on a specific instance of that method, so it can't be reused. It's also really awkward since I'm now dealing with multiple functions/methods that are now very similar.
I would also like to be able to have a class, that when passed a web server object, registers itself as a callback to a particular page event (I want to write a network connection manager similar to the WiFiManager library, but with the ability to integrate with an existing webpage. I have all the code, but it currently can't be nicely integrated into a standalone class because of this issue). It needs to store a pointer to the server object to get the data once the callback's called, but it also needs to be attached to the callback of the class that holds that particular pointer AND the other handler functions once the data's retrieved.
There is already a library that does something similar, but I can't figure out at all how this works, since I was under the impression that this is not possible. Can someone help me understand how the following class operates?
https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPUpdateServer/src

Can you clarify ... if the server needs a callback, and you provide a callback, are you expecting to access server variables or functions? If so, your callback would need to be derived from the server class would it not? Can someone help me understand how the following class operates - this is rather a broad question. A quick glance seems to show it is using lambda functions and templates, but apart from that I think you will need to narrow down what it is you want to know.

the ESP8266HTTPUpdateServer registers a lambda function as server->on handler. a lambda function is not a member of a class

The Object-Oriented Programming (OOP) way of doing this is to use virtual member functions and subclassing. This allows access to the member data. A callback will require the object as a parameter but will not have access to private or protected member data or functions.

@NickGammon, It uses normal functions, not ones that derive from the class. They call the same instance of the class' member functions to get data back. I'd like to know how to get a class I wrote (nothing special about it, but how do I connect it?) to register itself as a callback so IT gets data and I don't need a bunch of disconnected non-class functions around.

@Juraj, I begin to think that might be it. Can you post an answer explaining more and how exactly they did that? If the function is inline but not part of the class, that would work, I think... But how do they still get access to class members in it?

@MikaelPatel I've done that for my menuing system, but it doesn't really apply here? I can only access inherited members if they exist in the parent, so I can't easily do more than one entry point (let alone name them all well) for subclasses, and at very minimum the web server won't take polymorphic child classes, since it just accepts vanilla callback functions instead. Friend functions are also rather a problem.

The ESP8266WebServer uses callback functions to handle HTTP request by your code. This callback functions can't be members of a class. But you can use anonymous functions to implement this callbacks. And if you like you can implement them as 'redirects' to functions of your objects.
server.on("/leftbutton", []() {
  currentgui.leftbutton(server);
}

Note: this anonymous functions are called lambda functions and they can do some tricks with parameters too

Bonus Internet points for the link. Looks like I need to figure out how those capture clauses work, though, since it looks like that example uses them...
Thanks!

I have since run into issues doing this with my own callback-accepting functions, as it would appear that lambdas have a compiler-defined type. How do I write callback-handling code that can take a lambda?

They call the same instance of the class' member functions to get data back.

Yes, but if they eventually call the class' member function to get data, other than static data, then the need to know what instance of the class to get the data from.

I'd like to know how to get a class I wrote (nothing special about it, but how do I connect it?) to register itself as a callback so IT gets data and I don't need a bunch of disconnected non-class functions around

If function X (not a member of this class) needs to be able to access the data from instance A or instance B then clearly X needs to know which instance it is looking at (the this pointer). This is not a syntax thing, you need to have a way of solving this problem.
In fact, when you say "a class I wrote" then that would also have instance data (its own this) so now you are trying to connect two instances of two classes.
How many server objects do you have? If just one in this particular case you might be able to fudge your way around it by storing its this somewhere, or making some glue routines.

Yes, but if they eventually call the class' member function to get data, other than static data, then the need to know what instance of the class to get the data from. -- yes, that's the problem. I need to store the this per-instance of MY class, but also connect a member of my class TO its callback, so the callback gets my instance that can access ITS instance!
Connecting two instances of two classes -- yes, exactly. There should be a way to do this, right? Someone said something about lambda functions being used in the existing example, but I don't understand what they did.

A lambda function is just an anonymous function. That is, you can put a lambda function "inline" instead of having to name a function declared elsewhere. Other than that, they don't help solve this problem. I think you need to make up an example and edit that into your question. And to be honest I think this is a pure C++ problem, which might be better asked at Stack Overflow. The fact that it is an Arduino is irrelevant to the issue of what you are trying to do with classes and instances of classes.

That might be a fair point. I was uncertain, though, if there might be some extra method that Arduino happened to use or implement that might make this easier.

@RDragonrydr Arduino just uses g++ - the industry-standard compiler (or one of them, anyway). There is no special "Arduino" functionality that you can call on.

I was thinking that maybe they overloaded the callback registering function, or some other method that would simplify it. I'm just using the lambdas now, though...


text:
ESPAsyncWebServer how do you escape the % character?
% characters are used for template processing but I want it to just send the % through. How do you tell it to do that?

Can you please add some more context. Thanks.

You'd use %% to get a single % as output.
From the source code: double percent sign encountered, this is single percent sign escaped.

Thank you. Biyaaaaaa!


text:
Why does a function inside void set up is repeating after some minutes
I am trying to time sync my arduino hardware to NTP server. I have a `setSyncProvider(getNtpTime)´ function to do it and called inside the void setup. I have another function (mainFunction) inside the main loop, that calls every minute. I have added a function to display time inside this mainFunction so that time will update every minutes.  Code works fine for first five minutes. Then it calls the getNtpTime again even though it is not inside the loop. Why is it happening?

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

Arduino is resetting for some reason?

But no other functions inside void set was repeated. If Arduino was resetting, everything inside setup should have repeated, right?

i have this millis() function inside getNtpTime() and mainFunction(). any possibility of conflicts?

The setSyncProvider function of the TimeLib sets a function which will be called by the library every interval seconds. The interval is set with setSyncInterval. Default interval is 300 seconds.

I checked the time of calls in serial monitor. As i mentioned in the question, my main loop has a function that calls every minute. in the main loop getNtpTime called at 360.8 second   and then at 660.8. After first call, there was no display error. But after second call, there was display error. Display returned to normal in the next minute and the above cycle of error repeated. That means 3rd call was fine, 4 gives error. 5th was fine, 6th gives error! Any suggestions

try a little longer wait time


text:
Creating global webserver without port forwarding
I'm setting up a "Smart House" project with Arduino+Esp01F(Serial Communication).
But I want to make it global server. For it I use WiFiEsp library. But for it I must Get any port (neither 80 nor 443), then make port forwarding on router. But there are no port forwarding in my router. I think how can I do it?
Code:
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif
 String response = "";
char ssid[] = "Nazim";            // your network SSID (name)
char pass[] = "eminmamedov1";         // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(5000);

 WiFiEspClient client;

void setup() {
Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
Serial.println(WiFi.localIP());

WiFi.config(IPAddress(192,168,0,165));
  // start the web server on port 80
  server.begin();

}

void loop() {
   WiFiEspClient client = server.available();
   if(client){
    String res = "";
     Serial.println("New client");
      while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        res+=c;

        if (c == '\n') {
          Serial.println("Sending response");
           client.print(
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
               "\r\n");
               if(res.indexOf("on?") >=0){
               int s = res.indexOf("on?")+7;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  pinMode(i,OUTPUT);
                  digitalWrite(i,HIGH);
                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
                 }else{
                  client.println("ERROR\r\n");
                 }
               }else if(res.indexOf("off?") >=0){
                 int s = res.indexOf("off?")+8;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  pinMode(i,OUTPUT);
                  digitalWrite(i,LOW);
                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
                 }else{
                  client.println("ERROR\r\n");
                 }
               }else if(res.indexOf("state?") >=0){
                 int s = res.indexOf("state?")+9;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
               }
               }

                   client.stop();

      }
      }

   }

}

You can't. Get a better router.

The ESP does only provide the server. The traffic from and to that server has to be routed between your local network and the internet. That is, what a router is for. You need a better one

I heard there is the IP Cameras without port forwarding(it works without por). I thought that was p2p but No. How can I realize it in my ketch

use the DMZ setting in the router to expose your server to the internet

@TheGamerCoder You may be talking about UPnP which can configure port forwarding for you. Or there are cameras that communicate with a service on the internet so need no port forwarding (they connect outwards).  If your router supports UPnP (why it would support that and not port forwarding would be a mystery) then maybe you could do it with that.  See this question

Incidentally, to do that you will have to give up the idea of using the AT command set and trying to get it working with an Arduino, and program the ESP8266 directly.

Can I use for it Esp01f adapter?

Only if you program it directly instead of using an Arduino as I said above.

Can I use UPnP Tiny library with WiFiEsp?

use web sockets and an always-on cloud server for 2-way non-ported real time communication.

What? How to use it? And Can I use it with WiFiEsp + TinyUPnP

What part of "Only if you program it directly instead of using an Arduino" don't you understand?

STOP. I understand. But how to use WEBSOCKETS and ALWAYS-ON CLOUD SERVER I didn't understand

@TheGamerCoder Use @ followed by a username to direct your comments at a particular user.

I mean how to realize @dandavis said

typically, you need a VPS to run a websocker server on. there's some free VPS options, and a few hosted websocket server options, like pubnub and pusher.

@dandavis Thanks  for information, but how can  I add VPS to wifi sketch


text:
SIM800L HTTP request is not reliable
I have a question regarding SIM800L and HTTP GET request. I'm using this https://exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L simple code to communicate with SIM800l with AT commands. To perform the HTTP request, I use the following set of AT commands:
AT+CFUN=1
OK

AT+CSTT="internet","",""
OK

AT+CIICR
OK

AT+CIFSR
10.180.xxx.xx

AT+CIPSTART="TCP","84.42.xxx.xx",80
OK

CONNECT OK

AT+CIPSEND=52
>
GET /bakalarka.php/? HTTP/1.1
Host:84.42.xxx.xx

SEND OK
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 16:20:27 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

10
time201908191820
0

CLOSED

The problem is that sometimes. Or every other time, I don't get the whole HTTP answer. I usually get only the beginning. Something like this:
AT+CIPSEND=52
>
GET /bakalarka.php/? HTTP/1.1
Host:84.42.xxx.xx

SEND OK
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 16:20:27 GMT
Server: Apac

and then after a couple of seconds, the connection closes.
CLOSED

Do you know what could cause that? It's literally random. I need the information from the webpage (it's the current time) and currently, it's really unreliable.
Another question. What does the "10" and "0" mean in the HTTP request? The "time201908191820" is the current time from printed from PHP.
Thank you very much!

Thank you for your answer. The code is as follows:
#include <SoftwareSerial.h>

String Arsp, Grsp;
SoftwareSerial gsm(12, 8); // RX, TX

String GET = "GET /bakalarka.php/? HTTP/1.1\r\nHost:84.42.xxx.xx\r\n\r\n";

void setup() {

  Serial.begin(115200);
  Serial.println("Testing GSM SIM800L");
  gsm.begin(19200);

}

void loop() {

  AT("AT+CFUN=1");
  AT("AT+CSTT=\"internet\",\"\",\"\"");
  AT("AT+CIICR");
  AT("AT+CIFSR");
  AT("AT+CIPSTART=\"TCP\",\"84.42.xxx.xx\",80");

  int get_length;
  get_length = GET.length();

  AT("AT+CIPSEND=" + String(get_length));
  AT(GET);
}

void AT(String AT){

  gsm.println(AT);

  if(gsm.available()){

    Grsp = gsm.readString();
    Serial.println(Grsp);
  }
}

I was thinking about a couple of things that could cause this.
1. Hardware design - some noise could cause a freeze of the GSM module while getting the answer from the server. After thinking through I don't think it's likely to be that. The power supply is made to be really beefy and there are enough bypass caps to reduce the noise and provide enough energy during current spikes. Also, the module doesn't freeze. It's still connected to the server, after a couple of seconds it closes the connection exactly as it should be.

Serial buffer gets somehow full. This was just a quick thought. The buffer of Arduino could get somehow full so it's not able to save any more incoming data. I think it's nonsense, but...

Thank you for your answers.
Krystof

I've figured it out. The answer to HTTP GET request was read as a string. The string has aroud 284 bytes. Since it's so big, string gets to be saved fragmented, which is apparently a problem. The solution is to create a buffer and save the characters there from the Serial.

Do you know what could cause that? It's literally random.

Could be your code, could be your network provider / signal. It's impossible to tell without you providing your code for us to inspect.

Another question. What does the "10" and "0" mean in the HTTP request? The "time201908191820" is current time from printed from PHP.

Those look to be part of the response body - so they are printed by whatever the PHP script is that you are requesting. Either that or they are generated by your undisclosed Arduino program.


text:
control 3 relays with 1 button
Is there a way to control 3 relays with 1 button?
My idea is: There are 3 modes; mode 1 for relay 1, mode 2 for relay 2 and mode 3 for relay 3.
With a long press you switch between modes (After 3 comes 1) and with a short press you activate the relay which is in the activated mode.
I need this for my wheelchair so please help me.
Thank you, Michael

Further question:
Does the relays really need a external power supply?
Because I have a small amount of power to control with the relays.

you asked only one question ... the answer is "yes" .... is that what you really wanted to ask?

What do you need to control? If the thing you need to control takes DC, and it's voltage and current needs are reasonable, you might be able to control them using MOSFET transistors rather than relays. You could power those just fine from the Arduino's voltage regulator

Sure you can. This site isn't a great place for open-ended questions like this though. Since you have a serious real-world need I'll give you some guidance anyway.
You'd need to break it into pieces and solve each one in turn.
First create code that recognizes long and short presses (not using delay().) You'll probably want to respond on releasing the button, since at that point it's easy to tell if it was a long or a short press.
The pseudo-code might look something like this:
void loop()
   if button_is_pressed
      if !press_in_progress
         press_in_progress = true
         start = millis()
   else
      if press_in_progress //Button has been released
         elapsed = millis() - start
         press_in_progress = false
         if elapsed > long_press_threshold
            long_press_function()
         else
            short_press_function()

For controlling the relays, I suggest getting "digital" relays that are made to be controlled with 5V logic signals. Relays like this work well. (Link). Since you need to control 4 relays, a 4 channel model like this one would be a better choice. Note that you'll need a fairly high current power supply. A 2A 5V regulated supply should be plenty for both your Arduino and your relays, although it's more of a sure thing if you use separate power supplies for the arduino and the relays (that way the voltage to the arduino doesn't bounce around as the relays energize and de-energize.
You'll need a global variable for the currently active relay. The long press would increment that value modulo 4: (going from 0 to 3 and then back to 0)
relay_index = (relay_index + 1) % 4;

You'd need an array of 4 bools for the states of each relay:
bool relay_states[4];

The short press would toggle the state of the current relay
relay_states[relay_index] = !relay_states[relay_index];

Note that if you're more interested in solving your wheelchair problem cost-effectively than tinkering, this is the sort of thing that a maker space would be ideal for. There are lots of tinkerers there who love a challenge, and would likely pitch in and help you.

You posted an answer to your question asking if you really need an external power supply. Don't do that. Post a comment on my answer. But the answer is "very likely". Each relay draws 50-60 mA. At 60 mA, that's 240 mA just for the relays. You might be able to get away with powering that from the 5V supply on the Arduino, but as the relays energize and de-energize they will cause dips and spikes in the voltage from the supply, as the supply tries to adjust to the varying load. You can try it, and if you have problems like the Arduino restarting, switch to a higher current external supply.

Note that you should NOT use bare relays. You want relays that are made to be driven from logic signals and have built in transistors and flyback diodes. (Bare relays will almost certainly fry the Arduino used to control them.)

@MichaelMesser Consider buying a relay driver board such as this one:  Arduino Compatible 4 Channel 12V Relay Module

@sa_leinad I included a link to a 5V 5 channel relay module in my answer.

Can I use a powerbank as a powersupply?

@DuncanC, so you did. Sorry I missed that.

I would not recommend using a powerbank because those consume power just to maintain 5V. It's probably better to buy 12V rlays like those shown by sa__leinad, and use a 12V lead-acid battery on your chair. Those store a large number of amp-hours, and have good shelf-life.

Then you can get a 5V switching power supply, attach it to the 12V battery and feed it's output into the USB connector on your Arduino. That way you have a large capacity, high efficiency way to power your Arduino.

Its a little complicated to use the battery from the wheelchair, so I'd like to use a 5v external power supply.

Can I use this relays too: https://www.amazon.de/Boladge-4-Kan%C3%A4le-Steuerschalter-Treiber-Raspberry/dp/B0734P228K/ref=asc_df_B0734P228K/?tag=googshopde-21&linkCode=df0&hvadid=231932152232&hvpos=1o2&hvnetw=g&hvrand=8055025540693799388&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9068490&hvtargid=pla-613740420672&psc=1&th=1&psc=1

Cause I'm from Germany

If you have a high enough capacity power bank that will work but it will need to be recharged pretty regularly. A 12V lead-acid battery, and a 5V switching power supply would give you MUCH longer running time.

@DuncanC do you know where i can find someone programming it for me?

Yes, it is possible to do that and there are libraries for that purpose. Check for example  ObjecButton library, which supports click, press and double click action. It is well documented and comes with many examples...
And does the relays really need a external power supply? It depends, what kind of relays you want to use, what kind of power supply is available on wheelchair, what is the load switched by these relays and so on...

The load switched by the relays is really low. Are there alternatives for a relay which have the same function, but a lower power consumption for switching on and off?

Yes, there are. For DC load use transistors, for AC load use e.g. triacs or SSR relays. There is plenty Arduino modules on the market with these kind of switching "elements".


text:
Can I use an RF Receiver to any pin on an Arduino?
I have a project that uses a nodemcu and it includes an rf receiver, I created the pcb board already etc etc... so I've already chosen D7 (GPI013) before reading on connecting the rf receiver and found that a lot of people are saying to connect it to the interrupt pin and for the case of an Arduino it was pin 2 and for the nodemcu it's D3 (GPIO0).
UPDATE: the pin in question is the data pin for the rf receiver, this would be connected to D7 (GPIO13) because of the trace on the board. it is purely used for receiving the data it picks up and giving it to the nodemcu to handle.
Can I just use a different pin which in my example is D7 (GPIO13) or does it HAVE to be an interrupt pin?
Side note: I'm aware of the advantage of using an interrupt pin where that it takes priority over code running.

What does the pin do?  Is it used to notify the program that data is ready? if so, then you will have to poll that pin rather then take advantage of an interrupt, and this will be a bit slower, but I have no idea if that will effect your project since we dont know what your project is, or what that pin is even doing.

you did not say what is the purpose of the pin in question

you can hook it to the ESP, which can use any pin as an interrupt, and side-steps the middle man uno.

Thank you @dandavis how would I go about using D7 (GPIO13) as the pin interrupt in this case, when testing with the uno I would just define the enablereceiver as 0 which equals pin 2 on the board using RC Switch.


text:
How to program micro chips directly with USB
Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?
Where can i find information on the protocols/standards to do such a thing?
More specifically, I want to be able to make a custom pcb for my Attiny85 chips with a usb connector. I would prefer not to use the arduino IDE.
Is it possible to program this chip like so?

The short answer is no.  The longer answer is maybe if you are willing to make some compromises.  USB is not a simple protocol and requires considerable hardware and software.  In a nut shell, the compromise will likely come in the form that much of your embedded processor's resources will be devoted to supporting the USB port.  Further you will likely have to handle programming the embedded processor similar to a field update or upgrade.  Much effort for small benefits.

Thanks for the helpful comment @st2000. Im not sure if you are familiar with the Digispark Attiny85. The serial usb pins are connected directly to the uC pins 2 and 3. Do you know how they achieved this?

If RS232 can be described in 4 or 5 sheets of type, then USB is so complex that it requires a book.  That said, you can just get by w/only software if you constrain your self to a simple USB peripheral type of a device.  Try reading this.

adafruit has attiny with usb bootloader https://cdn-learn.adafruit.com/downloads/pdf/introducing-trinket.pdf

@st2000 Your "short answer" should be posted as an answer. Stack Exchange considers this question unanswered right now, which looks bad for this site. I like your "answer" except it's not an answer. It's a comment, which is supposed to be used to get the OP to clarify what s/he wants.

https://learn.adafruit.com/introducing-trinket/starting-the-bootloader

Thanks @NickGammon.  I'll keep this in mind for the next one.  Majenko has done a good job covering this question.

Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

The bare chip? Generally, no.
Some chips that include USB hardware also may include a DFU bootloader in ROM. If your chosen chip has this, then yes you can - you just need to wire it up and use a suitable DFU firmware upload program to install your compiled code into the chip.
However chips that don't have USB will never have a USB DFU bootloader in them. In such cases is is your responsibility to create (or otherwise obtain) a suitable bootloader that you will install into the chip.
Digispark and Adafruit both do that.  They take a chip that doesn't have USB and install software that tries to (poorly) emulate USB over GPIO pins1.
For chips that do not have actual USB hardware in them it is far more common to use a UART-based bootloader - simply because this is a much lighter and more "correct" way of doing it.
If you want to use a direct USB connection for your device you should be selecting a chip that has USB built into it (AVR "U" series2, most PIC32, many ARM-based chips) which will allow you to have proper USB communication instead of slow HID and custom (non-standard) protocols only3.
Note that at no point does your choice of bootloader, or method of communication with the bootloader, tie you in to using the Arduino IDE.  The IDE just compiles the code then runs an external program that communicates with the bootloader (different bootloaders need different programs to communicate with them). How you compile the software is up to you. How you execute the bootloader upload program is up to you.

Personally I think that's a horrible idea and should NEVER be done. I'm a purist though.
Such as the ATMega32U4 used on the Leonardo and Micro boards.
VUSB can only (barely) run fast enough for USB 1.1. That means only HID protocols are officially supported (keyboard and mouse), and anything else is non-standard and requires special supporting software to work with it.

So what youre saying is if I really wanted to create a custom pcb with a usb connector to program, I can either add a UART to USB converter or choose a chip with built in usb?
Otherwise there is the slow HID software option... If i were to go with that option where can i find info on the software to do this?

That would be the normal way. Having a UART header on a board is more common than you'd think - even if you have USB available.

I think we are all thinking you should not sacrifice performance of the embedded processor by always supporting a USB port (even when you are not using it).  The real Arduino and it's knock offs use a support chip (FTDI or 2nd processor w/a USB port built in).  This only cost a few dollars if that and allows the embedded processor to run a minimal Arduino program to support down loading new applications.  (The cable in another answer is supposed to have the FTDI chip inside it.)  BTW, didn't I point you to the HAD article w/the HID project?  That's where you would go to learn more.

Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

Put a bootloader on the chip first, then an offboard USB/Serial adapter can be used for the serial programming.   That's basically what a ProMini is - a bootloaded '328P (in SMD form) with a resonator & decoupling caps and a small voltage regulator - and a header to accept an FTDI Basic for programming serially.  If you notice the Black and Green colors next to the FTDI header, those are to match the wire colors on the the FTDI cables that were originally used, before seperate USB cable and FTDI modules became more popular.
https://www.sparkfun.com/products/9718

Instead of the 6-pin FTDI header, you could make an adapter board to go from FTDI to a USB-A 5-pin connector, then on your board have a USB-B-Mini or USB-B-Micro 5-pin connector to bring in the FTDI's 5V, Gnd, DTR, Tx, and Rx signals.
USB wouldn't be coming in directly, but you would have the spacing advantage of the small USB connector, and could program serially from a PC USB port.
Too bad you don't want to use the Arduino IDE, there are supported core codes to add to the IDE for the Attiny85 and other chips like that. Attiny85 with bootloader could then be serially programmed with an offboard USB/Serial adapter.
https://github.com/SpenceKonde/ATTinyCore

ATtinyCore Universal
This core supports the following processors - essentially every ATtiny processor that makes sense to use with Arduino. Click the processor name for part-specific information:
ATtiny2313, 4313
ATtiny24, 44, 84 (With or without Optiboot bootloader)
ATtiny25, 45, 85 (With or without Optiboot bootloader)
ATtiny261, 461, 861 (With or without Optiboot bootloader)
ATTiny87, 167 (with or without Optiboot bootloader)
ATTiny48, 88 (With or without Optiboot bootloader)
ATTiny441, 841 (With or without Optiboot bootloader)
ATTiny1634 (With or without Optiboot bootloader)
ATTiny828 (With or without Optiboot bootloader)
ATtiny43 (no bootloader)

Thanks for your excellent answer. I will use the Arduino if it makes my life a whole lot easier. With the usb to FTDI cable you can directly program the Attiny with the help of the github link?

Yes, just add the cores to the IDE.  You will need a Programmer to put the Bootload code into the chip; The FTDI route can be used after that.  A Programmer connects to the Reset (2), SCK (7), MISO (6), and MOSI (5) pins to access the bootload memory area.

I can just use Arduino as programmer right? And programming the chip will automatically remove the previous bootloader from the chip if there is one?

Yes, you can use Arduino as ISP or whatever it's called these days.  I have an Atmel AVRISP MKii for a Programmer, so I don't need to fool around with loading a program into an Uno to use it as  a Programmer.