body:
I am exploring the ATmega328p MCU via a standard Arduino UNO, with the help of avr-gcc toolchain and AVRdude (All in the WINAVR package). I have successfully programmed the board a few times with it. However, when I try to read the fuse values via AVRdude, I get `0x0` for `lfuse`, `hfuse` and `efuse`.

I am using the following command (or its variants) to read:

```avrdude -c arduino -p ATMEGA328p -P com3 -b 115200 -v -F -U hfuse:r:hi_fuse_val.hex:h```

Following is the output I get:
```
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
```
The file `hi_fuse_val.hex` also has `0` written to it.
What am I doing wrong?

title: AVRdude does not read the FUSE byte values correctly

Answers: 1

body:
A couple of things.  That you can't change fuses from the bootloader and that optiboot can't report fuse values correctly, even if you change them.

No self-programming of fuses
----------------------------

A bootloader can't write fuses, at all.  The chip just doesn't allow self-programming of fuses.  If you want to change fuses, you'd need to resort to external programming (usually using the ISP protocol) with an AVR programmer (or another Arduino [set up to behave as one][1]).

Optiboot and reading fuses
--------------------------

Optiboot doesn't report fuses, at least not as compiled for UNO.

The "arduino" bootloader protocol used by the avrdude `-c arduino` option is a modified version of the [STK500(v1) protocol][2].  The are two commands there that would need to be implemented to read fuses, `Cmnd_STK_READ_FUSE` and `Cmnd_STK_READ_FUSE_EXT`.  They have [corresponding][3] [definitions][4] in the AVR Arduino core's copy of optiboot source.  But the places where they would be implemented in the series of `if`-`else`s [are absent][5].  Unlike writing fuses, reading fuses *is* possible from AVR code.  So it's not a limitation of the chip, the code to do it just isn't there.

Sidenote: You may notice that there are also definitions for commands that write FUSES.  These exist for STK500v1 programmers rather than bootloaders, which can implement these to support writing fuses.

For what it's worth optiboot doesn't actually read the signature of the chip either.  It just reports whatever values have been baked in [at compile time][6].  Both this and the not-reading-fuses above are probably done to keep optiboot as small as possible, which is its goal.

In any case, if you *do* change your fuses using a programmer, expect optiboot to continue reporting them as zero.

Current fuse values
-------------------

If you're curious about your actual fuses values, you run sketch that [reads them][7] and prints them over serial by using `#include <avr/boot.h>` and

```c++
Serial.print('E');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS), HEX);

Serial.print('H');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS), HEX);

Serial.print('L');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS), HEX);
```

  [1]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoISP
  [2]: http://ww1.microchip.com/downloads/en/Appnotes/doc2525.pdf
  [3]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/stk500.h#L33
  [4]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/stk500.h#L38
  [5]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/optiboot.c#L331
  [6]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/optiboot.c#L486
  [7]: https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html#ga37ce7078335dd85f04d150a52a01d6ad


body:
I'm trying to power an arduino and a few modules (RF receiver, two servos, and a laser diode) through one power supply.

