message:
Alternative to a delay so it can be interrupted

I have task which includes a 30s delay in the void loop. During this delay I want to be able to press a key on a keypad and have a message displayed on the serial monitor as an emergency stop. Since delays block code until they are done I thought I would be able to break them down into smaller sections so I could still press the emergency stop key in between them but of course that doesn't work. I've read through how to use the milis() function but from what I can gather it seems like it wouldn't work for my system as I need user input for it so the time from the start of the Arduino to me pressing the emergency stop button is different every time. Is there a way that isn't too complicated and would allow me to press the button during that 30s?

The delay is in if (key == '2') and the last part of the sketch is the emergency stop.
```
const int greenLED = 13;  //Declares greenLED as being connected to D13
const int redLED = 12;    //Declares redLED as being connected to D12
//
const int ButtonT1 = 11;    //Declare pin number for ButtonT1 as D11
int ButtonT1State = 0;      //Variable for reading ButtonT1 state
const int ButtonT2 = 10;    //Declare pin number for ButtonT2 as D10
int ButtonT2State = 0;      //Variable for reading ButtonT2 state
//
int count_value1 = 0;       //Variable for storing counter value for turnstile 1
int count_value2 = 0;       //Variable for storing counter value for turnstile 2
//
const byte ROWS = 4;        //Four row matrix
const byte COLS = 4;        //Four columns matrix
char keys [ROWS] [COLS] = { //Defines symbols on buttons of keypad
  {'1','2','3','A'},        //Defines ROW 1
  {'4','5','6','B'},        //Defines ROW 2
  {'7','8','9','C'},        //Defines ROW 3
  {'*','0','#','D'}};       //Defines ROW 4
  byte rowPins[ROWS] = {9, 8, 7, 6};  //Pin numbres of row pinouts of the keypad
  byte colPins[COLS] = {5, 4, 3, 2};  //Pin numbers of column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
//
void setup() { //Begin void setup, code runs once
 Serial.begin(9600);      //Begin serial transmission
 Wire.begin();            //Begin I2C wire communication protocol
 lcd.begin(16,2);         //Begin LCD with 16 columns and 2 rows
//
 pinMode(greenLED, OUTPUT);  //Set greenLED as an OUTPUT
 pinMode(redLED, OUTPUT);    //Set redLED as an OUTPUT
 pinMode(ButtonT1, INPUT);   //Set ButtonT1 as an INPUT
 pinMode(ButtonT2, INPUT);   //Set ButtonT2 as an INPUT
}
//
void loop() {                               //Begin void loop
   char key = keypad.getKey();              //Get a character key from the keypad
//
   //counter 1
    ButtonT1State = digitalRead(ButtonT1);  //Read the state of ButtonT1 -
    if (ButtonT1State == HIGH){             //Begin IF ButtonT1State is HIGH
      count_value1++;                       //IF buttonT1 pressed, increase count value
      Serial.println(count_value1);         //Print count_value1 on serial monitor
      delay(200);                           //Delay for 200ms, 0.2s
      digitalWrite(greenLED,HIGH);          //Set greenLED to HIGH,ON
      digitalWrite(redLED,LOW);             //Set redLED to LOW, OFF
 //
     if (key == '1'){                         //Wait until key '1' is pressed
    }                                         //End IF key == '1'
    ButtonT2State = digitalRead(ButtonT2);   //Read ButtonT2 state
    if (ButtonT2State == HIGH){              //Check if ButtonT2State is == HIGH
      count_value2++;                        //IF buttonT1 pressed, increase count value
      Serial.println(count_value2);          //Print count_value2 on serial monitor
      delay(500);                            //Delay for 500ms, 0.5s
//
    if(key == '2'){                            //Wait untill key '2' is pressed - confirm ride is ready
      Serial.println("Ride starting - 30s");   //Print message in brackets on serial monitor
//30s delay, broken into smaller delays
      delay(10000);
     Serial.println("20s left");
      delay(10000);
      Serial.println("10s left");
      delay(10000);
      Serial.println("Ride finished");        //Print message in brackets on serial monitor
      delay(100);                             //Delay for 1000ms, 1s
    }                                         //End if key == '2'
//
    if (key == '4'){                        //Wait until key '4' is pressed - emergency stop
      Serial.println("Emergency stop");     //Print message in brackets on serial monitor
      digitalWrite(redLED,HIGH);            //Set redLED to HIGH,ON
      digitalWrite(greenLED,LOW);           //Set greenLED to LOW,OFF
      lcd.clear();                          //Clear i2c LCD
      lcd.setCursor(0,0);                   //Set cursor to column 0, row 0
      lcd.print("Emergency stop");          //Print message in brackets on i2c LCD
      count_value2 = 0;                     //Set count_value2 to 0
      delay(1000);                          //Delay for 1000ms, 1s
    }                                       //End IF key == '4'
}
```

body:
Make a statemachine.

Take a piece of paper and draw out the order of operation and each time you are waiting you specify what each button will do.

So for example each time button 1 is pushed you increment the counter and change the display.

When waiting for a timeout you check `if(startTimestamp - millis() > timeout)` for the next step.

Then give each waiting state a number and put a big switch on a global at the start of the `loop()` and update the global each time the state needs to change.


sender: user

message:
arduino will not save data after receiving from serial communication

I'm new to Arduino and what I'm trying to do is change the variable by sending it from php to the Arduino.

I've added the delay as stated by other questions but it has not worked so far. The pin 13 LED so

Arduino Code

    float val;
    void setup() {

      Serial.begin(9600);

      pinMode(13,OUTPUT);
      digitalWrite(13,LOW);
      val=29.1;

      Serial.println("Start!");
    }

    void loop() {

      if(Serial.available()){
        String temp = Serial.readStringUntil('\n'); //read string
        val = temp.toFloat(); //convert string to float
      }

      if(val==62.10){
        digitalWrite(13,HIGH);
      }else{
        digitalWrite(13,LOW);
      }

      Serial.println(val);
      delay(1000);

    }

PHP Code

    <?php
    $port = fopen("COM3", "w");
    sleep(2);
    fwrite($port, "62.1");
    fclose($port);
    ?>

Any tips would be much appreciated. Thank you for reading.

sender: assistant

body:
You are writing "62.1" but you are trying to read up until a `\n`, which you never send.

You need to ensure that you send the end-of-line character that you subsequently check for,

```php
fwrite($port, "62.1\n");
```

Also it's worth noting that floating point values are only ever an approximation. They're great for doing calculations, but very poor at doing comparisons. Your test value of 62.1 cannot be represented precisely as a floating point value, the closest being about 62.099. If you do need to do a comparison then you should check it's within a small range, not a precise value.

----

Your "problem" seems to stem from you opening the serial port with one program, sending a value, then closing the serial port and opening it again in something else and expecting to see that value being echoed back to you.

That can't happen on a stock Arduino UNO. Every time you open the serial port the DTR line toggles the RESET pin to enter the bootloader - which is why you need the 2 second delay after opening the serial port.

In doing so the sketch then runs fresh every time you open the serial port.

There are a number of ways of disabling that reset, from cutting a trace on the Arduino, to adding a large-ish (10µF +) capacitor between RESET and GND - both of which will interfere with your ability to program the board. The capacitor is the easier to reverse.

Ideally you'd use a different serial channel to communicate so it never interferes with the reset or programming. You could use `SoftwareSerial` and an external USB to UART adaptor instead of the `Serial` connection, or use a board with a native USB connection that doesn't reset when you open the serial port, such as a Leonardo.


message:
Are there any Arduino libraries that allow you to upload data directly to PostgreSQL?

I have been turning the internet upside down to answer this question but most of the information is several years old.

body:
The only solution to this question that I could find is a GitHub repository that hasn't been touched in several years called, SimplePgSQL. Feel free to add a better answer if you are able to find something more current. More current information would be useful!

https://github.com/ethanak/SimplePgSQL


message:
UART between arduino UNO and pc via USB not in sync

I connected my arduino uno to my system and then using serial tried writing and reading data but there is a problem which I found when I tried giving arduino crafted messages.
My arduino code is pretty simple.
```cpp
void setup() {
  Serial.begin(115200);

}

void loop() {
  if (Serial.available() > 0) {
    String data = Serial.readStringUntil('\n');
    Serial.print(" You sent me: ");
    Serial.println(data);
  }
}
```
and my python code on my system
```python
#!/usr/bin/env python3
import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
    ser.flush()

    while True:
        string=input("Enter the string: ")
        ser.write(str.encode(string))
        line = ser.readline().decode('utf-8').rstrip()
        print(line)
        time.sleep(0.01)

```
Now this gives me ability to write instructions to my arduino but following sequences of communication occur

```
└──╼ $python3 serial_communication.py
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v
Enter the string: d

Enter the string: r
 You sent me: sd
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds
Enter the string: r
 You sent me: e
Enter the string:

```

Looking at them I understand that this might be a problem with my code or I am using the wrong protocol.

body:
There's a number of things going on here that combined give you the results you're seeing.

First off there's the delay at the start:

```
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v
```

This is because when you first open the serial port the Arduino resets and enters the bootloader. Thus the first few things that get sent are discarded, and nothing is sent back from the Arduino - your sketch just isn't running at that point.

Next is the format of what you're sending compared to how you're receiving it.

You input a string and then send that string verbatim.  But on the Arduino you are reading all data up until a terminating newline character, *which you are not sending*.

But the reading function also has a timeout in it so it will return whatever it has managed to read in that time even if the terminator hasn't arrived. That timeout is 1 second by default.

So everything that gets sent within a 1 second window gets grouped together, which is what you see here:

```
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds
```

The "out of sync" appearance is because of that 1 second timeout - you are seeing what was sent a second ago.

The fix is simple enough: make sure that you send the terminating newline character from Python:

```python
ser.write(str.encode(string + "\n"))
```

And wait a few seconds after starting your program and opening the serial port before asking for anything to be sent. Maybe add a `time.sleep(2)` after opening the port to enforce that delay.


message:
WS2812B Led Digital Panel Matrix Flexible Screen 8*8. Some LEDs that are not supposed to, switch on

My project is composed of an ESP32, a level converter and two WS2812B Led Digital Panel Matrix Flexible Screen 8*8 (from Aliexpress) interconnected with the provided cable. My objective is to show a score, no scrolling or any other animation.

The main functionality works ok, I can display any decimal number between 00 to 99 (one digit in each 8x8 panel).

My problem is that apart from the digits printed, some not so aleatory LEDs switch on, not necessarily on the same color as the intended number, nor on the selected luminosity. Changing the number changes this undesirable pattern that seems to repeat for the same number on the same 8x8 matrix. Problem patters does not follow a specific 8x8 matrix, the problem does not seem to be in the hardware.