I get jittery/unresponsive servos when hooked up in the following configuration:
* power supply goes to usb breakout, joins with top + and - rails, powers everything (tried
* all grounds go to top - rail
* black/grey/white wires going off right side are power/ground for the servos
* red, green, yellow wires going off left/top side are signals to the servos/laser
* purple wire going off left/top is ground for the laser

[![circuit photo][1]][1]

If I remove the orange wire (usb breakout to + rail) and plug another power supply into the Arduino, the poor performance disappears and everything works nicely.

Since my power supply is 2.5A, I doubt that I don't have enough power for this setup. This leads me to believe that the Arduino/receiver side of the circuit is making the voltage unstable so the servos misbehave. Is there a way I can isolate these two parts of the circuit (diode, capacitor?) so that I can power the whole setup with one cable?

Components:
* Arduino pro micro (5v)
* RF Link Receiver (WRL-10532, 434 MHz)
* Servo (ROB-09065, sub-micro)
* Laser diode (5V, 20mA)
* Micro USB breakout (1A)
* USB Micro power supply (5.1V, 2.5A)

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

title: How can I share one power supply between an arduino and servos?

Answers: 2

body:
You need to figure out your total current requirements. Don't guess, figure it out. What is the peak current draw of the servos? of the other components? Add everything up. If the total is within 20% of your power supply current, that may be the problem.

Also, servos tend to draw spikes of current. You might need to add a filter capacitor to the +5V rail on the Arduino to even out dips as the servos cause sags in current before the voltage regulator in your power supply can compensate. (Put the cap between +5V and ground right at the Arduino.)

body:
I too have found the servo driving of the Arduino ie UNO to be jittery. The problem is that the Arduino uses a timer, interrupts and software to terminate the pulse so if the processor is busy servicing another interrupt then the pulse gets extended by up to 10us. Modern servos, even the cheap ones, respond to this delay as if it were noise.

The servo library was dependent on clock frequency, and limited to pins 9 & 10, at one point in time, although that might have been fixed in updated versions. out of curiosity, what pins are you attaching your servos to? (9 or 10?)

you might try updating your version of the ardunio IDE/Libraries.

another thought, is that many servos are rated at 6V (not 5v), and while they will work, they may also be jittery. you might find it best to use a separate power supply. Be sure to connect the grounds of the Arduino and external power supply together.

From Servo.h:

    ...
        //attach(pin )  - Attaches a servo motor to an i/o pin.
        //attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds
        //default min is 544, max is 2400
    ...

    #define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo
    #define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo
    #define DEFAULT_PULSE_WIDTH  1500     // default pulse width when servo is attached
    #define REFRESH_INTERVAL    20000     // minumim time to refresh servos in microseconds
    ...

you might try tweaking the min, max, and default settings, or check your code against the settings provided by Servo.h.


body:
I bought myself a WEMOS D1 mini PRO (16MB) for creating a quite large project.

As I'm writing code, my memory is starting to grow.
When I looked at the Flash size in Arduino IDE, the only options I have are
 - FS 14MB, OTA: 1019KB
 - FS 15MB, OTA: 512KB

The only things I need in the project is OTA and EEPROM. (no need for SPIFFS)

I looked around on the internet and came on a couple of sites that manipulate the filesystem.
https://robotzero.one/arduino-ide-partitions/

Also on other forums I read that you could modify the LD scripts that Arduino uses.
But I'm not sure how to define the addresses and what to do.

Here is a visual of the config I want.

**ORIGINAL**

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

**ADJUSTED**

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

Can someone push me into the right direction ?

Thanks in advance.

  [1]: https://i.stack.imgur.com/xe8DY.png
  [2]: https://i.stack.imgur.com/SOh9s.png

title: How to adjust Partition Scheme Wemos D1 mini pro?

Answers: 0


body:
I'm in progress of making a stickman rush game, Until I hit a bug that I have been stuck on. I want to make a if statement that states "If the stickman and the object are in the same place, clear everything and print "Game over." But when i do this, the object is still there. I tried using "lcd.clear()" but it doesnt seem to affect anything. Is there another way to fix this?

Code:

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

byte customChar[] = {
  B01110,
  B01110,
  B01110,
  B00100,
  B01110,
  B10101,
  B00100,
  B01010
};

byte gameObstical[] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111
};

int vX = A0;
int vY = A1;
int sw = 8;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

int screenWidth = 16;
int screenHeight = 2;

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

  pinMode(vX, INPUT);
  pinMode(vY, INPUT);
  pinMode(sw, INPUT_PULLUP);

  lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();
  lcd.write(byte(0));

  lcd.createChar(1, gameObstical);

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManRow = 0;
  int obsticalRow = 0;

  int obsticalPosition2 = 0;
  int obsticalRow2 = 0;

  for (obsticalPosition = 15; obsticalPosition >= 0; obsticalPosition--) {
    lcd.setCursor(obsticalPosition, obsticalRow);
    lcd.write(byte(1));
    lcd.print(" ");
    delay(150);

    xPosition = analogRead(vX);
    yPosition = analogRead(vY);
    SW_state = digitalRead(sw);
    mapX = map(xPosition, 20, 1003, -500, 500);

    Serial.println("-----------");
    Serial.println(mapX);
    Serial.println(SW_state);
    Serial.println("-----------");

    if (mapX > 200) {

      lcd.clear();
      lcd.setCursor(stickManPosition, stickManRow);
      lcd.write(byte(0));

    } else if (mapX < -200) {

      stickManRow = 1;

      lcd.clear();
      lcd.setCursor(stickManPosition, stickManRow);
      lcd.write(byte(0));
    }

    if (stickManPosition == obsticalPosition) {
      if (stickManRow == obsticalRow) {

        lcd.clear()
        lcd.print("Game Over...");
        delay(150);

      }

      if (obsticalPosition == 12) {

        for (obsticalPosition2 = 11; obsticalPosition2 >= 0; obsticalPosition2--) {
          obsticalRow2 = 1;

          lcd.setCursor(obsticalPosition2, obsticalRow2);
          lcd.write(byte(1));
          lcd.print(" ");
          delay(150);
        }
      }
    }
  }
}
```
Any ideas? Thanks for reading.

title: How to completely clear everything from an arduino and print something new?

Answers: 0


body:
I am currently working on a drone project using multiwii.
I m using mpu6050 as gyro and accelerometer sensor with i2c protocol. I was able to read data coming from mpu6050 while using Arduino Uno through multiwii but can't get it work with Arduino pro mini. I was able to get data with pro mini while using i2c scanner and mpu6050 test codes available on web but can't see any data from sensor on multiwii platform though it shows that Arduino is connected. I tried using pull up resistors and try with another pro mini but with no luck. One note is that because I will be using this with a 1s lipo battery ,I bootloaded both pro mini with 8mhz internal oscillator at 3.3v and even tried using external oscillator 8mhz but with no luck (I actually modified both of them cause 3.3v Mini's are not available in my country). I am using Arduino Uno without ic to program the pro mini board and its having no problem while programing or while reading data on serial monitor but only with multiwii. I tried multiwii with my Uno and nano and both worked just fine so right now I m wondering if on board programmer effects this but I have seen some people using pro mini with multiwii
My connections are not lose at all cause I soldered them directly to the Uno board.

title: Problem getting data from Arduino pro mini

Answers: 0


body:
I have this code:
```
for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
}
```
which calls the function "multiLamp" and passes 3 int arrays with 2 values each. Here is the function:
```
void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],2);
    }
  }
}
```
This function is supposed to call some function "lamp" with a few integers from the arrays. In the beginning this works fine but after more than 50 calls of the "multiLamp" function the values in the arrays become {0,128,128} and {3,3,3} or something similar even though the values passed into it from my main code are equally valid as before (they are somehow changed after being passed to the "multiLamp" function).

I can't seem to find the issue here. Any help is appreciated!

**UPDATE:**

Here is the full code, although I don't know if it will be of any use because I wrote it to control some LEDs and if you don't have the setup it's difficult to see if the code is working or not.

```
int e[] = {12,13,11,10};
int xy[] = {2,3,4,9,6,7,8,5,1,A0,A1,0,A3,A4,A5,A2};

void setup() {
  for(int a=0;a < 4;a++){
         pinMode(e[a], OUTPUT);
         digitalWrite(e[a], LOW);
  }
  for(int b=0;b < 16;b++){
         pinMode(xy[b], OUTPUT);
         digitalWrite(xy[b], HIGH);
  }
}

void loop() {
  bigCubes(100);
  rain(20, 30);
  miniCubes(15);
  every(80);
}

void lamp(int epos, int xpos, int ypos, int del) {
  int xypos = 4*xpos+ypos;
  digitalWrite(e[epos], HIGH);
  digitalWrite(xy[xypos], LOW);
  delay(del);
  digitalWrite(e[epos], LOW);
  digitalWrite(xy[xypos], HIGH);
}

void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],1);
    }
  }
}

void every(int wait) {
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      for(int k = 0; k < 4; k++) {
        lamp(i,j,k,wait);
      }
    }
  }
}

void miniCubes(int wait) {
  int cube[8][3] = {{0,0,0},{0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,1,1},{1,0,1},{1,0,0}};
  for(int c = 0; c < 8; c++) {
    for(int it = 0; it < wait; it++) {
      for(int i = 0; i < 8; i++) {
        lamp(cube[i][0]+2*cube[c][0],cube[i][1]+2*cube[c][1],cube[i][2]+2*cube[c][2],2);
      }
    }
  }
}

void bigCubes(int wait) {
  multiLamp(new int[32] {0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3}, new int[32] {0,0,0,0,1,1,2,2,3,3,3,3,0,0,3,3,0,0,3,3,0,0,0,0,1,1,2,2,3,3,3,3}, new int[32] {0,1,2,3,0,3,0,3,0,1,2,3,0,3,0,3,0,3,0,3,0,1,2,3,0,3,0,3,0,1,2,3}, wait, 32);
}