The level converter converts the ESP32 3.3v to 5v required by the Matrix but even before I connected the level converter the problem was the same.

The code I am using is as below:

    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
      #include <avr/power.h>
    #endif

    // Which pin on the Arduino is connected to the NeoPixels?
    #define PIN            14

    // How many NeoPixels are attached to the Arduino?
    #define NUMPIXELS      128

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    int delayval = 10; // delay for half a second

    void setup() {
      pixels.begin(); // This initializes the NeoPixel library.
    }

    void loop() {

      // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
      pixels.clear();
      pixels.setBrightness(1);

      boolean N0[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,1,1,1,1,0},{0,0,1,1,1,1,0,0}};
      boolean N1[8][8] PROGMEM = {{0,0,0,1,1,0,0,0},{0,0,1,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
      boolean N2[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,0,1,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
      boolean N3[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
      boolean N4[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,0,1,1,0},{1,1,0,0,1,1,0,0},{0,1,1,1,1,1,1,1},{0,0,0,0,1,1,0,0},{0,1,1,1,1,0,0,0},{0,0,0,1,1,1,1,0}};
      boolean N5[8][8] PROGMEM = {{0,0,1,1,1,1,1,0},{0,1,1,1,1,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
      boolean N6[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,0,0,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,0,0,1,1,0,0,0}};
      boolean N7[8][8] PROGMEM = {{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,0,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0}};
      boolean N8[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
      boolean N9[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,1,0},{0,1,1,0,0,0,0,0},{0,0,0,0,0,1,1,0},{0,1,1,1,0,0,1,0},{0,0,1,1,1,1,0,0}};

      int counter = 0;
      for(int line=0;line<8;line++){
        for(int column=0;column<8;column++){
          if(N2[line][column]==1){
            pixels.setPixelColor(counter, pixels.Color(0,255,0));
            pixels.show();
            delay(delayval);
          }

          if(N1[line][column]==1){
            pixels.setPixelColor(counter+64, pixels.Color(255,33,255));
            pixels.show();
            delay(delayval);
          }

          counter++;
        }
      }
      while(1){};
    }

This is a non optimized code for testing purposes only.
What am I doing wrong?

body:
Found the Adafruit NeoPixel is the reason for the problem (or the way it is implemented above is not the best).

Solved with the fastLED library as below:

    #include "FastLED.h"
    #define NUM_LEDS 128
    #define DATA_PIN 14
    #define BRIGHTNESS 10
    CRGB leds[NUM_LEDS];
    int delayval = 10; // delay for half a second

    boolean N0[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,1,1,1,1,0},{0,0,1,1,1,1,0,0}};
    boolean N1[8][8] PROGMEM = {{0,0,0,1,1,0,0,0},{0,0,1,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
    boolean N2[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,0,1,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
    boolean N3[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
    boolean N4[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,0,1,1,0},{1,1,0,0,1,1,0,0},{0,1,1,1,1,1,1,1},{0,0,0,0,1,1,0,0},{0,1,1,1,1,0,0,0},{0,0,0,1,1,1,1,0}};
    boolean N5[8][8] PROGMEM = {{0,0,1,1,1,1,1,0},{0,1,1,1,1,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
    boolean N6[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,0,0,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,0,0,1,1,0,0,0}};
    boolean N7[8][8] PROGMEM = {{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,0,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0}};
    boolean N8[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
    boolean N9[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,1,0},{0,1,1,0,0,0,0,0},{0,0,0,0,0,1,1,0},{0,1,1,1,0,0,1,0},{0,0,1,1,1,1,0,0}};

    void setup() {
      FastLED.setBrightness( BRIGHTNESS );
      FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
    }

    void loop() {
      int counter = 0;
      for(int line=0;line<8;line++){
        for(int column=0;column<8;column++){
          if(N2[line][column]==1){
            leds[counter] = CRGB::Yellow;
            FastLED.show();
            delay(delayval);
          }

          if(N1[line][column]==1){
            leds[counter+64] = CRGB::Green;
            FastLED.show();
            delay(delayval);
          }

          counter++;
        }
      }
      while(1){};
    }


message:
Updating mysql data using SIM900 and Arduino

Thanks in advance for your kind support.
I am not an expert but have little understanding of concepts and trying to integrate various things to get some useful projects for my purpose. I want to update the database (MySQL) on shared hosting using the SIM900A module and Arduino nano board. With help of examples shared on this platform and my understanding, I achieved a significant part of the same.  The following is the approach I have adopted and the current status:

I have put a PHP code on the server (shared hosting) to update the database once it received the GET request
I have also uploaded the code in the Arduino with proper connections for sending requests to the server.

Problems I am facing:
I am not able to update the data on my specific database, through the Arduino sent request. the same code is working with Thingspeak, My code is also working otherwise, as I have tested through web form request and URL request. I am not sure where is the problem.  I am also not getting any errors. The response to the AT request is "OK" only
Though I can update the Thingspeak channel, only till the command lesser than 61 characters, which are sent after the AT+CIPSEND command. There is no error, even if the request size increases, but data updated only till 61 characters (including \x1A character)
            "I am wondering, is this the limit, that cannot be increased or there is some possibility to increase it."
           I understand that the problem appears to be in approach and not in code, as the code is working in itself. However, please let me know, which code I need to share, as it is a multifile code on the web-editor

body: I have faced a similar issue. It happened due to an SSL issue. You can find all info about it here - https://stackoverflow.com/questions/62950561/sim800l-gsm-module-working-with-http-and-shows-error-with-https-why


message:
MCU Recommendations for Audio Pitch Shifting

I'm looking to use a MCU for audio sampling. I want to sample incoming audio and pitch shift it (without speeding it up/slowing it down). A bit about the build. I'm planning to make a circuit board that can take in a single audio source and output three or four different pitch-shifted sounds in real time, with each output being its own pitch-shifted sound. If possible, I would like to have a potentiometer for each output that could in effect change how pitch shifted each output is, sort've of like a tuning knob. These outputs will eventually get summed together to produce a chord-like sound.

I'm not quite sure what exact requirements are needed for this, just that the sampling rate should be around 44KHz (standard audio sampling rate). Of course, I would like the outputs to replicate the original sound as much as possible, just pitch-shifted. I am assuming as well that the way I pitch-shift and sample could affect the requirements. Also, I would like to avoid SMT if I can.

Given these requirements, what do you suggest the best MCU to use is? I would like to use Arduino to program the MCU. I really only need the chip itself (I think?), as I plan to create a separate circuit board for this (although would I need an Arduino board to initially program the chip?)

I'm fairly new to the Arduino world, so apologies in advance if I miss something obvious or mess up terminology. I do come from a background in analog circuitry and programming though. Just looking for as much help as I can get from people who know more than me but am eager to learn about this all.

Thanks!

body: I get the impression that you haven't done this sort of thing before, on any scale. Pitch shifting is a totally non-trivial process.  I suggest you start out on a regular computer and try to get a single channel working to your satisfaction.  Then, if you are still determined to do this on a smaller system, you will at least know what you are up against and will be able to decide what systems are appropriate.  Sorry if it sounds like I'm trying to throw cold water on your idea, because I'm sure it would be a fun instrument to play.  But I think you would be getting in way over your head if this isn't already your field of expertise.


message:
Get a specific item from comma separated text

I use bluetooth (works like serial monitor).
Let me say i send a text to my hc-05 (same as sending to serial monitor)
My current code is displaying text from serial monitor/HC-05 TO LCD
```
#include <LiquidCrystal.h>

LiquidCrystal lcd(4, 6, 10, 11, 12, 13);
String readString;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  while(Serial.available()){
    delay(50);
    char c=Serial.read();
    readString+=c;
  }
  if(readString.length()>0){
    Serial.println(readString);
      lcd.clear();
      lcd.print(readString);
    readString="";
  }
}
```
    from serial monitor i type `a,b,c,d`

>now my goal is to just get the a and display in lcd

or

>in other words i want to get the value of a b c d in the text that is CSV to list or array and get value for index 1,2,3,4

OR

>***split string by delimiter***

so how can i do it

details-ARUINO UNO

body:
Use the `strtok` function.

From Geeks for geeks (https://www.geeksforgeeks.org/strtok-strtok_r-functions-c-examples/):

arguments:

- str: The string which is to be split
- delim: The character on the basis of which the split will be done Return value

The function performs one split and returns a pointer to the token split up. A null pointer is returned if the string cannot be split.


body:
i searched in stack exchange Arduino but i dint get answer so i posted but when i searched in stack over flow i got [link][1] this is my final code
```
String part01;
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }

  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

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

void loop()
{
  String part01 = getValue("523;524;525",';',1);
  Serial.println(part01);

}
```

  [1]: https://stackoverflow.com/a/29673158/14862885


message:
Why is my liquid crystal display not showing any output?

UPDATE:
The LCD will light up only when the all my components are located in the bottom right of the breadboard. Why am I not able to use the entire breadboard for my circuit?

I am trying to display data from a temperature and humidity sensor on the serial monitor and the liquid crystal display.

I am using :
 - Arduino Uno R3
 - I2C 16x2 LCD Module
 - 3 pin DHT11 sensor

Here is my code :

```
#include <dht.h>                // initialize the digital temperature and humidity sensor library ("DHTlib")
#include <LiquidCrystal_I2C.h>  // initialize the liquid crystal display library ("LiquidCrystal I2C")
#include <Wire.h>               // intialize the wire library

/*   the first parameter is the I2C address
 *   the second parameter is how many columns are on your screen
 *   the third parameter is how many rows are on your screen
*/
LiquidCrystal_I2C lcd(0x27, 16, 2);

dht DHT;              // create a handle to call functions from the sensor library
#define DHT11_PIN 7   // assign a digital pin number to the sensor
float TempC;          // create a variable to store temperature in celsius
float TempF;          // create a variable to store temperature in fahrenheit
float Humi;           // create a variable to store humidity

void setup()
{
  lcd.init();                // initialize liquid crystal display
  lcd.backlight();           // turn on the backlight of the lcd
  pinMode(DHT11_PIN,INPUT);  // configure the pin for the sensor as an input for reading the data
  Serial.begin(9600);        // set data rate in bits per second for serial data transmission
}

void loop()
{
  // collect sensor data
  int chk = DHT.read11(DHT11_PIN);  // store sensor data in a variable
  TempC = DHT.temperature;          // store temperature in Celsius
  TempF = 9 / 5 * TempC + 32;       // store temperature in Fahrenheit
  Humi = DHT.humidity;              // store relative humidity as a percentage

  // display sensor data on LCD
  lcd.setCursor(0,0);    //tell the screen to write on the top row
  lcd.print("T: ");
  lcd.print(TempC);    // print the temperature in Celsius
//  lcd.print(TempF);    // print the temperature in Fahrenheit
  lcd.print((char)223);  // print the degree symbol
  lcd.print(" C");
//  lcd.print(" F");
  lcd.setCursor(0,1);    // tell the screen to write on the bottom row
  lcd.print("H: ");
  lcd.print(Humi);       // print the humidity
  lcd.print(" %");

  // display sensor data on the serial monitor
  Serial.print("Temperature = ");
  Serial.print(TempC);     // print the temperature in Celsius
//  Serial.print(TempF);     // print the temperature in Fahrenheit
  Serial.print("\xc2\xb0");  // print the degree symbol
  Serial.println(" C");
//  Serial.println(" F");
  Serial.print("Humidity = ");
  Serial.print(Humi);        // print the humidity
  Serial.println(" %");

  delay(2000);  //delay fetching the next sensor values for 2 seconds
}
```
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/8ZO91.png

My jumper wires are connected as follows:
- DHT plus → red plus row
- DHT middle → digital pin 7
- DHT minus → blue minus row
- LCD GND → blue minus row
- LCD VCC → red plus row
- LCD SDA → analog pin A4
- LCD SCL → analog pin A5
- Red plus row → 5V pin
- Blue minus row → GND pin

body: Your breadboard is one of those which have the power/GND lines interrupted between columns 31 and 33. I also once fell into this trap. If you look closely, you see that the blue and red lines are interrupted in the middle of the board. Just put wires between these pins to bridge the gap.


message:
ISR for timer on Arduino MEGA gets called only once

I am trying to write an Arduino code to blink LED using timer 4 on Arduino MEGA (atmega2560). I resetted the timer registers, and entered all the necessary values to bring to 16MHz to 1Hz (rescalar = 1024, OCR4B = 15624), then I wrote the blinking code inside the service routine block. Now when I run the program, the ISR is called **only once**. I saw from Youtube videos that even though the setting up of TCCR registers and TIMSK is in setup() function, it repeats indefinitely like a loop. Below is my code. Any help would be immensely appreciated. Thank you.

```
int led_pin = 10;
static int counter = 0;
int led_blink = 0;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(led_pin,OUTPUT);
cli();
TCCR4A = 0;
TCCR4B = 0;
TCNT4 = 0;
OCR4B = 15625;                                //set the maximum count 16MHz -> 1Hz
TCCR4B |= (1<<CS10) | (1<<CS12) | (1<<WGM12); // prescalar = 1024 , CTC(OCR3B) mode
TIMSK4 |= (1<<OCIE4B);
sei();
interrupts();
}

ISR(TIMER4_COMPB_vect)
{
  Serial.println(millis());
  led_blink = !led_blink;

}

void loop() {
  // put your main code here, to run repeatedly:
  if(led_blink == 1)
    digitalWrite(led_pin,HIGH);
}
 ```

body:
Your missing an else statement in your loop:

    else
      digitalWrite(led_pin,LOW);


message:
Can UNO log more PCB 353b33 accelerometer data points compared to TDS3014B oscilloscope?

I'm currently recording data points from an analog accelerometer(PCB 353b33) using a TDS3014B oscilloscope which has Record Length of 10,000 points at a Sample Rate 1.25 Ga/s. I'm want to record more data points, would it be possible to use UNO as a data acquisition device and record much higher data points than the oscilloscope(>> 10,000)

body: No way. The UNO has only 2.5kb of RAM, so you can't cache the data points and you would need a very quick link to get the data out. And sampling at 1.25 GigaSamples/s is orders of magnitude beyond an UNO, as its maximum clock frequency is only 16 MHz. An Uno is about $20, while your TDS3014B is around $1500. Sometimes, there's a reason for a different price tag.


body:
For 10 minutes of sampling at 1.25Gsps using 32-bit floats you would need about 3 terabytes of memory. You're not going to even get close to that with a very very powerful desktop. An Arduino...? Dream on. It's never going to happen.

An Arduino has a couple of kB of memory. Plus a slow, crude, ADC. You may get a fraction of a second at its highest sample rate. To stretch it out over 10 minutes you'd be looking at no more than about 800 samples (16 bit values from a 10 bit ADC), so maybe one sample every 1 1/2 seconds.


message:
Send values from Arduino Uno to Wemos D1 R1

I have a weather project in which I have to measure the temperature and humidity (DHT22 sensor), the pressure, and other things, and then show them on a local web page (using a Wemos D1 R1) in either my phone or PC (I have both an Arduino Uno and a Wemos D1 R1 for this project)

I wanted to use only the Wemos D1 R1 since it works the same as an Arduino Uno except it has an ESP8266 WiFi built-in while the Arduino Uno doesn't, but as you may know it only has 1 analog pin while I need at least 3 or 4 analog pins, so in my case I should connect the sensors with the Arduino Uno and measure the temperature, humidity, etc. and then send those values to the Wemos D1 R1 which will show the results itself on a web page as I said earlier.

It seems that there is a way to do that using an I2C connection, but I have read many articles talking about connecting an Arduino to another Arduino using an I2C connection, but I don't know how to do that in my case (Arduino Uno and Wemos D1 R1); if there is another way to send values please tell me.

body:
As I see it, the most straight-forward way to connect 2 Arduinos is using their built-in UART (aka Serial port, TX/RX pins) communication.

There are many tutorials on this on Google, and a similar explanation can be found in this question:
https://arduino.stackexchange.com/questions/75362/serial-communication-arduino-mega-and-d1-wemos-mini

However, there is a slight difference.
Arduino Mega has built in more than 1 hardware serial ports (I can't recall now if it's full 3 ports, or just 2), what leave one port for debug purposes, and the other - for your communication.
In your case (Arduino Uno) - you have only one serial port, that if will be used for the inter-Arduinos communication - will not be available for debug/console messages.
The solution for this is adding a Software Serial port, also highly available in tutorials over the net, here is one example:
https://arduino.stackexchange.com/questions/48539/softwareserial-between-arduino-uno-and-esp8266

Enjoy your project!


body:
I agree with @Offer that using UART is the simplest solution to connect the devices.
I just want to suggest two alternatives:

 1. Use an external analog to digital converter IC. Using the Arduino only for analog conversion is a bit over powered. E.g. the ADS1115 has a resolution of 16 bits and there's already a library, so usage should be easy.

 2. The ESP8266's bigger brother - the ESP32 - has several ADC pins.

The biggest advantage (beside the higher resolution) is, that you only need to write code for one device, which makes your project less complex.


body:
Have a look at my blog 'Paynters Palace' and search for posts with the 'I2C' tag - you'll find quite a bit of useful code, I think.

[This project][1] shows how to connect two Arduinos using SPI

[This project][2] shows how to connect two Arduinos using I2C and how to pass arbitrary data types between the two units

  [1]: https://www.fpaynter.com/2020/03/arduino-spi-data-exchange-between-two-arduinos-in-a-master-slave-configuration/
  [2]: https://www.fpaynter.com/2020/03/i2c-between-an-arduino-mega-and-a-teensy-3-x/


message:
How to work with WS2812B 16x16 matrix panel from aliexpress

I'm completely new to Arduino, and I want to build the project using an LED 16x16 matrix, but I don't know where to start. On the internet, I keep finding these custom matrix panels and they aren't similar to mine. So I'm asking here. Does anyone have experience with this Arduino-compatible RGB LED matrix panel? [This][1] is the link to the Aliexpress product. [![This is my Arduino board][2]][2]
[![This is the back of the matrix panel][3]][3]
[![This is the back of the matrix panel with description visible][4]][4]
Will I need an additional power supply? What will I need to install to make it work? Where do i plug what wire into my arduino? Thanks for any answer!

  [1]: https://www.aliexpress.com/item/1005002342288045.html?spm=a2g0o.productlist.0.0.6b0b4449alflb5&algo_pvid=null&algo_expid=null&btsid=0b0a0ac216174813684097268eee35&ws_ab_test=searchweb0_0,searchweb201602_,searchweb201603_
  [2]: https://i.stack.imgur.com/GZRyW.jpg
  [3]: https://i.stack.imgur.com/wNtZl.jpg
  [4]: https://i.stack.imgur.com/qbQRW.jpg

body:
It's just a string of WS2812B LEDs that have been "bent" into a grid. You treat it exactly like any other WS2812B strip of LEDs.

You have 256 LEDs, and as far as the Arduino is concerned, they are just in a line numbered 0-255.

The "grid" arrangement is solely down to you to you to calculate.  Fortunately 256, or 16x16, is very easy to work with: you have a byte which can represent any one of the LEDs, and each half of the byte (a nibble) is one coordinate.

The traditional calculation to convert X and Y into a linear number is:

    num = x + y * width

where `width` is the number of LEDs in the X direction (16).  However since we're working with a width of 16 that can be optimized to use bit-shifting and bitwise operations:

    num = x | (y << 4)

That is assuming LED 0 is on the left (either top or bottom) and LED 1 is one place to the right.

Will you need an external power supply for it? Yes, most certainly (and they even provide you with a dedicated power connection for it). 256 LEDs, if all are turned on full brightness at once, could consume up to about 15 amps (20mA per channel, three channels per LED, 256 LEDs).


message:
Why echo "R" > /dev/ttyUSB0 doesn't work, but on the same PC Serial Monitor in Arduino IDE works?

I have a strange problem. I am running Ubuntu and NodeMCU si plugged into USB. I have very simple sketch running on it, when it reads letter "R" on serial, it turns ON relay.

  When I open Serial Monitor in Arduino IDE and I type letter "R" and send it, it works perfectly. However when I run commands below, it does nothing:

    stty -F /dev/ttyUSB0 115200
    echo "R" > /dev/ttyUSB0

I tried running the same commands on different PC with Ubuntu and these system commands work just fine.

I also tried copying exact same configuration from `stty -a -F /dev/ttyUSB` from PC where it works to PC where it doesn't, but it didn't help either.

I don't think it's driver issue, because if it would, then I suppose it wouldn't work with Serial Monitor also.

Thank you for any help or hints in advance.

body:
OK, so I resolved this problem, but only half-way. I was using NodeMCU with CH340 ... and this controller worked only in Serial Monitor, not in command shell on one computer (it worked fine on other computer).

So I tried using different NodeMCU with CP2102 and it worked just fine. So I assume there must be some kind of issue with ch341 driver in my linux, I don't know.


body:
I had the same issue.
After entering command that Majenko suggested:
```
stty -F /dev/ttyUSB0 -hupcl
```
I still wasn't able to send commands to Arduino nano.
Strangely, when I open Arduino IDE Serial Monitor and send command it works.
When I close it, I can send commands in terminal to Arduino for some time. Then it stops working again :/


message:
L298 Motor Driver not showing Red light when connecting power supply

I recently bought an L298 motor driver module for controlling 2 motors(5v each).

When i connect the power supply(which is a normal RC car battery holder(3)) the red light doesn't light up.

Instead if i connect the +ve to the 5v on the motor driver, the red light is glowing, but the motors don't work.

body:
You need to do math on the power consumption as arduino uno takes takes 5 V 500 mA at least for it to work. That is why it can be powered by USB cables too.
Now if you try calculating power consumption on the motors you would understand that the power you are giving is nowhere enough for the arrangement to work or you could have been able to run the motors without the motor driver.
Try upgrading the power you are giving.


message:
Arduino RTC SD Card problem

I am using a script on an Arduino to record BME280 data onto an SD card and to display it on a lcd display. To have a valid time stamp I am also using a DS3231 RTC module. I set the time succesfully and can manually read it and write it to the serial monitor.
Writing the sensor data to the SD card works fine as well. But as soon as I try to include the time from the RTC into the file onto the SD card the script jumps back to the else statement in the setup() where I try to open the file for writing the header line.

Without using the RTC time it works fine, as soon as I put it in using the corresponding function, it fails.

Here is the script I am using:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <SPI.h>
    #include <SD.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>

    #define BME_SCK 8
    #define BME_MISO 6
    #define BME_MOSI 7
    #define BME_CS 5

    #define SEALEVELPRESSURE_HPA (1013.25)
    #define RTC_I2C_ADDRESS 0x68 // I2C Adresse des RTC  DS3231

    Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

    unsigned long lastReadRTC = -1;
    boolean sd_ok = 0, sensor_ok = 0;
    File dataLog;
    String dat_time;

    LiquidCrystal_I2C lcd(0x27, 20, 4);  //Hier wird das Display benannt (Adresse/Zeichen pro Zeile/Anzahl Zeilen)

    void setup()
    {
      Wire.begin(); //Kommunikation über die Wire.h bibliothek beginnen.
      Serial.begin(9600); // open serial communications and wait for port to open
      // SD Card Initialization
      if (SD.begin())
      {
        Serial.println("SD card is ready.");
        sd_ok = true;
      } else
      {
        Serial.println("SD card initialization failed");
        return;
      }
      //if( SD.exists("test.txt") == 1 ){
      dataLog = SD.open("test.txt", FILE_WRITE);
      if(dataLog) {                               // if the file opened okay, write to it:
         Serial.println("OK, writing header");
         // write some texts to 'test.txt' file
         dataLog.println("DATE | TEMPERATURE | HUMIDITY | PRESSURE");
         dataLog.close();   // close the file
      }
      else {
        Serial.println("error opening testfile.txt");
      }
      unsigned status;
      status = bme.begin();
      if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
        Serial.print("SensorID was: 0x");
        Serial.println(bme.sensorID(),16);
        Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
        Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
        Serial.print("        ID of 0x60 represents a BME 280.\n");
        Serial.print("        ID of 0x61 represents a BME 680.\n");
        while (1) delay(10);
      }else{
        sensor_ok = true;
        Serial.println("OK, sensor recognized");
      }
      lcd.init();
      lcd.backlight();
      lcd.setCursor(0,0);
      lcd.print("Temp. = ");
      lcd.print(bme.readTemperature());
      lcd.print(" *C");
      lcd.setCursor(0,1);
      lcd.print("Press. = ");
      lcd.print(bme.readPressure() / 100.0F);
      lcd.print(" hPa");
      lcd.setCursor(0,2);
      lcd.print("Alti. = ");
      lcd.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
      lcd.print(" m");
      lcd.setCursor(0,3);
      lcd.print("Hum. = ");
      lcd.print(bme.readHumidity());
      lcd.print(" %");

      delay(1000);
    }

    //Reads the current datetime from rtc module
    String rtcReadTime(){
      Wire.beginTransmission(RTC_I2C_ADDRESS); //Connect to address 0x68
      Wire.write(0);
      Wire.endTransmission();
      Wire.requestFrom(RTC_I2C_ADDRESS, 7);
      int sekunde    = bcdToDec(Wire.read() & 0x7f);
      int minute     = bcdToDec(Wire.read());
      int stunde     = bcdToDec(Wire.read() & 0x3f);
      //weekday not included
      /* wochentag  =*/ bcdToDec(Wire.read());
      int tag        = bcdToDec(Wire.read());
      int monat      = bcdToDec(Wire.read());
      int jahr       = bcdToDec(Wire.read())+2000;

      char timestamp[30];
      sprintf(timestamp,"d.d.M d:d:d",tag,monat,jahr,stunde,minute,sekunde);
      return timestamp;
    }

    //Converts binary to numeric
    byte bcdToDec(byte val){
      return ( (val/16*10) + (val) );
    }

    void loop()
    {
      unsigned long currentMilliseconds = millis();
      if((lastReadRTC + 1000) < currentMilliseconds){
        lastReadRTC = currentMilliseconds;
        lcd.setCursor(0,0);
        lcd.print("Temp. = ");
        lcd.print(bme.readTemperature());
        lcd.print(" *C");
        lcd.setCursor(0,1);
        lcd.print("Press. = ");
        lcd.print(bme.readPressure() / 100.0F);
        lcd.print(" hPa");
        lcd.setCursor(0,2);
        lcd.print("Alti. = ");
        lcd.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
        lcd.print(" m");
        lcd.setCursor(0,3);
        lcd.print("Hum. = ");
        lcd.print(bme.readHumidity());
        lcd.print(" %");
        //Serial.println(rtcReadTime());
        if(sd_ok){
          dataLog = SD.open("test.txt", FILE_WRITE);
          //dataLog.print(rtcReadTime());
          dataLog.print(" |  ");
          if(sensor_ok) {
            dataLog.print(bme.readTemperature());
            dataLog.print("°C   |  ");
            dataLog.print(bme.readHumidity());
            dataLog.print("  | ");
            dataLog.println(bme.readPressure() / 100.0F);
            dataLog.close();
          }
          else{
            dataLog.println("  Error    |  Error   |  Error");
            dataLog.close();
          }
        }
      }
      delay(1000);
    }

So when I run the script without the RTC time included it gives me the output:

> SD card is ready.

> OK, writing header

If I include the line `dataLog.print(rtcReadTime());` towards the end (in the script commented out) it jumps to the beginning of the setup section into the else statement giving me:

> error opening testfile.txt

and nothing is written into the file on the SD card.

I tried to find the mistake for multiple hours yesterday and was hoping to find it today after a good night of sleep, but nope. It is probably an easy fix that i can't see. The code is probably far from perfect or good. I am a beginner in c++, so keep that in mind. :)

**EDIT:**
As I was not able to find a solution using `rtcReadTime()`, I used the `RTClib.h` directly and created the time manually in the writing process for the SD card:

    void loop()
    {
      unsigned long currentMilliseconds = millis();
      if((lastReadRTC + 1000) < currentMilliseconds){
        lastReadRTC = currentMilliseconds;
        lcd.setCursor(0,0);
        lcd.print("Temp. = ");
        lcd.print(bme.readTemperature());
        lcd.print(" *C");
        lcd.setCursor(0,1);
        lcd.print("Press. = ");
        lcd.print(bme.readPressure() / 100.0F);
        lcd.print(" hPa");
        lcd.setCursor(0,2);
        lcd.print("Alti. = ");
        lcd.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
        lcd.print(" m");
        lcd.setCursor(0,3);
        lcd.print("Hum. = ");
        lcd.print(bme.readHumidity());
        lcd.print(" %");
        if(sd_ok){
          dataLog = SD.open("test.txt", FILE_WRITE);
          DateTime now = rtc.now();
          dataLog.print(now.day(), DEC);
          dataLog.print(' ');
          dataLog.print(now.month(), DEC);
          dataLog.print(' ');
          dataLog.print(now.year(), DEC);
          dataLog.print(" ");
          dataLog.print(now.hour(), DEC);
          dataLog.print(':');
          dataLog.print(now.minute(), DEC);
          dataLog.print(':');
          dataLog.print(now.second(), DEC);
          dataLog.print(" |  ");
          if(sensor_ok) {
            dataLog.print(bme.readTemperature());
            dataLog.print("°C   |  ");
            dataLog.print(bme.readHumidity());
            dataLog.print("  | ");
            dataLog.println(bme.readPressure() / 100.0F);
            dataLog.close();
          }
          else{
            dataLog.println("  Error    |  Error   |  Error");
            dataLog.close();
          }
        }
      }
    }

Probably far from ideal, but enough for me.

body:
`timestamp` in `rtcReadTime()` is a local variable. When you return from that function it ceases to exist - so what you have returned is nothing. You can't print nothing, so the Arduino crashes.

You either need to make the `timestamp` variable `static` so that it's not lost when you leave the function, make it a *global* variable, which has a similar effect, or pass a buffer variable to `rtcReadTime()` which is then filled instead of returning a pointer to a char.

The simplest of these is just to make `timestamp` static. Also you should use `snprintf` instead of `sprintf` to avoid the possibility of buffer overflows:

```
String rtcReadTime(){
  Wire.beginTransmission(RTC_I2C_ADDRESS); //Connect to address 0x68
  Wire.write(0);
  Wire.endTransmission();
  Wire.requestFrom(RTC_I2C_ADDRESS, 7);
  int sekunde    = bcdToDec(Wire.read() & 0x7f);
  int minute     = bcdToDec(Wire.read());
  int stunde     = bcdToDec(Wire.read() & 0x3f);
  //weekday not included
  /* wochentag  =*/ bcdToDec(Wire.read());
  int tag        = bcdToDec(Wire.read());
  int monat      = bcdToDec(Wire.read());
  int jahr       = bcdToDec(Wire.read())+2000;

  static char timestamp[30];
  snprintf(timestamp, 30, "d.d.M d:d:d",tag,monat,jahr,stunde,minute,sekunde);
  return timestamp;
}
```


message:
GPS Ublox neo-6mv2

I'm trying to get gps data from ublox neo-6mv2 module via arduino. Should ublox's neo-6mv2 light blink after power up by 5v from arduino ? Or is there any other sign that tells the module isnt dead ?

Module is connected to 5v, gnd for few hours - still no blink / light.

[![enter image description here][1]][1]

[![enter image description here][2]][2]

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/JB6Tj.png
  [2]: https://i.stack.imgur.com/t5wes.png
  [3]: https://i.stack.imgur.com/ZhSES.png

body: Be sure the active antenna is attached and may have to move it around to differnent areas of you work bench. some of these modules are very deaf or prone to inteference from reflections in the room.


message:
Nrf24l01 smd pcb placement tips

I am working on pcb design with nrf24l01 smd. I have read somewhere that nrf24l01 module has problem while communication when it is placed with its antenna within the pcb. I want my module to be within the pcb as much as possible to save some space. I will be making the pcb at home and will be placing atmega 328p smd on the opposite layer. Should I fill the opposite layer with ground pad?

body:
You need to keep the ground plane away from the antenna. The rest of the module doesn't care (and having a ground plane under it can help with unwanted EMI).

Here's a design I did recently for a customer with the same module in it. It's placed near the edge of the PCB with the ground plane cut out around the antenna:

[![enter image description here][1]][1]

That layout is actually set up for either the small SMD, the SMD with PA+LNB or the thorugh-hole version. The important thing is that there is a nice big exclusion zone in the ground plane where the antenna is.

  [1]: https://i.stack.imgur.com/jy7XF.png


message:
How to split 12V power suply to arduino and led matrix panel

I'm trying to build my Arduino project with Arduino mega and led matrix panel. I'm wondering what power supply should I buy, my first thought was to power the matrix panel from a 5v Arduino pin, but I read [here][1] that it's not really a good idea. So now I'm wondering if I can buy a 12V power supply and somehow split it to 6V and 6V (or something like it). To connect one end to Arduino and the other to the matrix panel. If it's possible, how do I do that? Thanks for any help!

  [1]: https://forum.arduino.cc/index.php?topic=618723.0

body:
No,you cannot split the voltage and expect the devices (Arduino and LED strip) to work correctly together (would lead to different ground levels beside other problems). For getting a different voltage you would need a voltage regulator. A switching "buck" regulator is the better choice here than a linear regulator (lile the one on the Arduino), since it is way more efficient (To get from 12V to 5V a linear voltage regulator would burn up the excessive 7V as heat).

But since both Arduino and LED strip use 5V, why not just buying a 5V power supply, which can provide enough current. Then you can connect it to the Arduino and the LED strip in parallel. No need for voltage regulation in that case.


body: Figure out the amp draw of each component, i.e. Arduino and LED strip.  Buy a voltage regulator that supplies the voltage needed but, more importantly, can supply the Arduino amp draw plus the LED strip amp draw.


message:
Scheduler comparison for Arduino Uno

I understand that the official [Arduino Scheduler](https://www.arduino.cc/en/Reference/Scheduler) doesn't support Uno, and there are several third-party schedulers to fill the gap, notably, [Scheduler](https://github.com/vbextreme/Scheduler), [Arduino-Scheduler](https://github.com/mikaelpatel/Arduino-Scheduler) and [TaskScheduler](https://github.com/arkhipenko/TaskScheduler). There are probably many more, though I see that many so-called "task schedulers" are actually just periodic function callers which don't handle context (i.e. they don't support `yield()`).

I need to make a choice of a scheduler to use in a project (a real one, with `yield`, not a periodic function caller). Is there any comparison of Arduino task schedulers? I'm specifically interested in the following aspects:

- context switching time (the most important one)
- RAM/ROM consumption estimation
- list of supported boards

body:
I have just tested `vbextreme/Scheduler` and `Arduino-Scheduler` using the following code:

```
#include <Scheduler.h>

void setup() {
  pinMode(3, OUTPUT);
  Scheduler.startLoop(loop2);
}

void loop() {
  digitalWrite(3, LOW);
  yield();
  digitalWrite(3, HIGH);
  yield();
}

void loop2() {
  yield();
}
```

Without any `Scheduler` lines, the code occupies 734 bytes of ROM, 9 bytes of RAM, and the pin toggles with a period of 8.5 us (117 kHz). The numbers below represent the additional ROM/RAM/execution time:

- [`vbextreme/Scheduler`](https://github.com/vbextreme/Scheduler) occupies additional 1676 bytes of ROM, 70 bytes of RAM, and the context switch takes 15.5 us (toggle frequency 14.18 kHz). It seems to only support AVR/SAMD boards.

- `vbextreme/Scheduler` with `CONFIG_AVR_OPTIMIZE_COOPERATIVE` set to 1 occupies additional 1568 bytes of ROM, 70 bytes of RAM, and the context switch takes 11 us (toggle frequency 19.07 kHz).

- [`Arduino-Scheduler`](https://github.com/mikaelpatel/Arduino-Scheduler) occupies additional 578 bytes of ROM, 44 bytes of RAM, and the context switch takes 10.6 us (toggle frequency 19.59 kHz). It supports AVR/SAMD and some of the Teensy/STM32 boards. It seems that this scheduler is not compatible with tasks which use `malloc()`.

- [`CopyThreads`](https://github.com/jensh/CopyThreads) occupies an additional 2148 bytes of ROM, 41 bytes of RAM, and the context switch takes 54.5 us (toggle frequency 4.417 kHz). This scheduler claims to have the advantage of using a single stack, so as long as tasks do not `yield` during peak stack usage, each task has essentially the complete stack at its disposal.

I couldn't get the equivalent code for `TaskScheduler` to run, I'll be grateful if someone posts an answer featuring schedulers I didn't test.


message:
Running Arduino mega on 5V power supply

I'm wondering if I can run Arduino mega on 5V power supply, even though it's recommended for 6-12V. USB has only 5V right, will it be a problem? I expect to draw quite a lot of power from the 5V pin too so could it be a problem?

body:
The 6-12V range applies only to the onboard voltage regulator(if you provide power via Vin or the barrel jack). The Arduino itself runs on 5V and the regulator needs a bit headroom above that to do the regulation.

You can run the Arduino via USB, since it has 5V, just as needed by the Arduino

And you can provide power directly to the 5V pin (with a voltage of 5V or course).

If some of your components draw a lot of power, you should never draw that current through the Arduino. You need to connect the power supply in parallel to your components and the Arduino, so that the high currents can flow past the Arduino, not through it.


body:
If you connect it from the USB port on your computer to the USB plug on the Mega, you'll do fine. What you can't do is connect a 5v source to the barrel jack; that goes to the board's voltage regulator which needs ~ 7v minimum to provide 5v out.

"Quite a bit of power" is a rather vague specification. A USB port can supply 500mA unless the device in question negotiates for more current and the port in question is capable of supplying it. What is probably more concerning is if you're trying to pull a lot of current *through the Mega*, you risky overloading its pin-drivers or its PCB tracks. The Mega's pins are spec'd for 20mA; 40mA Absolute Max, briefly, to not damage it. The total current budget is 200mA max. If you're planning to approach either of those levels, you should consider powering some of your devices separately. That might include powering from the same or another USB port, as long as you don't pass it through the board, and you observe the USB ports' maximum currents as well.


body:
Here's what I did for my project:

I used a high current regulated 5V supply. I took a USB cable with the square connector that goes into the Arduino and cut it in half. I attached the red and black wires to +5V and ground on my regulated power supply. I then drove the high current components in my project directly from the 5V supply.

If you use this approach you should probably also add filter capacitors between 5V and ground at both the Arduino and the high current load. Those will help  smooth out the voltage variations as the high current load switched on and off.


body:
Yes, you can run the Arduino Mega off of a 5V supply. Instead of connecting the voltage to the DC jack, instead feed your 5V into the +5V pin on the Arduino header. (it is one of the red pins in the image below).
[![Ardiono Mega pinout][1]][1]

  [1]: https://i.stack.imgur.com/maoqX.png


message:
Arduino UNO with integrated ESP2866 wifi not working correctly

I bought this "knockoff" Arduino UNO with an integrated ESP 2866 wifi module. But I can't make it work. I've followed [this][1] tutorial because it's the same product as I have, but I can't make it work anyway - even blinking with LED doesn't work. Does anyone have experience with this exact (or similar) board with integrated ESP2866? I would be really glad for any help. [link to the product][2]. If you need to know anything else, I'll try my best to answer it.

My problem:

The board normally loads into IDE and i can send code to it. But after I do that, I get this:
```
Executable segment sizes:
IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)
DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 257316 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.8
Serial port COM6
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 2c:f4:32:44:1f:0b
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Erasing flash (this may take a while)...
Chip erase completed successfully in 8.7s
Compressed 261472 bytes to 193136...
Wrote 261472 bytes (193136 compressed) at 0x00000000 in 17.0 seconds (effective 122.9 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...
```
But the LED doesn't blink.

  [1]: https://www.youtube.com/watch?v=tj2fwh989D8
  [2]: https://s.click.aliexpress.com/e/_AEhGBH

body:
You are obviously currently programming the ESP8266, not the Atmega328p. The board seems to have DIP switches on it. With those you can control, which chip is connected to which. The product description has the following table

    Connection  DIP
   1  2  3  4  5  6  7
    ATmega328<->ESP8266  ON  ON  OFF  OFF  OFF  OFF  OFF
    USB <->ATmega328  OFF  OFF  ON  ON  OFF  OFF  OFF
    USB<->ESP8266 (Update firmware or sketch)  OFF  OFF  OFF  OFF  ON  ON  ON
    USB<->ESP8266 (communication)  OFF  OFF  OFF  OFF  ON  ON  OFF
    All independent  OFF  OFF  OFF  OFF

If you want to program the Atmega328p on it, you need set the DIP switches to the combination "USB <-> Atmega328". Currently you most likely have the combination "USB<->ESP8266 (Update firmware or sketch)", which means, that the ESP is connected to the USB chip (and thus to the PC) for programming. For blinking the Arduinos buildin LED you need to program the Atmega328p.

---

**About the blink sketch:** In the tutorial video he programs the ESP. But in the blink example he changes the delay time to 5000, which would mean on and off times of 5s. The LED, that he is pointing to, is blinking much faster, though he doesn't address this. I think he actually has the standard blink sketch on the Atmega and only pretends (or just didn't notice) that this happened due tp his programming. As you don't see a blink with the ESP, but with the Atmega, I would guess, that the LED marked with L is connected only to the Atmega (like on a normal Uno) and the ESP doesn't have any LED to blink connected. So everything is actually working as expected, the tutorial was just bad at that point.


body:
I don't know why the answer below is accepted, as it clearly doesn't solve the question but also gives **false** information. In this answer @chrisl assumed that blinking green LED is what was programmed with sketch, but if you will open sketch used in this video and read comments in the source code, then this misconception will become obvious: actually red **RX** LED is what was programmed.

This board has two independent chips: ATmega328P and ESP8266, and ESP8266 built-in LED is **combined** with RX LED. So when you are blinking with ESP8266 LED, you are blinking with RX led.
And this is what tricked most people answering here, as they were looking on green blinking LED, which is controlled by ATmega328P.
Having said that, I also have to admit that I don't have solution for original question and I don't know why it doesn't work for @krystof18, but in video it clearly works.

**EDIT:**

**TL/DR:**

Don't use `LED_BUILTIN`, but attach an external LED and a resistor to ESP GPIO pins. Modify the sketch to use correct pin and upload while switches 5,6 and 7 are ON. Then disconnect the board and turn switch 7 OFF. Then you have to power board again and it should work.

**Long explanation:**

I have a board visually similar to what is on the video tutorial you have posted, but for me the blink example doesn't work, probably because LED is wired to some other PIN, rather than `#defined` for `LED_BUILTIN`. But I managed to get it working using [this](https://youtu.be/VfwvVi0rnLQ?t=358) tutorial! Watch from 5:58. (Please note this video is in language I don't understand and have no idea what language it is, but the video itself is so obvious, that you basically don't need to understand what does that guy say).

Basically in this tutorial it is just blink example, but using external LED, instead of built-in. If you look at your board, then you can find 4x3 bar of pins located near 0, 1 and 2 Arduino digital pins. This bar is labelled "ESP pins" and it is what is says: ESP8266 pins. Pin labels are on the back of the board.

So this guy in video just connects GPIO16 and GND pins to a LED with resistor, and then modifies original blink example to use 16 instead of `LED_BUILTIN`. Then he uploads it to his board with switches 5,6 and 7 ON. **Then he plugs-off the board and turns switch 7 OFF**, so only switches 5 and 6 are on. Then he plugs board back in and it works!

I tried it and it works for me, hooray!

Also, if anyone can tell me what language this guy speaks in the video tutorial I [posted](https://www.youtube.com/watch?v=VfwvVi0rnLQ) - I am just curious! :)


message:
Programming ATtiny85 with Arduino-IDE and an 8MHz external oscillator

I have a *digispark* ATtiny85 development board and I am using the Arduino IDE to program it along with the Arduino UNO as my hardware programmer.

I have successfully burned the fuses for both the internal 1 and 8 MHz RC oscillators using the *original* Arduino as ISP sketch (you'll understand why I said *original* in a moment), but as my application needs precise timing, I would like to use an external oscillator, however, every time I tried to burn/program the bootloader/fuses using the Arduino IDE and using the *original* Arduino as ISP, the avrdude spits the infamous (Yikes).
I searched online and found an *updated* version of the Arduino as ISP sketch, which is supposed to an updated version, it has only one downside, which is, it can't do anything other than burn/program the bootloader/fuses, meaning that it can't be used to program the ATtiny85 like the *original* Arduino as ISP could do.

So without hesitating, I tested it to burn/program the bootloader/fuses for the internal 1 and 8 MHz RC oscillators, and it worked perfectly, and as expected, it fails to upload the code.
But the *original* Arduino as ISP successfully uploaded the code.
When I tried to burn/program the bootloader/fuses for the *external* 8MHz crystal oscillator using the *updated* Arduino as ISP, it worked flawlessly... until I noticed that the ordinary Arduino as ISP can not upload the code anymore and I am presented with the infamous (Yikes!) error.

Let me elaborate the difference in the *connections* between the two sketches.
The updated Arduino as ISP generates a clock signal on pin #9, which connects to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), while the *original* Arduino as ISP does not utilize this pin at all.

I found the updated Arduino as ISP on the *electronics stack exchange* forum, but unfortunately I lost the link to the question which contained why is this updated Arduino as ISP is better.
I can provide both codes though if someone needs them.

I have my crystal connected in both cases, burning/programming the bootloader/fuses and while trying to upload my code.

This is the infamous (Yikes!) error which I was talking about.
[![enter image description here][1]][1]

This is my current wiring.
[![enter image description here][2]][2]
Please note that I connect pin #9 to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), only when I am using the *updated* Arduino as ISP.

This is the *actual* wiring.
[![enter image description here][3]][3]

[![enter image description here][4]][4]

[![enter image description here][5]][5]

[![enter image description here][6]][6]

[![enter image description here][7]][7]

My two questions are:
1) How could I burn/program the bootloader/fuses of the ATtiny85 to use an external oscillator of 8MHz or 16 MHz?
2) How could I upload my application code after burning/programming the bootloader/fuses?

I hope the answers elaborate how the connections would differ, if it would.

Thank a lot in advance.

  [1]: https://i.stack.imgur.com/ebRAN.png
  [2]: https://i.stack.imgur.com/CPhVg.png
  [3]: https://i.stack.imgur.com/KbLK5.jpg
  [4]: https://i.stack.imgur.com/TPncu.jpg
  [5]: https://i.stack.imgur.com/Goypa.jpg
  [6]: https://i.stack.imgur.com/mJa0b.jpg
  [7]: https://i.stack.imgur.com/uOGMB.jpg

body:
If you look at the [Digispark Schematic][1] you'll see resistors and Zener diodes attached to XTAL1 and XTAL2:
[![Digispark Schematic with circuitry connected to XTAL1 and XTAL2 pins highlighted.][2]][2]

These are for the USB D+ and D- signals that the Digispark bit-bangs.  I deeply suspect that the crystal is just not going to resonate with these parts connected.

To get back to a working Digispark you'll probably have to inject signal onto XTAL1 again and reprogram the fuses to internal OSC.

  [1]: https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf
  [2]: https://i.stack.imgur.com/VHd1L.png


message:
I need a good battery reccomendation

I have simple project composed of an Arduino Nano, a HC-05 module, and a small toy DC motor controlled using a L293D driver, I want to be able to power this circuit entirely using a battery, here is what I tried:

-The motor/L293D combo works when the Arduino Nano is powered through it's USB jack, except the L293D is drawing power from the Nano, which I know is very bad practice, but I only did it for testing purposes.

-The HC-05 module also works fine when the Nano is powered through it's USB jack, as expected.

-However, the power received through the USB jack is not enough power for both the HC-05 and the L293D & motor simultaneously, if I want to change the PWM through the HC-05, I have to disconnect the motor, send the instruction, then disconnect the HC-05 and re-connect the motor.

-I have tried 3, pretty much new 9V batteries, none of them were enough to power anything, not the Nano board through the Vin pin, not an Uno board through barrel plug, not the motor, nothing, except a LED diode, I've read somewhere that most brands of these kinds of batteries don't actually provide nearly as much power as they claim, so that might explain it. (In case it's relevant, the brands I tried are VARTA, Uniross and Goldmen.)

-Someone gave me the idea of using an old mouse cable to power the Arduino, by taking the VCC and GND wires from the mouse cable and using those to power the Nano board through it's Vin and GND ports, it works, but not any components connected to it, not even the HC-05 module, which I even tried powering directly from the mouse cable, which lit up it's LED, but did not get it to work.

Honestly this isn't that relevant, I just wanted to make sure the Vin pin worked.

-Also, few side notes:

My multimeter mysteriously stopped working when I actually needed it, which is why I couldn't take any measurements.

The L293D datasheet and other pinouts suggest no less than 12V supply voltage, so maybe a 9V battery wasn't the right answer to begin with.

The power coming from the mouse cable is enough to power the DC motor independently, but not through the L293D, it says online the average output for these cables is around 5V, but without measurements I can't be sure.

The battery holder for the toy train that has DC motor inside accepts 1.5V batteries wired in series, and considering there's not much else there aside from the motor itself, it's safe to say that 3V is the minimum required voltage for the motor.

So, what battery do you think would be most suitable for my project?

And if it's not against the rules, what brand would you recommend?

body:
You could also use a 4 channel relay for making the motors work and they can be independent of using power from arduino and is really effective, I sometimes use it for high voltage optocoupling and can be used for small ones too all you need to do is build logic and everything would work fine I assume you know how to reverse polarity on a dc motor.
Relays are not power hungry and can be powered from arduino but if you could give it an external 5 volts that would be better.
Which in case of L293d driver is not the case you would require at least 12 volt to power the driver itself.


body:
The L293D has about a 2.6V drop on the output pins. That means for a 3V motor you need to provide about 5.6v for it to run at full speed. 5V will work, but it will run slightly slow and underpowered.

9V batteries are useless. Only any good for very low power applications like smoke alarms. They just can't provide the current you need.

Instead you need to be looking at model aircraft / drone suppliers for a "2S" battery (7.4V Li Poly / Li Ion) and a suitable 5V (or 5.6V if you can get it) UBEC (switching regulator).


message:
Where is the digitalPinToInterrupt macro defined

I am new to Arduino, and it's confusing to me how you can just write code in the IDE and use functions or macros such as `#define ISR()` in the avr-libc library without having to include the header file in the Arduino sketch.

I was trying to find where `digitalPinToInterrupt()` is defined, but had no luck. Any idea?

body:
Generally, if you want to find identifiers in your Arduino board support, you can run the [ctags program][1] on the libc and Arduino core files.  ctags is used as part of the [build process][2] in its effort to generate C++ declarations for you.  So it is generally available to you as an Arduino user.  You should find `ctags` or `ctags.exe` in:

> */path/to/arduino15*`/builtin/tools/ctags/`*version-number*`/`

This can be run against your board support in:

> */path/to/arduino15*`/packages/`*vendor*`/hardware/`*architecture*`/`*version-number*`/`

And your standard libraries found under directories in the form of:

> */path/to/arduino15*`/packages/`*vendor*`/tools/`*compiler-tool*`/`*version-number*`/`

If you're wondering what */path/to/arduino15/* would be on your system, it's [documented here][3] in terms of where the preferences file is stored.  The relevant paths containing and version numbers and architecture names should show in the verify/compile output when verbose mode is turned on in preferences.

Specific example
----------------

On my linux system with reasonably current versions of UNO-related things, my command-line would look like:

```none
~/.arduino15/packages/builtin/tools/ctags/5.8-arduino11/ctags \
    -f /tmp/output-file \
    -R \
     ~/.arduino15/packages/arduino/hardware/avr/1.8.3/ \
    ~/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/avr/include/
```

The resulting tag file can then `grep`ed or just opened and the following entries can be found, showing the filenames and line numbers to investigate:

```none
DigitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/circuitplay32u4/pins_arduino.h 138;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/ethernet/pins_arduino.h 79;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/gemma/pins_arduino.h 64;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/leonardo/pins_arduino.h 160;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/mega/pins_arduino.h 110;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_control/pins_arduino.h 120;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_motor/pins_arduino.h 115;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/standard/pins_arduino.h 79;" d
```

In the [case of an UNO][4] the `standard` [variant][5] is [the significant declaration][6].

---

There are different implementations of ctags.  The one used by the Arduino support files is [Exuberant CTAGS][7] and you may want to read [its documentation][8], to learn how to control the program to display differently to only search for specific identifiers, etc.  It is also typically used with editors that have some special support for the resulting tags file, to jump to definitions, like an IDE would.

  [1]: https://en.wikipedia.org/wiki/Ctags
  [2]: https://arduino.github.io/arduino-cli/latest/sketch-build-process/
  [3]: https://docs.arduino.cc/hacking/software/Preferences
  [4]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/boards.txt#L78
  [5]: https://arduino.github.io/arduino-cli/latest/platform-specification/#boardstxt
  [6]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/variants/standard/pins_arduino.h#L79
  [7]: http://ctags.sourceforge.net/
  [8]: http://ctags.sourceforge.net/ctags.html


body:
If you like to tinker with the files. Than platformio is great option to go with. It provides auto completion and much more advance functionality.

You can easy see where some function/mecro is defined, by just right click on the function than click on the "Go to definition" option.
[![Here is the picture][1]][1]

The file that contains the definition will be opened in the new tab. As for your current Macro check the image below
[![digitalPinToInterrupt macro definition][2]][2]

  [1]: https://i.stack.imgur.com/Ar9hq.png
  [2]: https://i.stack.imgur.com/9tPRn.png


message:
Digital pins are no longer outputting enough to click a relay

I've been working on a project for awhile now, and I ran into a problem a week ago I couldn't solve. I'm using an Arduino uno R3.

My project involves the use of 4 relays triggered by the digital pins. Write a HIGH value, relay clicks. Write a LOW value, relay unclicks. Rather simple.

One day, I come back to it to discover it can no longer click the relays. No changes were made to my code that worked previously. The relay light came on, but no click. Could it be that I sent HIGH to 4 at the same time? My theory is that I could've drawn too much power at the same time, weakening it in a way that causes it to not output as much as it did previously.

I tested a relay on a different board and it works perfectly fine.

body:
Not knowing the reference of your relay, my answer is generic but should suit your needs.

Relays need 2 things in order to work properly: a sufficient voltage source, and one that can provide enough current.
The Arduino output pins provide 5V on 5V boards or 3.3V on 3.3V boards. BUT, most Arduino GPIO can provide only 20 mA of current. That might not be enough for your relay. The solution here is to use a transistor to drive the relay.
Also, relay coils are inductive loads that generate voltage spikes when current is turned off. That voltage can rise much higher than 5V and damage your Arduino pins and weaken or destroy them. The solution to this problem is to add a flyback diode.

This is what a typical circuit with relay driven by an Arduino looks like:

[![enter image description here][1]][1]

When the Arduino pin is LOW, the transistor is turned off and no current goes through the relay.
When the Arduino pin turned ON, the transistor turns on fully saturated and the relay coil is energized.
When the Arduino pin is turned LOW, the coil generates a negative voltage and current is allowed to go through the diode, dissipating energy in the relay coil. More information on flyback diodes: https://en.wikipedia.org/wiki/Flyback_diode

  [1]: https://i.stack.imgur.com/grdIq.png


message:
NodeMCU and relay with VIN power

Have read a lot of different things online, and I just ain't sure yet.

I'm trying to hook up a NodeMCU to control some relays. And want to power the NodeMCU by the VIN pin.

Anyone know if this setup is possible?

Or should I do it in another way?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/IomMR.png

body: Looks fine to me, I don't see any issues, assuming the PSU has sufficient 'grunt' to power both, and most will have.


message:
Create a dead zone for joystick

I'm trying to create a dead zone so the joystick will turn the motor off completely when in the center position. It's much too sensitive and will start the motor if barely touched. How could I fix the code so the off position of the joystick is bigger? This is the original code.

```c++
#include <Servo.h> //Using servo library to control ESC

Servo esc; //Creating a servo class with name as esc

void setup()
{
  esc.attach(9); //Specify the esc signal pin,Here as D9
  esc.writeMicroseconds(1000); //initialize the signal to 1000
  Serial.begin(9600);
}

void loop()
{
  int val; //Creating a variable val
  val = analogRead(A0); //Read input from analog pin a0 and store in val
  val = map(val, 0, 1023, 1000, 2000); //mapping val to minimum and maximum(Change if needed)
  esc.writeMicroseconds(val); //using val as the signal to esc
}
```

body:
My method is to separate the direction from the magnitude:

* Subtract the "center" value to create a ± range
* Use the sign to indicate the direction
* Take the `abs` to give the magnitude
* Subtract the "threshold" value
* If negative set to zero

So, with example values:

```c++
int val = analogRead(0);          // Raw value
val -= 512;                       // Subtract center value (512)
int direction = val < 0 ? -1 : 1; // Direction is either -1 or +1
val = abs(val);                   // Remove the sign
val -= 10;                        // Subtract the threshold (10)
if (val < 0) val = 0;             // Anything below zero is now zero
// val is now 0-501 with a dead zone, and direction is -1 or +1.
```


body:
Here's how to create the new mapped range with a dead zone. I used `Servo.write()` which specifies the position in degrees because I couldn't understand what microsecond timings you need, but it should be easy to change it back. I've also added some debug statements to print `val` as the joystick is moved.

```c++
#include <Servo.h>

// Constants for servo angles in degrees.
const int SERVO_MIN = 0;
const int SERVO_MID = 90;
const int SERVO_MAX = 180;

// Constants for raw ADC values of joystick positions.
const int ANALOGUE_MIN = 0;
const int ANALOGUE_MID = 512;
const int ANALOGUE_MAX = 1023;
const int ANALOGUE_THRESHOLD = 100;

Servo esc;

void setup()
{
  esc.attach(9);         // Specify the esc signal pin as D9.
  esc.write(SERVO_MID);  // Move servo to mid position in degrees.
  Serial.begin(115200);
  Serial.println();
  Serial.println("Servo Test");
}

void loop()
{
  static int old_val = -1;   // Initialise to invalid value.
  int val = analogRead(A0);  // Read input from analogue pin A0.

  // Process val if it has changed.
  if (val != old_val)
  {
    old_val = val;
    Serial.print(val);
    Serial.print(", ");

    // Create the dead zone as per Majenko's algorithm.
    val -= ANALOGUE_MID;
    int direction = val < 0 ? -1 : +1;
    val = abs(val);
    val -= ANALOGUE_THRESHOLD;
    if (val < 0) val = 0;

    // Create a new mapped range with a dead zone.
    val *= direction;
    val += ANALOGUE_MID;
    Serial.print(val);
    Serial.print(", ");
    val = map(val, ANALOGUE_MIN + ANALOGUE_THRESHOLD, ANALOGUE_MAX - ANALOGUE_THRESHOLD, SERVO_MIN, SERVO_MAX);
    Serial.println(val);

    // Move servo to new angle in degrees.
    esc.write(val);
  }
}
```


body:
Note that in your case, the width of the input range (1023) is only very
slightly larger than the width of the output range (1000). You could
take this width difference (23) as the dead zone, and this would
simplify the arithmetics: now the linear parts of your map have a slope
of exactly 1, and you do not need multiplications or divisions.

The map is then:

* [0,  500] → [1000, 1500] (slope =1)
* [500, 523] →  1500 (slope = 0)
* [523, 1023] → [1500, 2000] (slope = 1)

In code:

```c++
/*
 * Map:
 *   [  0,  500] -> [1000, 1500]
 *   [500,  523] ->  1500
 *   [523, 1023] -> [1500, 2000]
 */
if (val < 500)
    val = 1000 + val;
else if (val < 523)
    val = 1500;
else
    val = (1500 - 523) + val;
```


message:
How to webClient.write() an image stored on a String?

My application runs on an ESP32-CAM.
It takes pictures and stores to SPIFFS.
Periodically SPIFFS is checked and if images are found:
1- The image is saved to a FTP server
2- The image is summited to a Web Service that returns some informations about the image
3- Values are saved to mySQL
4- The image is deleted from SPIFFS

To read the image from SPIFFS I use the following fragment of code:

    String imageName   = file.name();
    imageBuffer = "";
    while (file.available()){
       imageBuffer += char(file.read());
    }

The FTP transfer works perfectly with the following command:

    ftp.WriteData((uint8_t*)imageBuffer.c_str(),imageBuffer.length());

The service the image is submited for analizes works OK if I use the command:

    webClient.write(fb->buf,fb->len);

But as it is not usable in the current implementation of my project I am trying to work with:

    webClient.write((uint8_t*) imageBuffer.c_str(), imageBuffer.length());

I get no errors in return but it just does not work and the web service at the destination returns nothing.

What Am I doing wrong?

body:
You should not use `String` to store binary data.

Instead allocate yourself an array of `uint8_t` of the right size.

```c++
uint8_t *imageData;
size_t len = file.size();

imageData = alloca(len);
file.readBytes(imageData, len);

webClient.write(imageData, len);
```

With that said, without knowing what the rest of your program is doing I can only surmise that you're just blasting raw data at the web server and hoping it sticks. That's not how web data transfers work. You have to craft the upload page properly as multi-part mime form data. [Read this for more information](https://stackoverflow.com/questions/8659808/how-does-http-file-upload-work)


body:
OK, I got it to work as follows:

Not passing the binary anymore, passing the file name so the FTPPost function will do its own reading of the file on SPIFFS and will post in 256 bytes chunks.
The same strategy works with HTTP post to the WebService.

      File picFile = SPIFFS.open(fileName,FILE_READ);
      const size_t bufferSize = 256;
      uint8_t buffer[bufferSize];
      while (picFile.available()) {
        size_t n = picFile.readBytes((char*) buffer, bufferSize);
        if (n != 0) {
          ftp.WriteData(buffer, n);
        } else {
          Serial.println(F("Buffer was empty"));
          break;
        }
      }
      picFile.close();


message:
Arduino Uno's Timer maximum frequency using Timer Compare Interrupt, not Timer Output Pins (e.g. OC0A)

I want to achieve the generation of a custom binary signal over a digital pin at the highest possible frequency on Arduino Uno.

Using Timer's output pins (e.g. OC0A), one can get a pin to toggle at a maximum frequency of 16MHz (which corresponds to a sqaure wave of frequency 8MHz), as described here:
https://arduino.stackexchange.com/questions/19961/maximum-frequency-of-digital-signal-in-arduino-uno

However as far as I understand, Timer's output pins are only useful if one needs to generate a repetitive waveform such as a PWM or square wave, so it cannot serve my purpose which requires the generation of a custom binary signal.

Using the following code, I was expecting digital pin 9 to toggle at a frequency close to 16MHz too, since I use no prescaler and set the Compare Match Register value to 0:

    void setup()
    {
        DDRB = 1 << 1;  // Set D9 as OUTPUT

        cli();
        TCNT0 = 0; TCCR0A = 0; TCCR0B = 0;
        TCCR0A |= (1 << WGM01);  // CTC mode
        TCCR0B |= (1 << CS00);  // no prescaling
        OCR0A = 0;  // Highest timer overflow frequency possible
        TIMSK0 |= (1 << OCIE0A);
        sei();
    }

    ISR(TIMER0_COMPA_vect)
    {
        PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
    }

    void loop(){}

However in fact it appears to toggle at a frequency of only approximately 410kHz (which corresponds to a square wave of frequency 205kHz), as the below image shows:

[![Picture of the screen of an oscilloscope showing that the frequency at which the digital pin toggles is close to 410kHz][1]][1]

I used Timer0 but I get the same frequency with Timer1 and Timer2.

- How can one explain that using this code I get this toggle frequency on the digital pin ?
- How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

  [1]: https://i.stack.imgur.com/aeUoa.jpg

body:
> How can one explain that using this code I get this toggle frequency on the digital pin ?

Code takes time to execute. Your ISR, when compiled, looks like:

```
ISR(TIMER0_COMPA_vect)
{
 124: 1f 92        push r1
 126: 0f 92        push r0
 128: 0f b6        in r0, 0x3f ; 63
 12a: 0f 92        push r0
 12c: 11 24        eor r1, r1
 12e: 8f 93        push r24
 130: 9f 93        push r25
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
 132: 85 b1        in r24, 0x05 ; 5
 134: 92 e0        ldi r25, 0x02 ; 2
 136: 89 27        eor r24, r25
 138: 85 b9        out 0x05, r24 ; 5
}
 13a: 9f 91        pop r25
 13c: 8f 91        pop r24
 13e: 0f 90        pop r0
 140: 0f be        out 0x3f, r0 ; 63
 142: 0f 90        pop r0
 144: 1f 90        pop r1
 146: 18 95        reti
```

That's 18 assembly instructions, each needing between 1 and 4 clock cycles to execute.  Referencing the datasheet you can count the exact cycles needed and sum them up, yielding 31 clock cycles.

Toggling at maximum speed that would be 16MHz / 31 = 516kHz.

And then you have the rest of the code running between each call to the interrupt, so it's slower than that.

> How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

By not using interrupts, and writing a tight loop in assembly language.


message:
Converting an int to an unsigned char for display on a Nokia 5110

I've been working on a small project getting some images displayed in a Nokia 5110 screen via an Arduino. I've been getting it working, but one of the issues I have is that I would like to have a list on integers and convert that an unsigned char array that the display requires. Generally I have something like this which works out of the box.

    unsigned char src [] PROGMEM = {0x00, 0x00}

Surprisingly, I found that this also works

    unsigned char src [] PROGMEM = {255, 255}

But when I have a list like this

    int src [] = {255,255}

and try to convert it to an unsigned char array, things don't display correctly

    unsigned char new_src[2];

    for (int i=0; i<2; i++){
     new_src[i] = (unsigned char) src[i];
    }

When I try to display this, it's clearly broken. I thought simply casting the `int` to an `unsigned char` would be enough (it doesn't work even if I don't cast it).

Here's how I display the array (for 84x48, the above arrays were just an example) :

    Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);
    display.drawBitmap(0, 0,  src, 2, 48, BLACK);
    display.display();

On more note:

The end game is to have a file with a list of ints. I would then read that list of ints into an array and convert it into an unsigned char array and then display that.

body:
> The idea is that I would read a list of ints from a file ( I have
> several files that I would iterate through) and convert that list to
> the unsigned char array on each loop iteration.

The file could be a stream of bytes just as well as a stream of ints (or uints). If it were, no conversion would need to be done - just read a byte & store it, read a byte & store it, ....  If instead, it is a character representation of values, "37, 150, 8, ...", again, read the characters of one value, convert them to `int8_t` or  `uint8_t` and store them in your byte array. Look up the atoi() or sscanf() functions to do the conversion.


message:
Spectrabloom LED light box

I'm looking to make a DIY version of [Dan Conrad's Spectrabloom][1]. I've got an Arduinio Uno, a piece of code that uses PWM to randomly fade three 1w LEDs (one red, one blue and one green) and a [PicoBuck LED driver][2].

Question is - do I have to have two power supplies? One to power the PicoBuck and one to power the Arduino or can I have them all running off one supply? If the latter - can anyone give me pointers on the way to hook everything up?

  [1]: http://www.chromaccord.net/spectrabloom/
  [2]: https://learn.sparkfun.com/tutorials/picobuck-hookup-guide-v12

body: Three 1 Watt LED could potentially draw 600 mA total, exceeding the maximum draw for the Arduino. Each LED could draw 200 mA, exceeding (by 10x) the draw of a pin driver. So, yes, you need to supply the LEDs separately from the Arduino. Also, that driver is a constant-current driver, at 330 mA per channel. Your LEDs would prefer a constant voltage, chopped by PWM.


body:
> Question is - do I have to have two power supplies?

No, you can use one power supply for both. But you need to make sure, that the LED current is not flowing through the Arduino, since that can kill the Arduino. To do that, you need to connect the power supply to the LED driver and the Arduino in parallel. For example, lets assume you have bought a 5V wallwart/power supply, which is can provide enough current for your whole circuit (and some headroom for further development). Then you can connect the positive lead to the 5V pin of the Arduino and the Vin+ (positive supply voltage) pin of the LED driver. Also connect the negative lead of the power supply to ground on Arduino and Vin- (negative supply voltage) of the LED driver. That way the current for the LEDs comes directly from the power supply and doesn't need to flow through the Arduino, but past it.


message:
Electronics Laboratory

I would like to know if someone could explain to me how to create an arduino electronics laboratory with soldering iron etc. with a low budget <3

body:
I can't help with the whole laboratory, but I can suggest the free ArduinOscope mini-app to turn an Arduino UNO into an oscilloscope that uses your computer as the display. Here's the link to the Help topic that describes controls, features, and performance: <https://www.daqarta.com/dw_rroo.htm>.  This is a large macro script that comes with my Daqarta software <https://www.daqarta.com>. Please note that you don't have to purchase anything to use the DaquinOscope; a license is needed (after the trial period) only to use your sound card inputs, not the Arduino.  (You also don't need a license to use the sound card *outputs*, so you can use the free Daqarta Generator to create test signals.)

Enjoy!


body:
There won't be a really complete list, since there are many many tools, that one could use for an electronics/Arduino laboratory. Also low budget is relative, so you might wanna choose out of the below list based on your real budget and the actual price of the parts at your place. Also consider, that many tools can be bought very cheap, but these tools are often bad, which means, that you most likely will buy a better replacement product later (buying cheap means buying twice). Still a low budget can absolutely justify buying cheap at first (some bad tools is better than no tool).

Note: I will use Euro as currency here (as I'm from Germany), which can about be used interchangeably for US Dollar. Your mileage may vary.

- **Breadboards:** For working with Arduinos you wanna first build your circuits on a breadboard for testing. You should at least get one. I've seen 3-Packs of breadboards on platforms like amazon for about 12€.

- **Jumper-Wires (male-male/male-female):** These wires with attached dupont jacks will make it easier to prototype on breadboards.

- **Colored Wire spools:** I have a few spools with 4 different colors of 0.2mm² wire. You can use these for your PCBs and for breadboards. The different colors help to color code your wires for better overview. They cost a few € each.

- **Multimeter:** A simple multimeter, that can measure voltage, current and resistance and in best case has a continuity check mode. This is a very important base tool for all electronics. I think most multimeters from 15€ up would be ok.

- **Pliers and Wire cutter:** These are good for pressing and for cutting things. If you train a bit, you can even use the wire cutter for removing the isolation at the end of your wires. Technically a proper wire stripper is better, but I think using a wire cutter for the low budget start is totally ok. A wire cutter can go as cheap as 10-15€ for a decent one.

- **Soldering iron:** Don't buy one of these soldering irons, that go directly into the mains. Buy a little soldering station with basic temperature control and integrated holder and a sponge for cleaning the tip. It should also have the possibility to change the tip (when you need a smaller/bigger tip or when your tip is no good anymore). A few years ago I got one of these for about 15€. Going a bit higher will benefit you with a better solder station.

- **Solder wire:** You need to buy the actual solder. You should buy a spool of solder wire with integrated flux. Though most little spools have that. Depending on the exact solder wire it can be useful to also buy some flux (I'm currently using a flux pen), if the solder isn't flowing good enough.

- **Third hand with magnifying glass:** When soldering it is sometimes helpful, when you can put a part into a clamp (like the third hand) and then use your hands for soldering iron and solder wire. The magnifying glass (which is also hold by the third hand) can help with small parts and inspection of your soldering work. It often costs only a few €, but getting up a bit can give you better durability and stability.

- **Perfboard:** To build PCBs yourself you can most easily use perfboards. That are simple boards with solder pads for through-hole components. You can solder the components to the and then connect the pads via solder/wires. These are available with each pad not connected to anything else, or already connected like on a breadboard (I use these ones, like in [this answer][1]), or in stripes,... Building better PCBs would involve a more complicated process with chemicals or sending the PCB files to a manufacturer.

- **Heat shrink tubing/sleeves for wires and cables:** To isolate wires, you might want to get correspondingly sizes heat shrink tube. They slide onto the to-isolate place and then get heated with a heat gun or a lighter. They shrink down and so enclose the part for isolation.

- **Oscilloscope:** This is normally one of the most expensive tools. A decent oscilloscope can cost 250€ and up (into infinity). But you can sometimes get the big old oscilloscopes second hand (for example from ebay) as others upgrade to a digital oscilloscope. Or you can buy an USB oscilloscope, which works with your PC. I got one of these for about 50€. Or there are simple kits for standalone oscilloscopes (with limited capabilities) for 35€ and up. An oscilloscope is important for analyzing analog signals.

- **Logic Analyser:** This is used to analyze digital signals. Standalone logic analyzers are expensive, but you can get a USB version for about 10€. The opensource software sigrok can then be used to interface the logic analyser. This tools is really really useful in relation to its low price. For example: You can use it as debug tools by setting pins inside your code at special places. That gives a better view on the temporal code flow than the typical Serial output.

- **Hot glue gun:** Seems pretty basic, but I really often use my hot glue gun. You can fix things, protect them, build a supporting structure,... They only cost a few € plus a few for the glue sticks.

- **Scalpel and box cutter:** Cutting things is also important and these two are good at it. They only cost a few € and have interchangeable blades. Especially a fresh scalpel blade can make the cutting of light materials really smooth.

That's about, what I can think of currently.

  [1]: https://arduino.stackexchange.com/questions/73393/making-cases-for-projects/73395#73395