void rain(int its, int wait) {
  int x2 = random(0,4);
  int y2 = random(0,4);
  int x1;
  int y1;
  for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
  }
}
```

title: int array passed through function has wrong values only after multiple passes

Answers: 1

body:
You are wrongly using the `new` operator for your arrays. That will dynamically allocate these arrays. They are put on the heap (not the stack like local variables) and thus don't get freed automatically, when the function exits. That has to be done by your code with the `delete` keyword. Your code just eats up all the available memory. Thats called a memory leak.

That you need to free your dynamically created variables is not an Arduino thing; this is correct for all C/C++ code. But the limited memory on AVR based Arduinos like the Uno makes it worse.

If you do the math, one iteration of `void loop()` will block 432 bytes of memory (216 array elements, each of type `int` thus 2 byte). The 2KB of memory (which is also needed for local and global variables) is eaten up rather fast.

I don't see, why you even would use dynamically created arrays. Why not just using locally defined arrays, like in the `miniCubes()` function?

---

That said, it is also a generally bad idea to use dynamic memory allocation microcontrollers, especially those with small memory. When creating and deleting objects of different sizes (which is the main advantage of dynamic allocation), you will leave small holes in your RAM, which are too small for one of your objects to fit. At some point your RAM is completely filled with these holes, so that no more memory can be allocated for your objects to save. Thats called memory fragmentation.

On your PC that isn't a problem because of 2 reasons:

- The PC has loads of RAM available, and
- the OS manages the RAM, defragmenting it, if necessary.

Since microcontrollers don't have an OS managing the RAM and often very limited RAM, you need to make sure, that your RAM doesn't get fragmented too much in the runtime of your code.


body:
I'm trying to run my **DS3218MG Servo Motor** with an external power supply and my arduino nano.

I'm using the following code:

    #include<Servo.h>
    Servo Myservo;
    int pos;
    void setup()
    {
    Myservo.attach(3);
    }

    void loop()
    {

    for(pos=0;pos<=180;pos++){
    Myservo.write(pos);
    delay(15);
    }
      delay(1000);

      for(pos=180;pos>=0;pos--){
    Myservo.write(pos);
    delay(15);
    }
      delay(1000);
}

According to the datasheet the servo needs a **DC 4.8-6.8** voltage. My first attempt was to only use the arduino and no external power supply. So did the following connections:

 - servo's **ground** to arduino's **ground**
 - servo's **+** to arduino's **5V**
 - servo's **data** to arduino's GPIO **pin** 3

Using this connection works fine and the servo rotatates to the desired positions. However, because the arduino does not supply enough current, i bought a power supply with the following specs:

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

With that, i did the following connections:

 - connect the **ground** of the power supply to arduino's **ground** (and servo)
 - keep the **data** pin
 - connect **+** of power supply to servo's **+**

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

Unfortunately, the servo does not move with the external power supply. IMO, it should have the right voltage and also supply enough current (at least as much as the Arduino).

Do you see the problem?

  [1]: https://i.stack.imgur.com/4l18Dm.jpg
  [2]: https://i.stack.imgur.com/fGJgLm.png

title: DS3218MG Servo - Not working with power supply

Answers: 1

body: @starcat,  regular  usb cable for  powering  arduino


body:
Recently I have been trying to install Arduino IDE 1.8.13, and I have ran into according problem.
When trying to launch Arduino IDE with ./arduino command it shows according error:

    ./arduino: line 35: /home/wiktor/Downloads/arduino-1.8.13/java/bin/java: No such file or directory

I have checked and java file does indeed exist.
I am using 32 bit version of Arduino IDE and 32 bit version of Linux Alpine 3.13.3.

Thanks for all answers

title: Arduino IDE 1.8.13 won't launch properly

Answers: 1

body:
Note: Below, [technician 274][1] (the original poster) commented:

> It ended up working, after following alpinelinux wiki and installing
> the IDE using flatpak.

---

Part of the problem is how confusing the message is.
`No such file or directory` is not actually referring to the java file.  It's referring to the ld-linux.so interpreter specified in the elf file.

If you run the `file` command on the java executable, you'll see output that looks like:
```None
./java/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.9, not stripped
```

If you look for `/lib/ld-linux.so.2`, you're going to find that you don't have one, and that's the file it's complaining about.

Alpine Linux apparently uses [Musl][2] and the java binaries were compiled for [glibc][3], which is normal for desktop Linux.  On a typical desktop Linux system, that the java that ships with the Arduino IDE was compiled for, all kinds of executables make use of ld-linux.so.2.  On your Alpine system, you'll find they're referring to /lib/ld-musl-i386.so.1 instead.  From this vantage point, it's more of a Linux problem than an Arduino one, but I thought it might as well have something of an answer to point people toward relevant looking resources:

* https://wiki.alpinelinux.org/wiki/Running_glibc_programs
* https://github.com/sgerrand/alpine-pkg-glibc

You may find it's easier to replace the java interpreter, but that won't be enough, because the Avrdude and GCC binaries will also expect ld-linux.so.2.

In the end, it may be easier to just not use Alpine Linux.

  [1]: https://arduino.stackexchange.com/users/75308/the-technician-274
  [2]: https://www.musl.com/
  [3]: https://www.gnu.org/software/libc/


body:
I found this example on how to create a project with AUnit tests: https://www.thecoderscorner.com/electronics/microcontrollers/embedded-testing/getting-started-unittesting-arduino/

According to it and projects I have found on github my project structure should look like this:

    Application
        src
            SomeComponent.cpp
            SomeComponent.h
        tests
            TestSomeComponent
                TestSomeComponent.ino
        Application.ino

But when I try to run TestSomeComponent.ino with Arduino IDE or VSC with Arduino plugin it does not see contents of src folder. I am assuming that it is treated as a separate sketch. What is a proper way to build and run tests?

[edit]
Some context (not sure what matters):

- Our target board is ESP32 DevKit v1
- Optimally if our developers could run tests on Windows and Linux machines
- I have not gotten yet to continuous integration. I will start automating once I have any test building and running

[edit 2]
I have tried command line tools. Got AUniter running and tried like this (hoping for some automagic done by tools):

    me@mypc:~/workspace/Application/Application/tests$ auniter.sh test esp32:/dev/ttyUSB0 TestSomeComponent/

I have tried any sane path combination in include path directive, for example:

    #include "SomeComponent.h"
    #include "app/SomeComponent.h"
    #include "../../src/app/SomeComponent.h"
    #include <SomeComponent.h>
    #include <app/SomeComponent.h>
    #include <../../src/app/SomeComponent.h>

But I keep getting this:

    TestSomeComponent:4:42: fatal error: ../../src/app/SomeComponent.h: No such file or directory

title: How to build and run AUnit tests

Answers: 1

body:
I eventually switched to PlatformIO. It took me less than half an hour to rearrange sources, fix some compiler issues, build and flash my device.
Tests work really well. You just need to keep tested sources in lib folder. I even got GoogleTest package so I can use gmock in my tests.


body:
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'
}
```

title: Alternative to a delay so it can be interrupted

Answers: 1

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.


body:
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.

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

Answers: 1

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.


body:
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.

Answers: 1

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


body:
Using an STM32L476RG Nucleo microcontroller board as the SPI master and an Arduino mega as a slave with pin 52 for SCLK, pin 53 for SS and pin 51 for MOSI on the Arduino. There is no issue with the STM32 transmission as the USB logic analyzer I'm using (parallel to the arduino) shows a correct output on the master side so this is an Arduino issue:
[![enter image description here][1]][1]

The problem is the Arduino isn't recieving properly. The arduino code:

        #include <SPI.h>
    #include<stdint.h>
    #define SPI_SCK 52
    #define SPI_MISO 50
    #define SPI_MOSI 51
    #define SPI_SS 53
    char dataBuff[500];

    //Initialize SPI slave.
    void SPI_SlaveInit(void)
    {
      // Initialize SPI pins.
      pinMode(SCK, INPUT);
      pinMode(MOSI, INPUT);
      pinMode(MISO, OUTPUT);
      pinMode(SS, INPUT);
      //make SPI as slave

      // Enable SPI as slave.
      SPCR = (1 << SPE);
    }

    //This function returns SPDR Contents
    uint8_t SPI_SlaveReceive(void)
    {
      /* Wait for reception complete */
      while(!(SPSR & (1<<SPIF)));
      /* Return Data Register */
      return SPDR;
    }

    //sends one byte of data
    void SPI_SlaveTransmit(char data)
    {
      /* Start transmission */
      SPDR = data;
      /* Wait for transmission complete */
      while(!(SPSR & (1<<SPIF)));
    }

    // The setup() function runs right after reset.
    void setup()
    {
      // Initialize serial communication
      Serial.begin(9600);
      // Initialize SPI Slave.
      SPI_SlaveInit();
      Serial.println("Slave Initialized");
    }

    // The loop function runs continuously after setup().
    void loop()
    {
      uint32_t i;
      uint16_t dataLen = 0;
      Serial.println("Slave waiting for ss to go low");
      while(digitalRead(SS));

      i = 0;
      dataLen = SPI_SlaveReceive();
      for(i = 0 ; i < dataLen ; i++ )
      {
        dataBuff[i] =  SPI_SlaveReceive();
      }

      //  Serial.println(String(i,HEX));
      dataBuff[i] = '\0';

      Serial.println("Rcvd:");
      Serial.println(dataBuff);
      Serial.print("Length:");
      Serial.println(dataLen);
    }

The message i'm transmitting is my full name and is 12 characters long. The master first sends the length of the message (12 in this case) so the arduino knows how many characters to recieve and then the message is transmitted. On the logic analyzer output everything looks fine and I can see the message. However I keep getting results like this in the Arduino serial monitor:
[![enter image description here][2]][2]

I should also note I'm using a sparkfun logic level converter between the master and slave to step the STM32 3.3v signal to 5v for the arduino input: (Imagine the arduino is not uno but master in the following image with the pins changed to the ones I've listed above)
[![enter image description here][3]][3]

I'm seeing no message next to 'Rcvd:' and a length of 0 most of the time, if not than a number much larger than 12. What seems to be the issue?

  [1]: https://i.stack.imgur.com/NdmS0.jpg
  [2]: https://i.stack.imgur.com/npk7t.jpg
  [3]: https://i.stack.imgur.com/FLM63.jpg

title: SPI Arduino slave not recieving data correctly

Answers: 0


body:
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.

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

Answers: 1

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.


body:
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?

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

Answers: 1

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){};
    }


body:
there i just got started with the arduino mega2560 . i tried 8x8 matrix tube and after ~30secs i found the atmega2560 a bit hot that i can melt a small amount wax on it ! is there any sort of heatsink or a better way to use the matrix tube ? what i have done is to turn on a led is to turn on the positive side and turn off the negative side . i just tried that method because in my 1st beginner kit , the manual said this should be done incase of a common anode rgb led .

thanks alot

title: it just gets too hot . any way of cooling it?

Answers: 0


body:
my use case is that I am building a distance sensor using Arduino Uno. The idea is when the distance is between a threshold, an SMS is sent from the device.

I am using DS3231, SIM800L, and HCSR04 for my needs.

I want to save power consumption too so I am trying to put my Arduino into a deep sleep and then wake up using RTC interrupt.

The code below works fine when the distance is NOT in the threshold. Meaning Arduino is waking up by the interrupt and then doing what it needs to do. However, if the distance is in between the threshold the SMS is sent and received but after that Arduino never wakes up again. I checked out the SQW pin DS3231, using a multimeter and the signal indeed is going LOW, but Arduino does not wake up again.

Libraries that I am using,
[ds3231][1], [Sim800l][2], [NewPing][3]

Here is the code that I am using,

```
#include <Arduino.h>
#include <avr/sleep.h>
#include <wire.h>
#include <ds3231.h>
#include <NewPing.h>
#include <Sim800L.h>

#define WAKEUP_PIN 2  // when low, makes 328P wake up, must be an interrupt pin (2 or 3 on ATMEGA328P)
#define LED_PIN 13  // output pin for the LED (to show it is awake)

#define TRIGGER_PIN 7
#define ECHO_PIN 6
#define MAX_DISTANCE 200 //max distance we want to measure in cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

// DS3231 alarm time
uint8_t wake_HOUR;
uint8_t wake_MINUTE;
uint8_t wake_SECOND;

static boolean goToSleep = false; //to track the when to go to sleep and when to get data and do stuff

#define SIM_MODULE_RX 10
#define SIM_MODULE_TX 11
Sim800L gsmModule(SIM_MODULE_RX, SIM_MODULE_TX);

///* A struct is a structure of logical variables used as a complete unit
// struct ts {
//    uint8_t sec;         /* seconds */
//    uint8_t min;         /* minutes */
//    uint8_t hour;        /* hours */
//    uint8_t mday;        /* day of the month */
//    uint8_t mon;         /* month */
//    int16_t year;        /* year */
//    uint8_t wday;        /* day of the week */
//    uint8_t yday;        /* day in the year */
//    uint8_t isdst;       /* daylight saving time */
//    uint8_t year_s;      /* year in short notation*/
//#ifdef CONFIG_UNIXTIME
//    uint32_t unixtime;   /* seconds since 01.01.1970 00:00:00 UTC*/
//#endif
//};
struct ts t;

// When WAKEUP_PIN is brought LOW this interrupt is triggered FIRST (even in PWR_DOWN sleep)
void sleepISR()
{
 // Prevent sleep mode, so we don't enter it again, except deliberately, by code
 sleep_disable();

 // Detach the interrupt that brought us out of sleep
 detachInterrupt(digitalPinToInterrupt(WAKEUP_PIN));

 // Now we continue running the main Loop() just after we went to sleep
}

// Double blink just to show we are running. Note that we do NOT
// use the delay for the final delay here, this is done by checking
// millis instead (non-blocking)
void doBlink()
{
 static unsigned long lastMillis = 0;

 if (millis() > lastMillis + 1000)
 {
  digitalWrite(LED_PIN, HIGH);
  delay(10);
  digitalWrite(LED_PIN, LOW);
  delay(200);
  digitalWrite(LED_PIN, HIGH);
  delay(10);
  digitalWrite(LED_PIN, LOW);
  lastMillis = millis();
 }
}

// Set the next alarm
void setNextAlarm(void)
{
 // flags define what calendar component to be checked against the current time in order
 // to trigger the alarm - see datasheet
 // A1M1 (seconds) (0 to enable, 1 to disable)
 // A1M2 (minutes) (0 to enable, 1 to disable)
 // A1M3 (hour)    (0 to enable, 1 to disable)
 // A1M4 (day)     (0 to enable, 1 to disable)
 // DY/DT          (dayofweek == 1/dayofmonth == 0)
 uint8_t flags[5] = {0, 0, 0, 1, 1};

 // get current time so we can calc the next alarm
 DS3231_get(&t);

 wake_SECOND = t.sec;
 wake_MINUTE = t.min;
 wake_HOUR = t.hour;

 // Add a some seconds to current time. If overflow increment minutes etc.
 wake_SECOND = wake_SECOND + 10;
 if (wake_SECOND > 59)
 {
  wake_MINUTE++;
  wake_SECOND = wake_SECOND - 60;

  if (wake_MINUTE > 59)
  {
   wake_HOUR++;
   wake_MINUTE -= 60;
  }
 }

 // Set the alarm time (but not yet activated)
 DS3231_set_a1(wake_SECOND, wake_MINUTE, wake_HOUR, 0, flags);

 // Turn the alarm on
 DS3231_set_creg(DS3231_CONTROL_INTCN | DS3231_CONTROL_A1IE);
}

void getDistance(){

 // Send ping, get distance in cm
 float distance = sonar.ping_cm();

 // Send results to Serial Monitor
 Serial.print("Distance = ");

 Serial.print(distance);
 Serial.println(" cm");
 delay(500);

 if (distance < 10.00)
 {
  //Setup Sim800 for sms sending
  gsmModule.begin(9600);
  bool err = gsmModule.sendSms("+91790xxxxxxx", "CLose");
  Serial.println(err);
  gsmModule.end();
  delay(3000);
 }

 //sleep arduino after the above operation
 goToSleep = true;
}

// Standard setup( ) function
void setup()
{
 Serial.begin(9600);

 // Keep pins high until we ground them
 pinMode(WAKEUP_PIN, INPUT_PULLUP);

 // Flashing LED just to show the µController is running
 digitalWrite(LED_PIN, LOW);
 pinMode(LED_PIN, OUTPUT);

 // Clear the current alarm (puts DS3231 INT high)
 Wire.begin();
 DS3231_init(DS3231_CONTROL_INTCN);
 DS3231_clear_a1f();

 Serial.println("Setup completed.");
}

// The loop blinks an LED when not in sleep mode
void loop()
{

 // Just blink LED twice to show we're running
 doBlink();

 // Is the "go to sleep" pin now LOW?
 if (goToSleep == true)
 {
  // Set the DS3231 alarm to wake up in X seconds
  setNextAlarm();

  // Disable the ADC (Analog to digital converter, pins A0 [14] to A5 [19])
  static byte prevADCSRA = ADCSRA;
  ADCSRA = 0;

  /* Set the type of sleep mode we want. Can be one of (in order of power saving):
   SLEEP_MODE_IDLE (Timer 0 will wake up every millisecond to keep millis running)
   SLEEP_MODE_ADC
   SLEEP_MODE_PWR_SAVE (TIMER 2 keeps running)
   SLEEP_MODE_EXT_STANDBY
   SLEEP_MODE_STANDBY (Oscillator keeps running, makes for faster wake-up)
   SLEEP_MODE_PWR_DOWN (Deep sleep)
   */
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Turn of Brown Out Detection (low voltage)
  // Thanks to Nick Gammon for how to do this (temporarily) in software rather than
  // permanently using an avrdude command line.
  //
  // Note: Microchip state: BODS and BODSE only available for picoPower devices ATmega48PA/88PA/168PA/328P
  //
  // BODS must be set to one and BODSE must be set to zero within four clock cycles. This sets
  // the MCU Control Register (MCUCR)
  MCUCR = bit(BODS) | bit(BODSE);

  // The BODS bit is automatically cleared after three clock cycles so we better get on with it
  MCUCR = bit(BODS);

  // Ensure we can wake up again by first disabling interupts (temporarily) so
  // the wakeISR does not run before we are asleep and then prevent interrupts,
  // and then defining the ISR (Interrupt Service Routine) to run when poked awake
  noInterrupts();
  attachInterrupt(digitalPinToInterrupt(WAKEUP_PIN), sleepISR, LOW);

  // Send a message just to show we are about to sleep
  Serial.println("Deep Sleep");
  Serial.flush();

  // Allow interrupts now
  interrupts();

  // And enter sleep mode as set above
  sleep_cpu();

  // --------------------------------------------------------
  // µController is now asleep until woken up by an interrupt
  // --------------------------------------------------------

  // Wakes up at this point when WAKEUP_PIN is brought LOW - interrupt routine is run first
  Serial.println("Awake");

  // Clear existing alarm so int pin goes high again
  DS3231_clear_a1f();

  // Re-enable ADC if it was previously running
  ADCSRA = prevADCSRA;

  goToSleep = false; //reset so that arduino does what it needs to do

 }
 else
 {

  //check if distance is less
  Serial.println("Checking");
  getDistance();
 }
}
```

  [1]: https://github.com/rodan/ds3231
  [2]: https://github.com/vittorioexp/Sim800L-Arduino-Library-revised
  [3]: https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home

title: Arduino unable to wake up using interrupt after sending SMS

Answers: 0


body:
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

title: Updating mysql data using SIM900 and Arduino

Answers: 1

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


body: The Wemos D1 mini won't show up on the new M1 Mac. I know it's related to the drivers but I just can't find a viable solution to the problem. Has anyone solved this?

title: Getting a Wemos D1 Mini to work with a M1 Mac

Answers: 0


body:
I have a program which measures temperatures every 30 minutes and sends them to a database. Immediately after running the program the first measurement is sent, however, the second (which should be sent after 30 min), is sent only after 1 hour. From then on the code works fine. The time is measured in millis. However, if I set the time difference to 28 minutes everything works fine from the beginning. What could be the reason for this? Is there a possibility that it goes to sleep mode? I don't understand why it works fine with 28 minutes and it stops working with 29 minutes?

Thanks in advance!

My code:

    if (millis() - sendDataPrevMillis > 1740000)
      {
        sendDataPrevMillis = millis();

    //other code

    }

The only part I change, so it works is setting millis from 1740000 (29 minutes) to 1680000 (28 minutes).

title: ESP32 millis not working properly

Answers: 1

body:
1) Although not strictly required, maybe use parentheses around `millis() - sendDataPrevMillis` for readability;
2) I guess you will have initialised `sendDataPrevMillis` to 0 but
the first time you assign `sendDataPrevMillis` to `millis()` some time will have elapsed since you evaluated. So calling `millis()` twice will give different results. That makes it less easy to see what is going on.

Suggestion to try:

    long HALFHOUR = 30 * 60 * 1000L;

    if ( (millis() % HALFHOUR ) == 0L ) {
        //measure and send
        //....
    }

Hope this helps.

NB: `%` is what is called the 'modulo operator' see: https://www.geeksforgeeks.org/modulo-operator-in-c-cpp-with-examples/


body:
I am trying the example [ros arduino publisher][1] using an [ESP32 Dev Module][2].
When I try to connect using rosserial I get "Uable to sync" error.
I have tried using different baud rates, 115200, 57600 and 9600
None of them worked. I clicked on the serial port monitor of the arduino IDE by mistake and saw this message:

    Rebooting...
    ets Jul 29 2019 12:21:46

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1100
    load:0x40078000,len:9232
    load:0x40080400,len:6400
    entry 0x400806a8
Not sure what to make out of the above error.
What am I doing wrong?
Thanks in advance.

  [1]: http://wiki.ros.org/rosserial_arduino/Tutorials/Hello World
  [2]: https://www.amazon.ca/gp/product/B07Z9VSXVP/ref=ppx_yo_dt_b_asin_title_o03_s01?ie=UTF8&psc=1

title: ESP32 ROS unable to sync

Answers: 0


body:
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!

title: MCU Recommendations for Audio Pitch Shifting

Answers: 1

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.


body:
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

title: Get a specific item from comma separated text

Answers: 2

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


body:
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

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

Answers: 1

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.


body:
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);
}
 ```

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

Answers: 1

body:
Your missing an else statement in your loop:

    else
      digitalWrite(led_pin,LOW);


body: 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)

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

Answers: 2

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.


body:
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.

title: Send values from Arduino Uno to Wemos D1 R1

Answers: 3

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/


body:
Does anyone have any documentation on this device?

Im just curious how it work out of the box and how to reference the on board temp and soil sensors.

Its a (for lack of a better name)a "ESP32 DHT11 WIFI Bluetooth Soil Temperature Humidity Sensor18650"
SKU:012592

[Item on DIYmore site][1]

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

  [1]: https://www.diymore.cc/products/esp32-wifi-bluetooth-cp2104-dht11-soil-temperature-humidity-sensor-18650-battery-base?_pos=13&_sid=c0fb7615d&_ss=r
  [2]: https://i.stack.imgur.com/uF2w2.jpg

title: Need documentation for Soil Sensor from DIYmore

Answers: 0


body:
I am in the middle of an automation project and suddenly after completing one stage of my assembly, I now need to scale it. So my computer which until now was sending data to only one arduino UNO can send to multiple arduino uno's, also I am seeking an advice, I am using up all the digital pins on my arduino Uno and this makes me think if I should upgrade to arduino mega or leave it the way it is.
The communication protocol I am using is UART which is done through USB from my computer to the board, so can I just use a USB hub to handle this issue?

title: Multiple arduino slaves with one master computer that sends instructions for the actuators to work

Answers: 0


body:
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

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

Answers: 1

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).


body:
I am trying to use an [ESP32-S2 feather board][1] with a separate bluetooth module, the [Adafruit BLuefruit LE UART Friend][2]. I previously used this bluetooth module with the Feather M0 Adalogger through UART without experiencing any major problems. Now, the bluetooth module does not even get past its begin function. In fact, in order for my program to even compile, I have to change the UART header and cpp files in the nRF51 library by commenting out Software Serial code (although, I don't actually use software serial) because the esp32 core does not have that library. Is this a matter of cores (esp32 as opposed to samd or avr) or something else entirely?

  [1]: https://www.adafruit.com/product/4769
  [2]: https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend

title: Trouble using bluetooth module with the ESP32s2 feather board

Answers: 0


body:
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.

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

Answers: 2

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 :/


body:
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.

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

Answers: 1

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.


body:
First of all I am kind of a noob working with microcontrollers, by the way I am using **Arduino IDE 1.8.13**

I fallowed the [hookup guide][1] to set up [Arduino IDE][2] to work with [Sparkfun ESP 32 Thing][3] board, and actually I was able to run the Arduino examples "Blink" and "Wifi" with no problem.

But my problem is when I tried to use the [DHT11][4] sensor, I did fallowed several tutorials like [this one][5] but for my bad fortune I did not succeed, instead I was getting NaN reading from the temperature and humidity sensor, at first I thought it might had something to do with the libraries version, which I installed and uninstalled several times, including the IDE, then using those same libraries I was able to do the exact same [example][6] on an [Arduino Uno][7] microcontroller.

Then I realized I did not find any example, tutorial or document using the Sparkfun ESP32 Thing with the DHT11 sensor, since most of the examples that I found are for the generic ESP32.

Which makes me wonder, how can I know if those two components are compatible at all?

Does any one has faced something similar using ESP32 Thing with DHT11 or any another sensor?, if yes, how did you make it work or what did you do instead?

However any piece of advise is welcome.

Thanks in advance!

  [1]: https://learn.sparkfun.com/tutorials/esp32-thing-hookup-guide
  [2]: https://www.arduino.cc/en/software
  [3]: https://www.sparkfun.com/products/13907
  [4]: https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf
  [5]: https://randomnerdtutorials.com/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide/
  [6]: https://create.arduino.cc/projecthub/pibots555/how-to-connect-dht11-sensor-with-arduino-uno-f4d239
  [7]: https://store.arduino.cc/usa/arduino-uno-rev3

title: Does the Sparkfun ESP32 Thing is compatible with generic modules like DHT11 sensor?

Answers: 0


body:
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.

title: Arduino RTC SD Card problem

Answers: 1

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;
}
```


body:
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

title: GPS Ublox neo-6mv2

Answers: 1

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.


body: 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?

title: Nrf24l01 smd pcb placement tips

Answers: 1

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


body:
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

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

Answers: 2

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.


body:
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

title: Scheduler comparison for Arduino Uno

Answers: 1

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.