body:
Im building an RC car project and using 2 NRF24's for communication. I own an Arduino Uno, Nano and Nano Every. The NRF's work great with the Uno and Nano in any combinations but using a Nano Every either as TX or RX doesn't work.

I have tried the NRF24 and NRFLite and both say "Cannot communicate with radio".

When using the NRFLite library examples Basic_TX on the Uno/Nano and Basic_RX on the Nano Every, the Uno/Nano says transmission was successful even though the Every says "Cannot communicate with radio". This lasts about 1 second before the Uno/Nano says the transmission failed again. This happens every time you reset the Every. It is as if the NRF24 gets powered on but then is unable to communicate with the Every.

I am using power adapters for the NRF's and powering them through the 5v pin. No luck with capacitors either. Have swapped out all the wires and also double checked all connections.

Is there something wrong with the Nano Every? Does it work with a NRF24 for anyone?

I have completely ran out of ideas to fix this.
Thank you in advance

title: NRF24 and Arduino Nano Every usage

Answers: 1

body:
I stucked with the same problem too when use nRF24L01+ and Arduino Nano Every to transmit data to Arduino Uno with nRF24L01+. So I have solved the problem as follows below. I hope it could help you and for somebody else.

1. First of all you should add Arduino megaAVR Boards in the boards manager.

1.1 It is first necessary to add the URL of their Boards Manager JSON file in: File > Preferences > Additional Boards Manager URLs and Paste the link: https://raw.githubusercontent.com/amperka/iskra-boards/master/package_amperka_index.json

1.2. Then go to Tools>Boards Manager, search Arduino SAMD Boards and install it

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

1.3. Choose Arduino Nano Every in Tools>Board>Arduino megaAVR Boards>Arduino Nano Every

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

2. Upload the library for RF24. It must be compatible for architecture megaavr because  Arduino Nano Every uses Microchip ATmega4809. I use the latest version RF24-1.4.1.
Here is the link to the library: <https://www.arduinolibraries.info/libraries/rf24>

3. You should check whether you connected nRF24L01+ and arduino correctly.

The pinout of Arduino Uno is as follows:
5V - VCC if you connect nRF24L01+ via nRF24L01+ adapter (I use adapter)
or 3.3V - VCC without adapter

GND - GND

9 pin - CE

10 pin - CSN

11 pin - MOSI

12 pin - MISO

13 pin - SCK

not connected - IRQ

However, I use another pinout for Arduino Nano Every. When I use the same pinout as Arduino Uno it can't find nRF24L01+. You can check it in Serial Monitor by using a sketch below. If you get zeros in the third line, for example, something like this: RX_ADDR_P0-1 = 0x0000000070 0x0000000000. It means that Arduino Nano Every isn't connected to nRF24L01+ correctly and Arduino Nano Every doesn't see it.
I suppose the problem with the library of RF24 and it should be fixed. Perhaps I'm wrong and the problem with another things.

So I use the following pinouts for Arduino Nano Every:
5V - VCC if you connect nRF24L01+ via nRF24L01+ adapter (I use adapter)
or 3.3V - VCC without adapter

GND - GND

10 pin - CE

A3 - CSN (if you will get zeros in the third line RX_ADDR_P0-1 in Serial Monitor then change A3 to another one. You can vary pin from A5 and so on until A0). do not use A7 and A6 because on some model dev boards, A6 and A7 are analog input only.

11 pin - MOSI

12 pin - MISO

13 pin - SCK

not connected - IRQ

The sketch for checking:
```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(10,A3);  // for arduino nano every
//RF24 radio(9,10); // for arduino uno

const uint8_t num_channels = 128;
uint8_t values[num_channels];
void setup(void)
{
  Serial.begin(9600);
  printf_begin();
  radio.begin();
  radio.setAutoAck(false);
  radio.startListening();

  radio.printDetails();
  delay(5000);

  radio.stopListening();
  int i = 0;
  while ( i < num_channels )  {
    printf("%x",i>>4);
    ++i;
  }
  printf("\n\r");
  i = 0;
  while ( i < num_channels ) {
    printf("%x",i&0xf);
    ++i;
  }
  printf("\n\r");
}
const int num_reps = 100;

void loop(void)
{
  memset(values,0,sizeof(values));
  int rep_counter = num_reps;
  while (rep_counter--) {
    int i = num_channels;
    while (i--) {
      radio.setChannel(i);
      radio.startListening();
      delayMicroseconds(128);
      radio.stopListening();
      if ( radio.testCarrier() )
        ++values[i];
    }
  }
  int i = 0;
  while ( i < num_channels ) {
    printf("%x",min(0xf,values[i]&0xf));
    ++i;
  }
  printf("\n\r");
}
int serial_putc( char c, FILE * ) {
  Serial.write( c );
  return c;
}

void printf_begin(void) {
  fdevopen( &serial_putc, 0 );
}
```

Here is the correct output in Serial Monitor
the third line without zeros: RX_ADDR_P0-1 = 0xf0f0f0f0d2 0xc2c2c2c2c2
```
SPI Speedz = 10 Mhz
STATUS  = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1 = 0xf0f0f0f0d2 0xc2c2c2c2c2
RX_ADDR_P2-5 = 0xc3 0xc4 0xc5 0xc6
TX_ADDR  = 0xf0f0f0f0d2
RX_PW_P0-6 = 0x20 0x20 0x20 0x20 0x20 0x20
EN_AA  = 0x00
EN_RXADDR = 0x02
RF_CH  = 0x00
RF_SETUP = 0x14
CONFIG  = 0x0f
DYNPD/FEATURE = 0x38 0x38
Data Rate = 1 MBPS
Model  = nRF24L01+
CRC Length = 16 bits
PA Power = PA_HIGH
ARC  = 15
```

the next two lines are a list of available channels that should be read from top to bottom (i.e. we have 127 channels, еру channels are presented in 16-bit version, the first line is the first digit of each of 127 channels, the second line is the second digit of each of 127 channels).
```
00000000000000001111111111111111222222222222222233333333333333334444444444444444555555555555555566666666666666667777777777777777

0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

```

then the level of noisiness of the channels is displayed.
There are noise from the channel 09 to the channel 3f approximately.
this noise from my wifi router and some another electronics.
you should choose free channels for your purpose.
```
00000010114663444533233300000000001000011233544433221100112223212010000000000000000000000000000000000000000000000000000000000000

00200000035575656777697332111321022125625559643632551111000333012000000000100000010001000000001000000000000011010000000000000000

00000001135a9a767767c89a85646565866555645897434644445200121212122000000000000000000000001000000000000000011000000010000000000000

00101000035567667357878a51123341220322335373542222122000112313112000000001010000000001000000020000000010000000000000100000000010

11000011047587577457694521122232111121243247542232210100002222111000000000100002000002000000000000000000000000000010000000000000
```

Note:
1. Check Tools. There should be:
Board:Arduino Nano Every;
Registers emulation: "ATMEGA328";
Port:COM#(Arduino Nano Every).

2. some transmission errors can occur due to poor contacts between wires and pins of arduino, so the wires should be soldered.

If everything is ok, then you can use your sketches for the receiver and transmitter respectively. Good luck!

  [1]: https://i.stack.imgur.com/Jqag3.png
  [2]: https://i.stack.imgur.com/nowU0.png


body:
there. I am following this tutorial to build an energy monitor system.
The link is https://learn.openenergymonitor.org/electricity-monitoring/ct-sensors/interface-with-arduino
Everything works fine with an Arduino UNO on ADC A1, but I need to send the data to a WebServer, so I decided to do the same setup with ESP-WROOM-32 which has a wifi module. I read the value from pin 34, the code I am using is following
```
// EmonLibrary examples openenergymonitor.org, Licence GNU GPL V3

#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon1;                   // Create an instance

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

  emon1.current(34, 111.1);             // Current: input pin, calibration.
}

void loop()
{
  double Irms = emon1.calcIrms(1480);  // Calculate Irms only
  Serial.println(Irms);         // Irms
}

```
 The current is always 0, when I add a println(analogRead(34)), it always gives me back the maximum number 4095. I am confused when it is not working with the ESP32 but with Arduino UNO, the power supply for both is 3.3V.
[![enter image description here][1]][1]
[![enter image description here][2]][2]

Can someone help me, please? Thank you so much!

  [1]: https://i.stack.imgur.com/yipLh.jpg
  [2]: https://i.stack.imgur.com/q0a8r.jpg

title: CT Sensors with Arduino and ESP32

Answers: 0


body:
In my Arduino project, a string will be received. I understand using ```.indexof``` to find the placement of a certain character in the string. My problem is that I need to find the first occurrence of any letter A-Z and haven't found any resources regarding using ```or```  statements in an ```.indexof``` aka ```string.indexof("a" || "b" ....)```.

Is this something that is not possible using indexof functions and if so is there any function that I can use to solve this! Thanks!

title: Using index of to search for multiple characters

Answers: 1

body:
Here are two functions that I hope help in your endeavours. You can supply either a String or a char array and you should get the first position of an alpha character. Returns -1 if not present.

See https://www.arduino.cc/reference/en/language/functions/characters/isalpha/

Update:

Thanks to great comments from Edgar & Mat I have updated the functions with best practise and cost improvements.

```c++
int alphaPos(const char* str)
{
  for (int i = 0; str[i] !=0 ; ++i) {
    if (isAlpha(str[i]))
    {
      return i;
    }
  }

  return -1;
}

int alphaPos(const String& str)
{
  return alphaPos(str.c_str());
}

/*
    Usage:

    String bobble = "&&&88434a";
    int x = alphaPos(bobble);

    if (x != -1)
    {
      ...x has the position in the string
    }
    else
    {
     ...There is no alpha char present.
    }
*/
```


body: I would like to reset my ESP32 from the software, how do I do it and how to make it do this at regular intervals.

title: How to reset ESP32 after a certain duration?

Answers: 1

body:
Hope this helps.

```c++

uint32_t resetAfterMillis = 30000; // Reset after 30 seconds.
uint32_t lastResetWas;

void setup() {
   lastResetWas = millis();
}

void loop() {
  uint32_t now = millis();
  if (now >= lastResetWas + resetAfterMillis)
  {
      lastResetWas = now;

      // Whatever you want to do here
      ESP.restart();

  }

}
```


body:
I am new to using MPU 6050. I am stuck at a basic code of getting readings from the sensor. The code I used is attached below. Its the one with GY 521 breakout board. Concluding that my sensor is broken I have changed sensor and now using the third one. Still no luck. FYI I have run the i2c scanner code to check whether arduino(nano) can detect the sensor. The code responds to all the sensors I tried. I have no clue what I am doing wrong. If someone could provide some suggestions it would be helpful
```/*
    MPU6050 Triple Axis Gyroscope & Accelerometer. Simple Gyroscope Example.
    Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
    GIT: https://github.com/jarzebski/Arduino-MPU6050
    Web: http://www.jarzebski.pl
    (c) 2014 by Korneliusz Jarzebski
*/

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

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

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // If you want, you can set gyroscope offsets
  // mpu.setGyroOffsetX(155);
  // mpu.setGyroOffsetY(15);
  // mpu.setGyroOffsetZ(15);

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();

  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:     Serial.println("Stops the clock and keeps the timing generator in reset"); break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
    case MPU6050_CLOCK_PLL_ZGYRO:      Serial.println("PLL with Z axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_YGYRO:      Serial.println("PLL with Y axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_XGYRO:      Serial.println("PLL with X axis gyroscope reference"); break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:  Serial.println("Internal 8MHz oscillator"); break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:        Serial.println("2000 dps"); break;
    case MPU6050_SCALE_1000DPS:        Serial.println("1000 dps"); break;
    case MPU6050_SCALE_500DPS:         Serial.println("500 dps"); break;
    case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());

  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();

  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);

  delay(10);
}
```

title: MPU 6050 only reads 0 in output

Answers: 2

body:
I hope it is useful for debugging ...

Only a sketch I found ([here][1]), not remembering if I have tested ...

```cpp
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}
```

There is also a [long example sketch][2] ...

  [1]: https://playground.arduino.cc/Main/MPU-6050/#short
  [2]: https://playground.arduino.cc/Main/MPU-6050/#sketch

body:
You do not tell us what is the problem so my guess is address or level.
If you get "Could not find a valid MPU6050 sensor, check wiring!" this is an address problem. By default MP6050 uses x068 as I2C address. If you have something else connected to the bus, there might be a conflict. If so, connect AD0 to 3.3V (pull-up with a 2.2kOhms resistor) to set address to 0x69 (use I2C scanner in /example/wire to make sure).
If you see zeros, this might be a logic level problem:
To elaborate on the previous answer, the MP6050 is a 3.3V device. The GY 521 circuit has a voltage regulator (5V->3.3V) bUt on output it still uses 3.3V TTL logic level. With some noise, bad contacts or long wires, the Arduino may fail to read the I2C properly. Had similar problems, solved using a bidirectional logic level shifter between a Uno and the MPU6050. You can get pre-assembled 4-channels board (same size as GY521 board) for ~ 1US$. I hope this helps


body:
I am trying to flash STM32 "blue pill" using arduino IDE as mentioned in the link https://www.onetransistor.eu/2017/11/stm32-bluepill-arduino-ide.html#no-bootloader

Basically using MX linux as OS.

The following is the response
```
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink
$ ./st-flash --reset write ~/Desktop/generic_boot20_pc13.bin 0x8000000
2021-07-27T09:20:21 INFO src/common.c: Loading device parameters....
2021-07-27T09:20:21 INFO src/common.c: Device connected is: F1 Medium-density device, id 0x20036410
2021-07-27T09:20:21 INFO src/common.c: SRAM size: 0x5000 bytes (20 KiB), Flash: 0x20000 bytes (128 KiB) in pages of 1024 bytes
2021-07-27T09:20:21 INFO src/common.c: Attempting to write 22268 (0x56fc) bytes to stm32 address: 134217728 (0x8000000)
Flash page at addr: 0x08005400 erased
2021-07-27T09:20:21 INFO src/common.c: Finished erasing 22 pages of 1024 (0x400) bytes
2021-07-27T09:20:21 INFO src/common.c: Starting Flash write for VL/F0/F3 core id
2021-07-27T09:20:21 ERROR src/common.c: unknown coreid, not sure what flash loader to use, aborting!: 2ba01477
2021-07-27T09:20:21 WARN src/common.c: Failed to write flash loader to sram!
2021-07-27T09:20:21 ERROR src/common.c: init_flash_loader() == -1
stlink_fwrite_flash() == -1
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink
$
```
I am not finding any src/common.c program in any of the subfolders, hence unable to dwell into details of the unknown core ID error

STlink V2 is providing proper response for st-info --probe as below
```
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink
$ ./st-info --probe
Found 1 stlink programmers
 serial: 4a3307000e144c37514d4e00
openocd: "\x4a\x33\x07\x00\x0e\x14\x4c\x37\x51\x4d\x4e\x00"
  flash: 131072 (pagesize: 1024)
   sram: 20480
 chipid: 0x0410
  descr: F1 Medium-density device
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink
```

Please let me know if you can find any method resolve this error

title: STM32 "blue pill" st-flash error

Answers: 0


body:
I'm building what I thought was a simple Arduino Nano project... right up until it caught fire!

I am a long-time reader of stack exchange and I always find the answers to my questions somewhere on Google, but this seems to be a bit of a head scratcher.

The project is a 4 pin 7 segment LED screen with a timer that counts when Analog pin 0 receives a voltage signal of ~2.5-5v.

Testing the project worked as expected, but when I soldered everything together, I was getting static or white noise from the Analog pin with no voltage being supplied.

I figured I needed a Pull-Down resistor to keep the Analog pin grounded until it received a voltage signal to get rid of any interference.

I connected a 220ohm resistor DIRECTLY from GND and DIRECTLY to Analog Pin 0 and connected the voltage signal wire to Pin 0 as well.

When I actually tested the hardware while connected to the car battery, that's when it shorted out and caused a mini fire.

I was able to read the voltage with my multimeter before the chip burnt out, I was reading ~15.5v total. I'm guessing it's the car battery plus the input voltage on Pin 0.

I only do clean and precise soldering, so there were no unaccounted for connections.

I'm unsure if the issue was too many volts running through the Nano altogether or because I don't really understand how the Pull-Down resistor works and messed that up.

Please help me understand what the issue is and what I can do for a solution.

Thank you.

[![Schematic][1]][1]

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

title: Arduino Pull-Down Resistors

Answers: 2

body: You violated the voltage input specification of A0 by a lot. What happened is what I would expect. The input protection diode on A0 conducted the battery voltage (- the protection diode drop) into the VCC of the Nano, this overvoltage fried just about all semiconductors and possibly several of the passive components on the board. It sounds like they do what they do when abused and they let the smoke out destroying the Nano and possible several other components. Hopefully this explains what happened. If you had connected the resistor between A0 and the battery it might have survived.

body:
**Input power**

Car power systems operate between 13 and 15 volts when the car is running. Might be too high for the voltage regulator on the Nano. Mine is a AMS1117 which goes up to 15v. Sounds like that's what fried based on your description. Some fail closed circuit, so may have exposed the ATMega to 14v. There's some alternative voltage regulators with the same footprint that will go up to 20v or more input, look for one of those. SOT-223 footprint.

**Button**

The Nano/ATMegs has internal pullups. I'd use those; connect the one side of your button to ground rather than 5v, and the other to the Nano digital input. In your code, activate on LOW rather than HIGH. Then you can skip your external pullup.

**Pullups**

220 ohms is a very strong pulldown for the 5v signal. It will be seeing .11 watts of power dissipation. Use something higher like 10K or 100K. Put a 1K resistor on the 5v signal to limit it's current. You're Arduino is only sensing the voltage, so with a 10K to GND and 1K from 5v signal, the resistor divider will signal 4.5v, plenty for your Nano to detect "HIGH".


body:
I am trying use a HMI display. If I want to send a data, for example I want to write "TOPWAY" to 0x00000080 address it should like that:

        Serial.write(0xaa); // packet head
        Serial.write(0x42); // VP_N16 string write command
        Serial.write(0x00); // VP_N16 address
        Serial.write(0x00);
        Serial.write(0x00);
        Serial.write(0x80);
        Serial.write(0x54); //T
        Serial.write(0x4f); //O
        Serial.write(0x50); //P
        Serial.write(0x57); //W
        Serial.write(0x41); //A
        Serial.write(0x59); //Y
        Serial.write(0x00); //string end with "\0"
        Serial.write(0xcc); // packet tail
        Serial.write(0x33); // packet tail
        Serial.write(0xc3); // packet tail
        Serial.write(0x3c); // packet tail

I want to make a method like SendString(String abc) to send that like above. I need convert string a hex array and call in Serial.write(array[i]). Can you hep me?

title: How to convert a String to Hex array

Answers: 1

body:
I don't know anything about the particular display, but based on the information provided I hope this is at least shows the foundation of one way you could approach a final solution.

**Update:**
* Incorporated great improvements and a fix from Edgar in the comments.
* String overload.
* Display baud rate suggested by mehmet

```c++
#define DISPLAY_DEVICE Serial
#define DISPLAY_DEVICE_BAUD 9600

static uint8_t displayPktStart[] = {
    0xaa, // packet headchar
    0x42, // VP_N16 string write command
    0x00, // VP_N16 address
    0x00, // ...Fill
    0x00,
    0x80
  };

static uint8_t displayPktEnd[] = {
    0x00, // End of text
    0xcc, // packet tail
    0x33, // packet tail
    0xc3, // packet tail
    0x3c // packet tail
  };

void writeDisplay(const char* text)
{
  // Write packet headers
  DISPLAY_DEVICE.write(displayPktStart, sizeof displayPktStart);

  // Send text
  DISPLAY_DEVICE.print(text);

  // Write packet tail
  DISPLAY_DEVICE.write(displayPktEnd, sizeof displayPktEnd);
}

void writeDisplay(const String& text)
{
  writeDisplay(text.c_str());
}

void setup()
{
  DISPLAY_DEVICE.begin(DISPLAY_DEVICE_BAUD);
}

void loop()
{
  String msg = "TOPWAY";
  writeDisplay(msg);

  delay(2000);
  writeDisplay("Peanuts taste like chicken");
  delay(500);
  writeDisplay("");
  delay(1000);
  writeDisplay("No. Seriously");
  delay(2000);
}

```


body:
I have a Atmega328p IC without external Crystal (My target).

When I use a arduino to burn the bootloader to my target, the Arduino as ISP sketch changes the fuses of my target, so it tries to use its external crystal, which is not connected, So it cannot proceed the bootloader burn.

[![external crystal][1]][1]

How can I modify the Fuse settings while Burning bootloader with arduino?

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

title: How to Burn Bootloader with custom Fuses

Answers: 2

body:
You need to either adjust the current board fuse settings in `boards.txt` or create a new board variant that matches your settings.

For example the Uno is set up with:

```
uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0xFD
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex
```

body:
You can use [MiniCore][1] boards support package for Arduino IDE to work with nonstandard AVR boards or breadboard setups. This core has many settings in Tools menu to set different parameters of the board.

  [1]: https://github.com/MCUdude/MiniCore


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

  [1]: https://i.stack.imgur.com/WPIzj.png
For this device are the enable pins meant to be connected to PWM pins?
If so then how am I able to use this device with an arduino uno?
The uno does not have any pwm pins right?

title: L298N motor controller board EN pins

Answers: 2

body:
The uno pins are 3, 5, 6, 9, 10, 11.

See https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

Usage:
```c++
analogWrite(pin, value);
```

body:
The people over at [How to Mechatronics][1] have a great introduction to this board and using it with an Arduino Uno.

The enable pins are for turning the motors on and off. See the table for the different settings. [![Enable pin truth table][2]][2] But the EN pin is also used for controlling the motor speed.

PWM is used to adjust the speed the motors turn at. Rather than simply turning the enable pin fully “on” (i.e, full speed), PWM is used to adjust the voltage and thereby control the speed the motors turn.

So the short answer is yes, you can connect a PWM signal to the EN pins.  Yes a UNO can produce PWM (as answered by others)

  [1]: https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
  [2]: https://i.stack.imgur.com/7WDf3.jpg


body:
[![enter image description here][1]][1]
Hello I have 2 questions:
A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.
B) What is the purpose of the black plastic casing that I have pointed out?

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

title: L298 motor controller board

Answers: 1

body:
> A) do I have to remove any of the plastic casings that I have highlighted in order to make the motors move.

Those aren't "casings", those are diodes. They are part of the circuit and must be left alone.

> B) What is the purpose of the black plastic casing that I have pointed out?

That is a "jumper" and is used to connect the +5V pin to the internal 5V regulator so the board can be run from just the 12V input power supply. Remove that if, and only if, you want to supply 5V to the board separately from elsewhere.


body:
I'm testing the AW9523B IO expander with an Arduino Nano. I can't get the device to be recognized.

Using I2C scanner to find all attached I2C devices.

I've connected AW9523B to the correct pins to the SDA/SCL pints of the Arduino, with 5K pullups. INTN is connected to GND.

An EEPROM is also connected on the bus. The EEPROM is recognized on the bus. I swapped the SDA/SCL pins just to make sure, and still AW9523B was not found on bus.

I've tried changing the AD0 and AD1 pins to no avail.

I have a 22uf capacitor on the VCC.

Changing the AD0 pin does change the default state of a connected LED, so I'm fairly confident the chip is not dead.

I've also tried the two example sketches from:

> https://github.com/mrmx/AW9523B

Curious if anyone has gotten their AW9523B to work.

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

**Updated Working Schematic**
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/AEPAM.png
  [2]: https://i.stack.imgur.com/s99xR.jpg

title: AW9523B I2C on Arduino Nano

Answers: 1

body:
Transcribing and adding to the answer from the comments.

The [AW9523B][1] has a reset (RSTN) pin 23 which is internally pulled low by a 100K ohm resistor (i.e., default = reset). @Majenko suggests attaching a pull-up 10K ohm resistor to +5V (i.e., not reset) to enable the chip.

The data sheet schematics and section describing the reset function (pg14) seem to anticipate the RSTN pin being connected to an MCU GPO pin used to dynamically control the reset function.

  [1]: https://cdn-shop.adafruit.com/product-files/4886/AW9523+English+Datasheet.pdf


body:
Trying to program an ATTTYIN1614 with jtag2updi.

    https://github.com/ElTangas/jtag2updi

I was able to use this tool to program an ATTINY1626-XFR and ATTINY807-MNR, but I'm getting an error with ATTINY1614-SSFR.

    avrdude: Expected signature for ATtiny1614 is 1E 94 22
             Double check chip, or use -F to override this check.

title: Programming ATTiny1614; Unexpected Signature

Answers: 1

body:
I had the wrong ATTiny1614 selected. Needed to select the non-optiboot option.

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

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


body:
I need 2 PWM pins to oscillate at 25 KHz but they need to oscillate inverse to each other.  When one is high, the other must be low and vise-versa.

I want to do this with a Nano.

title: How do you get 2 PWM pins to inversely bitbang at 25 KHz on a Nano?

Answers: 1

body:
There are various solutions. I suggest using two PWM channels driven by
a single timer. This way you do not have to worry about synchronizing
two timers. You can configure the channels identically, except that one
of them would be in “non-inverting” PWM mode, while the other one would
be in “inverting” mode.

Here is how I would do it: use Timer 1 to drive pins 9 (PB1, OC1A) and
10 (PB2, OC1B) in fast PWM.

```c++
void setup() {
    // Configure Timer 1 for complementary PWM @ 25 kHz.
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    DDRB  |= _BV(PB2);    // set pin 10 = PB2 = OC1B as output
    TCCR1A = 0;           // undo the Arduino timer initialization
    TCCR1B = 0;           // ditto
    ICR1   = 640 - 1;     // period = 640 CPU cycles = 40 us
    OCR1A  = 320 - 1;     // OC1A HIGH for 320 CPU cycles = 20 us
    OCR1B  = 320 - 1;     // OC1B LOW for 320 CPU cycles = 20 us
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock at F_CPU
}
```


body:
this code runs fine until I add in the if statement surrounding the draw screen() method. upon clicking the screen, the program instantly crashes, turning the screen white. any help would be appreciated.

    "
    // IMPORTANT: Adafruit_TFTLCD LIBRARY MUST BE SPECIFICALLY
    // CONFIGURED FOR EITHER THE TFT SHIELD OR THE BREAKOUT BOARD.
    // SEE RELEVANT COMMENTS IN Adafruit_TFTLCD.h FOR SETUP.

    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_TFTLCD.h> // Hardware-specific library

    #include <stdint.h>
    #include "TouchScreen.h"
    #define YP A2  // must be an analog pin, use "An" notation!
    #define XM A3  // must be an analog pin, use "An" notation!
    #define YM 8   // can be a digital pin
    #define XP 9   // can be a digital pin

    // The control pins for the LCD can be assigned to any digital or
    // analog pins...but we'll use the analog pins as this allows us to
    // double up the pins with the touch screen (see the TFT paint example).
    #define LCD_CS A3 // Chip Select goes to Analog 3
    #define LCD_CD A2 // Command/Data goes to Analog 2
    #define LCD_WR A1 // LCD Write goes to Analog 1
    #define LCD_RD A0 // LCD Read goes to Analog 0

    #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin

    // When using the BREAKOUT BOARD only, use these 8 data lines to the LCD:
    // For the Arduino Uno, Duemilanove, Diecimila, etc.:
    //   D0 connects to digital pin 8  (Notice these are
    //   D1 connects to digital pin 9   NOT in order!)
    //   D2 connects to digital pin 2
    //   D3 connects to digital pin 3
    //   D4 connects to digital pin 4
    //   D5 connects to digital pin 5
    //   D6 connects to digital pin 6
    //   D7 connects to digital pin 7
    // For the Arduino Mega, use digital pins 22 through 29
    // (on the 2-row header at the end of the board).

    // Assign human-readable names to some common 16-bit color values:
    #define  BLACK   0x0000
    #define BLUE    0x001F
    #define RED     0xF800
    #define GREEN   0x07E0
    #define CYAN    0x07FF
    #define MAGENTA 0xF81F
    #define YELLOW  0xFFE0
    #define WHITE   0xFFFF

    Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
    // If using the shield, all control and data lines are fixed, and
    // a simpler declaration can optionally be used:
    // Adafruit_TFTLCD tft;
    int six;
    int hundred;
    int twenty;
    int ten;
    int four;
    int eight;
    int two;
    int twelve;
    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
    void setup()
    {
      Serial.begin(9600);
      Serial.println(F("TFT LCD test"));
      tft.reset();
      uint16_t identifier = tft.readID();

      tft.begin(identifier);
      tft.fillScreen(BLACK);

      six = random(1, 6);
      eight = random(1, 8);
      twenty = random(1, 20);
      hundred = random(1, 100);
      four = random(1, 4);
      ten = random(1, 10);
      two = random(1, 2);
      twelve = random(1, 12);

      tft.setTextColor(WHITE);  tft.setTextSize(4);
      drawNumbers();

    }

    void loop() {

      six = random(1, 6);
      eight = random(1, 8);
      twenty = random(1, 20);
      hundred = random(1, 100);
      four = random(1, 4);
      ten = random(1, 10);
      two = random(1, 2);
      twelve = random(1, 12);
      if (ts.getPoint().z != 0) {
        drawNumbers();
      }

    }

    void drawNumbers() {
      tft.setCursor(0, 0);
      tft.fillScreen(BLACK);
      tft.println("D2: " + String(two));
      tft.println("D4: " + String(four));
      tft.println("D6: " + String(six));
      tft.println("D8: " + String(eight));
      tft.println("D10: " + String(ten));
      tft.println("D12: " + String(twelve));
      tft.println("D20: " + String(twenty));
      tft.println("D100: " + String(hundred));

    }"

this library seems largely ill documented, but this seems egreigous if its not on my end.

title: Using the touchscreen.getpoint causes program to instantly crash

Answers: 2

body:
**Updated:**
* Provided info not revelant.

I would approach the problem like this. What if anything is returned by getPoint.

```c++
  if (ts.getPoint().z != 0) {
    drawNumbers();
  }
```
To
```c++
  auto pt = ts.getPoint().z;
  Serial.print("Point: ");
  Serial.println(pt);

  if (pt != 0) {
    drawNumbers();
  }
```

This would tell me if I am getting a value back or if it is a problem elsewhere.

Hope this helps.

body:
Figured it out

the TFT screen im using forces the sharing of pins being used for analog and digital together. By starting my draw method with pinMode() i set the pins to be treated as the touchscreen's

    void drawNumbers() {
        pinMode (XM, OUTPUT);
      pinMode (YP, OUTPUT);
      tft.setCursor(0, 0);
      tft.fillScreen(BLACK);
      tft.println("D2: " + String(two));
      tft.println("D4: " + String(four));
      tft.println("D6: " + String(six));
      tft.println("D8: " + String(eight));
      tft.println("D10: " + String(ten));
      tft.println("D12: " + String(twelve));
      tft.println("D20: " + String(twenty));
      tft.println("D100: " + String(hundred));

    }


body: I would just like to ask if this microcontroller can power or can manage 2 servos, 2 motors, and 2 hc-sr04 ultrasonic distance sensor combined? Also, does this board come with a bluetooth module?

title: NodeMCU ESP32 as a replacement for my arduino project

Answers: 1

body:
The ESP32 has more than enough free GPIOs to manage those peripherals. Also, the ESP32 does indeed come with a bluetooth module.

Your question about powering these peripherals very much depends on their power requirements. I would not count on being able to run motors or servos from the internal power supply of a NodeMCU board, so you would need an external supply.

Also, note that the ESP32 is a 3.3V device and might require logic level translation if you’re using 5V peripherals.


body:
How can I use a MC33926 Motor Driver like it is offered for Arduino to drive forwards, backwards with a PWM and a direction control.

**The problem is that the MC33926 has Inputs IN1 and IN2 and not PWM and DIR as usual. How can IN1 and IN2 be directly used with a Arduino. Such as it is done in the ArduMower project.**

I'm also wondering under which conditions this is controller is energy efficient? If the load has a flywheel effect (e.g. high RPM mower disk) reducing RPM would waste energy?

I know there are different shields that have logic to drive the inputs with PWM and DIR, but the ArduMower PCB 1.4 decided to hook it up directly. Here is a hardware solution by pololu (I wish i would understand these two NAND gates and the Q2, but that's another problem):

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

https://www.pololu.com/product/1213/pictures

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

title: MC33926 Brushed Motor Driver (Shield/Carrier)

Answers: 1

body:
I have figured this so far:

 - If the PWM frequency is too low, the load-free power consumption (100% PWM 200mA) of the
   motors increases(!) rapidly when driving slowly, e.g. 33% to 1A.
 - From a certain PWM frequency (>2kHz), the power consumption normalizes and driving more slowly requires less power.
 - MC33936 has IN1 and IN2, which are normally connected with IN1 = LOW and
   IN2 = PWM or IN1 = PWM and IN2 = LOW (not good for most MCs)
 - Alternatively you can use IN1 = PWM and IN2 = LOW / HIGH **BUT you must INVERT the PWM SIGNAL when running reverse**, i.e. IN1 = PWM and IN2 = LOW or reverse IN1 = ~PWM (inverted PWM) and IN2 = HIGH. Otherwise you start driving at 0 PWM with 100% motor power. This is quite tricky, too.
 - MC33936 has no freewheel (except if ENABLE = LOW) and brakes the
   motor to 0 when IN1 = IN2
 - MC33936 is a braking motor controller that actively sets the output RPM.
   of the motor according to PWM.


body:
I have, one program with only using printing array and other with serial write and print function for the array, while using serial write and print function I get these extra characters between the data as shown below, can anyone help me with this

Printing the array with print function

```c++
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    //Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}
```

[![Using Print Function][1]][1]

Using with serial write and print function for array

```c++
uint8_t a[13] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0X77, 0x88,
                 0x01, 0x02, 0x03, 0x04, 0x05};
int i;

void Print_Hexa(uint8_t num) {
  char Hex_Array[2];

  sprintf(Hex_Array, "X", num);
  Serial.print(Hex_Array);
}

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

void loop() {
  for (i = 0; i <= 12; i++) {
    Serial.write(a[i]);
    Print_Hexa(a[i]);
  }
  Serial.println();
  delay(100);
}
```

[![Using Serial write and Print function for array][2]][2]

  [1]: https://i.stack.imgur.com/VFLIa.png
  [2]: https://i.stack.imgur.com/HUDLP.png

title: Printing the array using print and serial write function in Arduino Uno

Answers: 2

body:
To store a 2 character string you need a 3 byte array, not a 2 byte array. This is because in C a string consists of the actual string data *and* a zero ("NULL") byte at the end to indicate where the end of the string is.

So you would need:

    char Hex_Array[3];

so it can store, for the number 0x69: `69\0`. Otherwise you overrun the array and corrupt other data that follows in the stack, and changing that other data corrupts your string by changing the "end of string" marker to some other random ASCII character.

body:
`Serial.write(some_byte)` writes a byte on the serial output. The
Arduino serial monitor tries to interpret the bytes it receives as text:

- `0x11` is a control character, displayed as “□”
- `0x22` is the ASCII code for the double quote (")
- `0x33` is the ASCII code for the digit 3.
- `0x44` is the ASCII code for the uppercase letter “D”
- etc.


body:
I have tried to follow along/reproduce the results from several sources for emulating the Nikon infrared remote trigger:

 - [Adafruit Guide](https://learn.adafruit.com/ir-sensor/overview)
 - [DIY Nikon ML-L3 IR Wireless Remote Hack with Arduino UNO](https://youtu.be/lk3DIUwNq2Q)
 - [Teardown and Project: Clone Nikon ML-L3 IR Remote and Emulation](https://goughlui.com/2013/12/06/teardown-and-project-clone-nikon-ml-l3-ir-remote-and-emulation/)
 - [Teach you how to DIY Nikon ML-L3 infrared remote control](https://www.programmersought.com/article/56665017649/) *did not read yet*
 - [Arduino wireless remote for Nikon DSLR](https://youtu.be/198oRcCQdP8)
 - [Arduino Nikon Infrared command code](https://www.christidis.info/index.php/personal-projects/arduino-nikon-infrared-command-code)
 - [Arduino – IR remote/ intervalometer for Nikon D80 DSLR](https://duino4projects.com/arduino-ir-remote-intervalometer-nikon-d80-dslr/)

I can read the signal from my remote trigger, but I cannot reproduce it with my Arduino setup. The signal I can receive (w/ TSOP38238 receiver diode) matches all of the signals given by the links above (there is some expected variance in pulse durations).

**I don't think my hardware is at fault:**

 - TSOP38238 receives @ 950 nm
 - my [IR LED](https://www.robotshop.com/media/files/pdf/datasheet-com-09349.pdf) is 940-950 nm per datasheet
 - my IR LED works (I can see it emitting when I point it at my phone camera)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/xF00k.png)

<!-- End schematic -->

**My Code:**

I have tried the code given in the links above, most don't use [Port Manipulation](https://www.arduino.cc/en/Reference/PortManipulation) and instead trial-and-error the delay durations to account for the overhead in Arduino functions. I have experimented with different values of the ```wait``` variable (8-13 microseconds) but have not gotten it working so far. I prefer to have my code versatile like this (no hard coded durations) so I can use it with other remotes in the future.

```
uint16_t Signal[] = [2050, 27800, 430, 1650, 430, 3650, 430, 65000]; // ON & OFF pulse durations (microseconds)
uint8_t wait = 13; // duration (microseconds) between pin state changes

// the setup function runs once when you press reset or power the board
void setup() {
    DDRB = B00000001; // set digital pin 8 to output
    PORTB = B00000000; // set digital pin 8 LOW
    Serial.begin(9600); // start serial monitor
}

// the loop function runs over and over again forever
void loop() {
    delay(1500); // wait a bit between sending signal
    sendSignal();
    sendSignal();
    // send signal twice, this is what the actual remote does
    Serial.println("Signal sent"); // message saying signal was sent
}

// function that sends the signal
void sendSignal(void) {
    for (int i = 0; i < sizeof(Signal)/sizeof(Signal[0]); i++) { // for each element in Signal array
        if (i%2 > 0) { // odd numbered index, is an OFF pulse
            PORTB = B00000000; // set digital pin 8 LOW
            delayMicroseconds(Signal[i]); // delay for OFF pulse duration
        } else { // even numbered index (including i=0), is an ON pulse, 38 kHz (26.3 usec period), 50% duty cycle
            unsigned long currentTime = micros(); // get current time
            while (micros() - currentTime < (unsigned long)Signal[i]) { // while still in ON pulse duration
                PORTB = B00000001; // set digital pin 8 HIGH
                delayMicroseconds(wait); // leave ON for time
                PORTB = B00000000; // set digital pin 8 LOW
                delayMicroseconds(wait); // leave OFF for time
            }
        }
    }
}
```

I hold my camera in direct line of sight of the LED (not blocking the receiver on the camera) from distances of ~2in to ~3ft away without success.

Has anyone tried this before? Is there a mistake in my approach or code?

title: Nikon IR remote trigger (ML-L3) emulator not working

Answers: 1

body:
Got it working. The problems were the ```delayMicroseconds``` input being too large (see comments) and the frequency mismatches.

I set up a script to time the code segments of interest and that allowed me to select the best wait duration. It looks like this:

```
while (i < 256) {
    /* your code to time here */
    i++;
}
i = 0;
unsigned long time = 10000000 + micros();
Serial.println(time);
```
Make sure to time the empty loop and subtract that from your readings w/ code. Take the difference between ```time``` read outs, subtract the printing statement overhead (which is dependent on how many digits it is printing, hence the ```10000000 + micros()``` to keep # of digits constant) and divide by 256.

I measured 4 different combinations to find the closest frequency match:

Command Type:|Wait duration (micro seconds):|Frequency (Hz):|% difference from 38 kHz
|:-:|:-:|:-:|:-:|
Port Manipulation|14|36990|-2.7 %
Port Manipulation|13|39960|5.2 %
digitalWrite|11|35980|-5.3 %
|**digitalWrite**|**10**|**38790**|**2.1 %**|

The final code ended up looking a lot like the one from [this link](https://www.christidis.info/index.php/personal-projects/arduino-nikon-infrared-command-code); counting off cycles of the on-off 38 kHz pulse.


body:
Since Core of ESP8266 upgraded to v.3.0 (now it is 3.0.2), I encounter errors using this library.

First, the deprecation of `byte` to `uint8` (hoped that an upgrade of NTP lib to 3.0.2 beta will solve it ), but now even using library's built in example file fails, show the same message regarding `byte` error.

Is there a workaround ?

    In file included from /home/guy/Documents/git/Arduino/libraries/NtpClientLib/examples/NTPClientESP8266/NTPClientESP8266.ino:38:
    /home/guy/Documents/git/Arduino/libraries/NtpClientLib/src/NtpClientLib.h:501:32: error: reference to 'byte' is ambiguous
      501 |     bool summertime (int year, byte month, byte day, byte hour, byte weekday, byte tzHours);
          |                                ^~~~
    In file included from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/cmath:42,
                     from /home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/xtensa-lx106-elf/include/c++/10.3.0/math.h:36,
                     from /home/guy/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/cores/esp8266/Arduino.h:34,
                     from sketch/NTPClientESP8266.ino.cpp:1:

EDIT 1 :: VERSIONS

[![pic1][1]][1]
[![pic2][2]][2]
[![IDE+Sketch file][3]][3]

  [1]: https://i.stack.imgur.com/05pVB.png
  [2]: https://i.stack.imgur.com/oXfH5.png
  [3]: https://i.stack.imgur.com/MrZ01.png

title: Error using `NtpClientLib.h`

Answers: 1

body:
The esp8266 Arduino 3 has breaking changes so library authors need to adjust their libraries to this changes. Check the repository of the library for the fixes.

The NtpClient library was marked as deprecated by the author. The reason was that there is a better way to work with NTP on ESP. Now the library was 'restarted' as an alternative to SDK functions because the author solved microseconds accuracy.

If you don't need microseconds accuracy, you don't need to use Arduino NtpClient library on esp8266 or esp32. The Espressif SDK have support to get the NTP time to internal RTC.

Both ESP Arduino cores have examples for NTP. For esp8266 it is the esp8266/NTP-TZ-DST example.

The NTP part should be in setup()
```
configTime(TIME_ZONE, "pool.ntp.org");
```
TIME_ZONE should be value from `TZ_` constants from `TZ.h`, for example I have
```
#include <TZ.h>
#define TIME_ZONE TZ_Europe_Bratislava
```

The SDK will keep the time with the internal RTC of the ESP and adjust it periodically from NTP server.

You can get the esp8266 RTC time time with
```
time_t t = time(nullptr); // epoch
struct tm *tm = localtime(&t);
uint8_t minute = tm->tm_min;
uint8_t hour = tm->tm_hour;
```

if you want to wait in setup() until the time is retrieved you can use
```
  time_t now = time(nullptr);
  while (now < SECS_YR_2000) {
    delay(100);
    now = time(nullptr);
  }
```


body:
I'm a little confused by the powering arrangements of the MKR 1010 WiFi. I need to power it on a breadboard from an external power supply. I will not be using a LiPo battery and I need it to work when the USB is disconnected.

Assuming there is no battery or USB connected, I think I need to apply power on the `Vin` pin (the pinout diagram on `arduino.cc` shows this as an input pin and `5V` as an output pin). However, the `5V` pin has a resettable fuse inline whereas `Vin` does not, which to me is counterintuitive.

So my questions are twofold:

1. What is the correct pin for supplying external power, and
2. What is the correct voltage to apply

title: What is the correct way to externally power a MKR 1010 WiFi

Answers: 1

body:
> What is the correct pin for supplying external power, and

VIN

> What is the correct voltage to apply

The bq24195 can accept between 3.9V and 17V according to the datasheet. However the power LED on the board may blow if you apply more than about 12v since it only has a 330Ω resistor with it.

----

The polyfuse on 5V is there to protect the USB's power connection incase the user makes a mistake and short circuits it. It's more for the protection of your computer's USB port than the MKR board itself.


body:
in order to minimise power consumption in a project using the Arduino Nano, I need to set pin D13 to HIGH after using it as SCK for transferring data to an SD card module (I use the `SD.h` module. I already read that there are issues, but trying `SdFat.h` somehow made the issue worse). The board is powered by 4*1.3 V batteries, which is within specifications of the chip. The onboard voltage regulator, the power LED and the built-in LED (connected to D13) are torn off the board.

So I power up the module via a MOSFET switch circuit, start the communication with `SD.begin(SDChipSelect)` and write something to the SD card. All of this works just fine. Afterwards, I call `pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);` (where `SDCLK == 13`) before powering off the whole module by closing the MOSFET switch and going to deep sleep forever.

The switch setup (using an n-channel MOSFET) is such that the SD module's VCC is always HIGH, but no current can flow to ground, if the switch is off. Hence I need to turn D13 HIGH, not LOW, in order to turn off the module completely. Changing MISO, MOSI pins didn't affect anything, so I don't change them.

**But**... instead of drawing something like 0.1 mA without anything attached, the Arduino draws around 1 mA, which I can't afford. Apparently, the reason is that D13 doesn't care that I want it to go to HIGH. I can confirm this directly by measuring its voltage as well as by measuring the current drop if I pull off the connection between the SD module's SCK and the D13 pin on the Arduino. If I pull off the wires connecting MISO, MOSI or even the MOSFET itself, power consumption doesn't change.

That being said, power consumption **is** low, if I never write to the card (i.e. if I turn D13 high at in the setup, never power on anything, do **not** initialise the module via `SD.begin(...)`, but go to deep sleep immediately).

What am I doing wrong? Do I somehow need to "end" the communication with the SD module, so I can turn D13 high or is there something special going on with this particular pin?

Here are the relevant parts of my code:

```
#include <LowPower.h>
#include <SD.h>

static const int GPSPower = 5;
static const int MP3Power = 2;
static const int SDPower  = 8;
static const int SDCLK    = 13;

void blink(int n) {
  for (int i=0; i<n; i++) {
    digitalWrite(9,HIGH);
    delay(50);
    digitalWrite(9,LOW);
    delay(200);
  }
  return;
}

void setup() {
  // this pin is used in 'blink' to power an LED for debugging
  pinMode(9,OUTPUT); digitalWrite(9,LOW);
  // Set all pins connected to MOSFET gates as low outputs.
  pinMode(MP3Power,OUTPUT); digitalWrite(MP3Power,LOW);
  pinMode(GPSPower,OUTPUT); digitalWrite(GPSPower,LOW);
  pinMode(SDPower,OUTPUT);  digitalWrite(SDPower,LOW);
  // this is D13
  pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);

  // if false, power consumption stays at ~0.1 mA
  // if true, two strings are written and power consumption stays ~1.0 mA
  if (false) {
    String filename = "test.txt";
    write2sd("firststring",filename);
    write2sd("anotherstring",filename);
    blink(3); // feedback for debugging
  }

  // never go into loop
  while (true) {
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  }
}

void loop() {
}

int write2sd(String data, String filename) {
  // power SD module
  digitalWrite(SDPower,HIGH);

  // check availability
  if (!SD.begin(SDChipSelect)) {
    // return early but power off the module first
    pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);
    digitalWrite(SDPower,LOW);
    blink(10); // indicates an error
    return 1;
  }
  // SD Card should be initialised now
  File file = SD.open(filename, FILE_WRITE);

  // write to file
  if (file) {
    file.println(data);
    file.close();
  }

  // CLK still runs at this point and causes power consumption of ~1mA
  // power it off
  pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);

  // turn off module power
  digitalWrite(SDPower,LOW);
  return 0;
}

```

title: Low Power, SD Card module and SCK

Answers: 0


body:
I have been trying to get a servo to sweep using an attiny13A. And i managed to get the servo to (kindoff) work by the help of a previous thread. But i'm now getting an issue. The servo only goes to 180 degrees and does not return to 0 degrees, instead it just keeps trying to go further then 180 degrees eventhough its not mechanicly capabel of doing so. Anyone have any idea how i can solve this? ( I need it for a small animatronic part) (also the servo is a generic 9gram servo and i have tested it on multiple servos, its the same result) thanks in advance

```
#define F_CPU 9600000
int servo = PB1;  //connect servo to PB1
long angle;
int pwm;
int counter = 0;
int LED = PB3;
#include <avr/io.h>
void adc_setup (void)
{
    // Set the ADC input to PB2/ADC1
  ADMUX |= (1 << MUX0);
  ADMUX |= (1 << ADLAR);
  // Set the prescaler to clock/128 & enable ADC
  // At 9.6 MHz this is 75 kHz.
  ADCSRA |= (1 << ADPS1) | (1 << ADPS0) | (1 << ADEN);
}
int adc_read (void)
{
  // Start the conversion
  ADCSRA |= (1 << ADSC);
  // Wait for it to finish
  while (ADCSRA & (1 << ADSC));
  return ADCH; // return the value
}
void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(servo, OUTPUT);  // set servo as output pin
  digitalWrite(LED, HIGH);
  delay(3000);
  pinMode(LED, LOW); //blink LED

}
void loop ()
{
 for(counter = 0; counter < 180; counter++)  //scan fril 0 degrees to 180 degrees
  {
    servoPulse(servo, counter);  // call the servoPulse function.
    delay(15);
  }

delay(1000);

 for(counter = 180; counter > 0; counter--)  // now scan back from 180 to 0 degrees
  {
    servoPulse(servo, counter);  // call the servoPulse function.
    delay(15);
 }
}
void servoPulse (int servo, int counter)
{
  pwm = (angle * 11) + 500;    // Convert angle to microseconds
  digitalWrite(servo, HIGH);
  delayMicroseconds(pwm);
  digitalWrite(servo, LOW);
  delay(50); // Refresh cycle of servo
}
```

title: ATTINY13A, Servo only makes half a sweep

Answers: 0


body:
For arduino nano.
I set digital pins 1,2,3,4,5 to HIGH (I do this using digitalWrite(pin,HIGH) for each pin). Does this mean that 5V is being sent through each of the pins so in total there is 25V going out from the arduino?
How is this possible?

title: Arduino voltage misunderstanding

Answers: 3

body:
Every pin gives you 5V on HIGH, yes, but these voltages don't add up.

Voltages are always measured between two points. In electronics we are defining one point in our circuit, that we use for all measurements, and call it ground. This is normally the negative pin of the power source.

Each pin has 5V in reference to the same ground, so they cannot add up (because that would mean the second 5V would be in reference to the 5V of the other pin, not in reference to ground). In the end they are connected in parallel to Vcc (where the power for the microcontroller is connected, in this case the 5V pin) of the Arduino (through the output drivers of the respective pin).

In the end this boils down to kirchoff's laws (if you want to research more about it). At a junction of connections, the voltage stays the same, but the current will be divided up between the connections.

body:
Imagine that I have 5 flagpoles. I go to each of those flagpoles and raise a flag to a height of 2 meters. Since I have 5 flags, each at a height of 2 meters, does that mean that my flags have a total height of 10 meters?

Well, that question doesn't make a whole lot of sense, because "total height of the flags" isn't really a meaningful quantity. It's true that if you add up all the heights, you get 10 meters, but that number doesn't have any real meaning. Nothing in the system is 10 meters high.

Likewise, suppose you set 5 output pins all HIGH. Those output pins are just like flags on flagpoles, and you're raising each pin to a "height" of 5 volts. Nothing in the system is at a voltage of 25 volts; it doesn't make any sense to talk about a "total voltage."

body:
It's a fascinating question. The Nano has 22 pins, all potentially set to output. D0 to D13, and A0 to A7.

So we have a total of 22 outputs. Now if they **did** add up then we could connect up a 5V battery and get 110V out of it! That might kill you! So clearly something is amiss here.

It's like when an employee has "20 years experience". Do they really have 20 times the experience they had in the first year, or do they have the same experience 20 times over?

The fact is that all 22 pins are all referenced to the same ground pin, so we really have 22 x 5V but all from the same starting point. So we really have 5V but with maybe a bit more current.

If you look at the datasheet, you don't even have 22 x the current you might have from one pin. The Atmega328P is specified to have a total of 200 mA current output.

Don't worry, setting all pins to output won't kill you. :)


body:
Hi i've a big problem with my project.
I realized a simple project with Arduino Uno: i've attached interrupt to pin 2 to read water flow.
If I power on Arduino from 5v usb all works as expected: my water counter (showed on an lcd) increase only if water pass trough the sensor flow.

But if poweron arduino with external 12v, the interrupt start immediately, also in no water passing trough sensor and also if i remove phisically the sensor from the circuit!!

Any suggest?

Flow sensor has 3 pins: vcc, gnd, data.

Data pin goes to pin 2 (interrupt), vcc to arduino 5v, and gnd with arduino gnd.

title: Arduino powered with 12v and interrupt noise

Answers: 0


body:
I am new to Arduino. I used Arduino IDE for upload code to ESP8266 module. I wrote an ATM application on the tiva-tm4c123 board. I am trying to connect to the application from the internet using telnet and ip address. I uploaded the example code of the ESPtelnet library to the ESP8266 module and connected the esp wifi module to the tm4c123 card by using uart. The ESP8266 module sends the data from the tiva card to the putty screen that I connect via telnet. But it does not transfer what I write from the putty screen to the tiva card. I couldn't find a function like telnet.read(). Is there a telnet function that will read the data from the Putty screen? I searched a lot but couldn't find it. If I find this function, I know that I can send the read data to the tiva card with Serial.write(telnet.read).ESP's RX and TX are connected to the tiva card. I created a wireless connection to the Putty screen.  When a char or string is entered on the telnet screen, it will send it to the tiva card with Serial write from the TX of the ESP8266.I want to write a code that will run in the following logic.

```
 if (telnet.available()) {
    Serial.print(telnet.read());
  }
```
Here is the example code
```/* ------------------------------------------------- */

#include "ESPTelnet.h"

/* ------------------------------------------------- */

#define SERIAL_SPEED    115200
#define WIFI_SSID       "****"
#define WIFI_PASSWORD   "****"

/* ------------------------------------------------- */

ESPTelnet telnet;
IPAddress ip;

/* ------------------------------------------------- */

void setupSerial(long speed, String msg = "") {
  Serial.begin(speed);
  while (!Serial) {
  }
  delay(200);
  Serial.println();
  Serial.println();
  if (msg != "") Serial.println(msg);
}

/* ------------------------------------------------- */

bool isConnected() {
  return (WiFi.status() == WL_CONNECTED);
}

/* ------------------------------------------------- */

bool connectToWiFi(const char* ssid, const char* password, int max_tries = 20, int pause = 500) {
  int i = 0;
  WiFi.mode(WIFI_STA);
  #if defined(ARDUINO_ARCH_ESP8266)
    WiFi.forceSleepWake();
    delay(200);
  #endif
  WiFi.begin(ssid, password);
  do {
    delay(pause);
    Serial.print(".");
  } while (!isConnected() || i++ < max_tries);
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
  return isConnected();
}

/* ------------------------------------------------- */

void errorMsg(String error, bool restart = true) {
  Serial.println(error);
  if (restart) {
    Serial.println("Rebooting now...");
    delay(2000);
    ESP.restart();
    delay(2000);
  }
}

/* ------------------------------------------------- */

void setupTelnet() {
  // passing on functions for various telnet events
  telnet.onConnect(onTelnetConnect);
  telnet.onConnectionAttempt(onTelnetConnectionAttempt);
  telnet.onReconnect(onTelnetReconnect);
  telnet.onDisconnect(onTelnetDisconnect);

  // passing a lambda function
  telnet.onInputReceived([](String str) {
    // checks for a certain command
    if (str == "ping") {
      telnet.println("> pong");
      Serial.println("- Telnet: pong");
    }
  });

  Serial.print("- Telnet: ");
  if (telnet.begin()) {
    Serial.println("running");
  } else {
    Serial.println("error.");
    errorMsg("Will reboot...");
  }
}

/* ------------------------------------------------- */

// (optional) callback functions for telnet events
void onTelnetConnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" connected");
}

void onTelnetDisconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" disconnected");
}

void onTelnetReconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" reconnected");
}

void onTelnetConnectionAttempt(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" tried to connected");
}

/* ------------------------------------------------- */

void setup() {
  setupSerial(SERIAL_SPEED, "Telnet Test");

  Serial.print("- Wifi: ");
  connectToWiFi(WIFI_SSID, WIFI_PASSWORD);

  if (isConnected()) {
    ip = WiFi.localIP();
    Serial.print(" ");
    Serial.println(ip);
    setupTelnet();
  } else {
    Serial.println();
    errorMsg("Error connecting to WiFi");
  }
}

/* ------------------------------------------------- */

void loop() {
  telnet.loop();

  // send serial input to telnet as output
  // this part read tiva and transmit to ESP
  if (Serial.available()) {
    telnet.print(Serial.read());
  }
}
//* ------------------------------------------------- */
```

title: Arduino ESPTelnet.h library read data from cmd screen

Answers: 1

body:
It appears to me that the library has been written to accept input terminated by a newline character.

```c++
    char c = client.read();
    if (c != '\n') {
      if (c >= 32) {
        input += c;
      }
    // EOL -> send input
    } else {
      if (on_input != NULL) on_input(input);
      input = "";
      }
```

It will keep adding characters to the input buffer until a newline character is detected, and then pass the contents to the `.onInputReceived` recieved handler.

If my understanding is correct, the best you can do without making alterations to the library itself is:-

```c++

  telnet.onInputReceived([](String str) {
      Serial.println(str);
  });

```

Again, if I'm right then the newline character will always need to be present to push the data through.

Hope this is useful.


body:
So I just got my first Arduino which is an Arduino Uno. I have a newer MacBook Air which doesn't have any USB ports so I thought I'd just use one of those USB-C to USB adapters.

I plugged it in and then searched for the Board in the Tools > Port menu. It was nowhere to be seen, only the `/dev/cu.Bluetooth-Incoming-Port` showed up.

To be clear, the Arduino did show signs of connectivity, it just didn't show up under the Port list. I'm also not 100% sure if it's an Arduino Uno since the company I bought it from said I should select Arduino/Genuino Uno in the Board menu which isn't an option anymore.

Is it a problem with my Arduino, my Laptop or my adapter?

title: Arduino Uno won't connect when using USB-C to USB adapter

Answers: 1

body: Maybe it is not original, and it uses different usb-serial chip than the original one. Popular converters for Arduino Uno clones are CH340 and CP2104. You may try to install the driver for these 2 chips.


body:
I have a pair of potentiometers, on the Arduino, the output seems to drift, by one or 2 digits, back and forth. I would prefer they were read as one fixed value, without variation when their knobs are not turning. You can see in the image, the first and second values are shifting back and forth slightly. How should I address this?

I'm thinking of making a standard deviation function, but then I thought that might be unnecessarily complex.

[![wandering pots][1]][1]

My code is that the 2 sensor values are setting points in an SVG polyline. Variance means extra points will get plotted, while the device waits for valid input.

How should I deal with the variance in potentiometer readings to avoid outputting noise?

Here's my source:

```cpp
/**Fucntion Defs**/
void svgHeader();
void svgFooter();
void polyLineBegin();
void polyLineEnd();

int Reset = 4;     //programmatically reset the arduino
int potX = A0;
int potY = A1;

int sensorValX = 0;
int sensorValY = 0;
int oldX = 0;
int oldY = 0;

int del = 2;       //a button on pin 2 for deleting drawn content
int delbutton = 0;
void setup() {
  Serial.begin(9600);
  pinMode(del, INPUT);
  svgHeader();
  polyLineBegin();
  delay(1000);
}

void loop() {
  // close the svg and start over
  if (digitalRead(del) == LOW ) {
    delbutton = 1;
    polyLineEnd();
    svgFooter();
    delay(5000);
    digitalWrite(Reset, LOW);
    digitalWrite(Reset, HIGH);
    svgHeader();
    polyLineBegin();
  } else {
    delbutton = 0;
    //Serial.println(delbutton);

  }

  //dont draw if its not changing
  sensorValX = analogRead(potX);
  sensorValY = analogRead(potY);
  if (sensorValX == oldX && sensorValY == oldY) {
    ; //dont do shi.
  } else {
    Serial.print(sensorValX);
    Serial.print(",");
    Serial.print(sensorValY);
    Serial.print(",");
    oldX = sensorValX;
    oldY = sensorValY;
    // Serial.println(delbutton);
    delay(1000);
  }
}
/**Functions**/

void polyLineBegin() {
  Serial.println ("<polyline points=\""); //x,y points go here

}

void polyLineEnd() {
  Serial.println ("0, 0\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");  //a dirty hack to avoid dealing with 1 last trailing comma.

}

void svgHeader() {
  Serial.println("<svg width=\"1023\" height=\"1023\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">");
};

void svgFooter() {
  Serial.println ("</svg>");
};
```

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

title: How do you handle sensor drift?

Answers: 4

body:
ok, once I got the idea I would need to do it in code, it became simpler to solve. In looking around the terms of quantization, the term thresh-holding came up, and I realized how to solve the problem.

I created a threshold value, and compared the difference between old and new variables.

    int threshold =3;
    int xVariance = abs(sensorValX-oldX);
    int yVariance = abs(sensorValY-oldY);
    if (xVariance >=threshold && yVariance >= threshold ||xVariance >=threshold || yVariance >=threshold){
      Serial.print(sensorValX);
      Serial.print(",");
      Serial.print(sensorValY);
      Serial.print(",");
     oldX=sensorValX;
     oldY=sensorValY;

    }else{
    ; //dont do shi.
     // Serial.println(delbutton);
    delay(1000);
        }

 now, when I turn either potentiometer, I get a response, and output I desire, but not while the device is just sitting there.

body:
Remove the analog component from your device.

Use a rotary encoder.

It will sense the knob rotation digitally.

One huge advantage is that you can easily select the sensitivity of the input. One click can advance the counter by .001 just as easily as advancing by a 1000.

https://duckduckgo.com/?q=rotary+encoder&iar=images&iax=images&ia=images

![enter image description here](https://cdn.hackaday.io/images/3405091516957678589.jpg)

body:
I think you *should* handle the trailing comma within the Arduino by using leading commas instead, but omit the first leading comma using a flag to indicate the first coordinate:

```cpp
bool firstCoordinate;

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        if (!firstCoordinate)
        {
            Serial.print(",");
            firstCoordinate = false;
        }
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}

void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    firstCoordinate = true;
}

void polyLineEnd()
{
    // Clean line ending.
    Serial.println("\" stroke=\"red\" fill=\"transparent\" stroke-width=\"5\"/>");
}
```

Alternatively, the first coordinate could be added to the line when it begins, then there is no need for a flag:

```cpp
void polyLineBegin()
{
    Serial.println("<polyline points=\""); //x,y points go here
    Serial.println(sensorValX);
    Serial.println(",");
    Serial.println(sensorValY);
}

void loop()
{
    . . .
    if (xVariance >= threshold || yVariance >= threshold)
    {
        Serial.print(",");
        Serial.print(sensorValX);
        Serial.print(",");
        Serial.print(sensorValY);
        oldX = sensorValX;
        oldY = sensorValY;
    }
    . . .
}
```

The thresholding technique is great, but, as an aside, I recently discovered this [excellent statistics library by Majenko][1] while working on a non-blocking averaging function for Arduino and looking at converting it into a class. I found that that library already does what I want.

  [1]: https://github.com/MajenkoLibraries/Average/blob/master/src/Average.h

body:
Some methods for "dealing" with the noise:

1. Take multiple samples. Calculate the average ("mean"). Discard the decimal. This is "oversampling" along with resolution reduction (but reduction of the now increased oversampled resolution).
2. Take multiple samples. Find the most common value ("mode").
3. Divide the value by 2 (or 4 if needed). This reduces the range of values and the sampled resolution but discards the noise portion.

The problem you are suffering from is "quantisation noise". This is because an analog signal and a digital signal are not completely compatible. The ADC converts the analog signal into a digital value by successively comparing it to smaller and smaller voltages in steps ("quanta"). There is a limit to how small the steps can get (the resolution), but an analog voltage doesn't adhere to those steps, it will always be somewhere between the final two steps. Sometimes it will be detected as the lower step, sometimes the upper step. By taking multiple samples and averaging them you are estimating how close to one step or the other the value is and "refining" the result. This is "oversampling" and is used to increase the resolution of the ADC at the cost of sample speed.

With those extra samples you can either say "It's this much closer to the upper step" (take the "mean"), or say "It's more likely to be nearer the upper step" (take the "mode") to try and "fix" the value to one of the steps.


body: we are currently working on a device that needs us to connect an sd card reader to 2 Arduino’s ( Uno and zero) , however, we just found that it is not possible to do so without a level converter , may we have some help about how to do the proper connection from the sd ( that is already connected to arduino zero) to the level converter and then to the Uno. We want to make sure that both microcontrollers work at the same voltage of 3.3V. The Arduino Uno works at 5V whereas the Zero works at 3.3V which is why we need the level converter

title: Using a level converter to adjust the voltage levels

Answers: 0


body:
well I am trying to get array size  to convert hex value to int value. but if I try to get size of array it returns every time 2. Actually .I dont understand. how to get array size, can you help me?

this is my code

    unsigned long w;

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

      uint8_t * packet = read_packet();
      Serial.println(sizeof(packet)); // PROMLEM IS HERE, IT RETURNS EVERYTIME "2"

      for (int i = 0; i < 4; i++)
      {
        Serial.println(packet[i]); //if i print the packet array all elements are here
      }

      /*
        for (byte i = 0; i < sizeof packet; i++) {
          w = w + ((long)(packet[sizeof packet - (i + 1)]) << (i * 8));
        }

      */
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

    uint8_t *read_packet() {
      static uint8_t buffer[4];

      buffer[0] = 0x00;
      buffer[1] = 0x32;
      buffer[2] = 0x32;
      buffer[3] = 0x32;

      Serial.println(sizeof buffer);
      return buffer;
    }
if I print the packet array, all 4 elements are there 0,50,50,50. but size of array returns every time "2". even if I increase the array size.

maybe you can think why am I using pointers? because of my previous question answer is using this method. https://arduino.stackexchange.com/questions/85326/read-serial-with-header-and-end-marker/85328?noredirect=1#comment194331_85328

title: Why I cant get sizeof a pointer Array

Answers: 2

body:
A pointer is just a pointer. It's not an array. On 8 bit Arduinos the memory address range is a 16 bit value, so a pointer will always be 2 bytes.

You need to return two values from your function - the buffer pointer *and* the length of the buffer. This is usually done by passing an extra integer pointer parameter:

```c++
unsigned long w;

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

  uint8_t plen;
  uint8_t * packet = read_packet(&plen); // Pass the pointer to the plen variable to store the length in

  Serial.println(plen); // This now prints "4"

  for (int i = 0; i < plen; i++) // You can now use `plen` here
  {
    Serial.println(packet[i]); //if i print the packet array all elements are here
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

uint8_t *read_packet(uint8_t *len) {

  static uint8_t buffer[4];

  buffer[0] = 0x00;
  buffer[1] = 0x32;
  buffer[2] = 0x32;
  buffer[3] = 0x32;

  if (len != NULL) *len = 4; // Store 4 in the length variable if provided

  return buffer;
}
```

body:
Majenko's answer explains things and shows how to fix your code, but the solution with static buffer inside the function is not common.

Common is to have `int readBuffer(unit8_t* buffer, size_t size)`.

The parameters are the buffer provided by the caller and the size of that buffer. The return value is the count of bytes written by the function into the buffer.

Real example:
```
int WiFiEspAtBuffStream::read(uint8_t* data, size_t size) {
  if (size == 0 || !available())
    return 0;

  size_t l = rxBufferLength - rxBufferIndex;
  if (l == 0 && size > rxBufferSize) // internal buffer is empty and provided buffer is large
    return EspAtDrv.recvData(linkId, data, size); // fill the large provided buffer directly

  // copy from internal buffer
  fillRXbuffer();
  for (size_t i = 0; i < l && i < size; i++) {
    data[i] = rxBuffer[rxBufferIndex++];
  }
  if (size <= l) // provided buffer was filled
    return size;
  return l + read(data + l, size - l); // handle the rest of provided buffer
}
```


body:
Following [this tutorial](https://forum.arduino.cc/t/simple-nrf24l01-2-4ghz-transceiver-demo/405123) I attempted making an NRF transmitter and receiver using an Arduino Nano. On the transmitter side I used the following code:
```c++
// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[10] = "Message 0";
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);
    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[8] = txNum;
}
```
The serial monitor prints
```
13:05:22.966 -> Data Sent Message 3  SimpleTx Starting
13:05:25.437 -> Data Sent Message 0  Acknowledge received
13:05:26.436 -> Data Sent Message 1  Acknowledge received
13:05:27.434 -> Data Sent Message 2  Acknowledge received
13:05:28.432 -> Data Sent Message 3  Acknowledge received
13:05:29.432 -> Data Sent Message 4  Acknowledge received
13:05:30.432 -> Data Sent Message 5  Acknowledge received
13:05:31.427 -> Data Sent Message 6  Acknowledge received
```
at 1 second intervals. I assume this points to an 'okay' transmitter. On the receiver side, I used the code
```c++
// SimpleRx - the slave or the receiver

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN);

char dataReceived[10]; // this must match dataToSend in the TX
bool newData = false;

//===========

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.startListening();
}

//=============

void loop() {
    getData();
    showData();
}

//==============

void getData() {
    if ( radio.available() ) {
        radio.read( &dataReceived, sizeof(dataReceived) );
        newData = true;
    }
}

void showData() {
    if (newData == true) {
        Serial.print("Data received ");
        Serial.println(dataReceived);
        newData = false;
    }
}
```
And the receiver gets flooded with data packets
```
13:06:20.318 -> Data received⸮SimpleRx Starting
13:06:21.798 -> Data received
13:06:21.831 -> Data received
13:06:21.831 -> Data received
13:06:21.864 -> Data received
```
The post also mentions that this is due to "most likely the Arduino is not communicating properly with its nRF24." Following the recommendations of post #30, later in the thread, the output of radio.printDetails() for the transmitter is
```
19:43:56.897 -> CheckConnection Starting
19:43:56.897 ->
19:43:56.897 -> FIRST WITH THE DEFAULT ADDRESSES aftCheckConnection Starting
19:43:58.355 ->
19:43:58.355 -> FIRST WITH THE DEFAULT ADDRESSES after power on
19:43:58.422 ->   Note that RF24 does NOT reset when Arduino resets - only when power is removed
19:43:58.488 ->   If the numbers are mostly 0x00 or 0xff it means that the Arduino is not
19:43:58.574 ->      communicating with the nRF24
19:43:58.621 ->
19:43:58.621 -> SPI Speedz = 10 Mhz
19:43:58.654 -> STATUS  = 0x7f RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
19:43:58.721 -> RX_ADDR_P0-1 = 0xffffffffff 0xffffffffff
19:43:58.754 -> RX_ADDR_P2-5 = 0xff 0xff 0x7f 0xff
19:43:58.788 -> TX_ADDR  = 0xffffffff7f
19:43:58.821 -> RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
19:43:58.854 -> EN_AA  = 0x00
19:43:58.887 -> EN_RXADDR = 0x7f
19:43:58.887 -> RF_CH  = 0x00
19:43:58.920 -> RF_SETUP = 0x00
19:43:58.920 -> CONFIG  = 0x00
19:43:58.954 -> DYNPD/FEATURE = 0x00 0x00
19:43:58.954 -> Data Rate = 1 MBPS
19:43:58.987 -> Model  = nRF24L01+
19:43:59.020 -> CRC Length = Disabled
19:43:59.020 -> PA Power = PA_MIN
19:43:59.053 -> ARC  = 0
19:43:59.053 ->
19:43:59.053 ->
19:43:59.053 -> AND NOW WITH ADDRESS AAAxR  0x41 41 41 78 52   ON P1
19:43:59.120 ->  and 250KBPS data rate
19:43:59.154 ->
19:43:59.154 -> SPI Speedz = 10 Mhz
19:43:59.186 -> STATUS  = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
19:43:59.253 -> RX_ADDR_P0-1 = 0x0000000000 0x0000000000
19:43:59.286 -> RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
19:43:59.320 -> TX_ADDR  = 0x0000000000
19:43:59.353 -> RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
19:43:59.386 -> EN_AA  = 0x00
19:43:59.419 -> EN_RXADDR = 0x00
19:43:59.419 -> RF_CH  = 0x00
19:43:59.452 -> RF_SETUP = 0x00
19:43:59.452 -> CONFIG  = 0x00
19:43:59.486 -> DYNPD/FEATURE = 0x00 0x00
19:43:59.486 -> Data Rate = 1 MBPS
19:43:59.519 -> Model  = nRF24L01+
19:43:59.552 -> CRC Length = Disabled
19:43:59.552 -> PA Power = PA_MIN
19:43:59.585 -> ARC  = 0
19:43:59.585 ->
19:43:59.585 ->
```
The same sketch when uploaded on the receiver gives,
```
19:48:38.260 -> CheckConnection Starting
19:48:38.260 ->
19:48:38.260 ->
19:48:38.260 ->
19:48:38.260 -> FIRST WITH THE DEFAULT ADDRESSES aftCheckConnection Starting
19:48:39.708 ->
19:48:39.708 -> FIRST WITH THE DEFAULT ADDRESSES after power on
19:48:39.774 ->   Note that RF24 does NOT reset when Arduino resets - only when power is removed
19:48:39.841 ->   If the numbers are mostly 0x00 or 0xff it means that the Arduino is not
19:48:39.941 ->      communicating with the nRF24
19:48:39.974 ->
19:48:39.974 -> SPI Speedz = 10 Mhz
19:48:40.008 -> STATUS  = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
19:48:40.075 -> RX_ADDR_P0-1 = 0x0000000000 0x0000000000
19:48:40.109 -> RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
19:48:40.141 -> TX_ADDR  = 0x0000000000
19:48:40.175 -> RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
19:48:40.208 -> EN_AA  = 0x00
19:48:40.242 -> EN_RXADDR = 0x00
19:48:40.242 -> RF_CH  = 0x00
19:48:40.274 -> RF_SETUP = 0x00
19:48:40.274 -> CONFIG  = 0x00
19:48:40.308 -> DYNPD/FEATURE = 0x00 0x00
19:48:40.308 -> Data Rate = 1 MBPS
19:48:40.341 -> Model  = nRF24L01+
19:48:40.374 -> CRC Length = Disabled
19:48:40.374 -> PA Power = PA_MIN
19:48:40.407 -> ARC  = 0
19:48:40.407 ->
19:48:40.407 ->
19:48:40.407 -> AND NOW WITH ADDRESS AAAxR  0x41 41 41 78 52   ON P1
19:48:40.474 ->  and 250KBPS data rate
19:48:40.508 ->
19:48:40.508 -> SPI Speedz = 10 Mhz
19:48:40.541 -> STATUS  = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
19:48:40.607 -> RX_ADDR_P0-1 = 0x0000000000 0x0000000000
19:48:40.640 -> RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
19:48:40.674 -> TX_ADDR  = 0x0000000000
19:48:40.707 -> RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
19:48:40.740 -> EN_AA  = 0x00
19:48:40.773 -> EN_RXADDR = 0x00
19:48:40.773 -> RF_CH  = 0x00
19:48:40.806 -> RF_SETUP = 0x00
19:48:40.806 -> CONFIG  = 0x00
19:48:40.840 -> DYNPD/FEATURE = 0x00 0x00
19:48:40.840 -> Data Rate = 1 MBPS
19:48:40.873 -> Model  = nRF24L01+
19:48:40.906 -> CRC Length = Disabled
19:48:40.906 -> PA Power = PA_MIN
19:48:40.939 -> ARC  = 0
19:48:40.939 ->
19:48:40.939 ->
```

There is some miscommunication as claimed by that post. I tried changing the pins of CE, CSN to 7,8 but the problem persisted for the receiver. I changed the power supply to the NRF using two alkaline AA batteries, but that didn't solve the problem either. I also connected a 10 μF capacitor between the power supply pins of the NRF, but no luck.
Next, I tried changing the NRF module. I used an NRF module which was working correctly as a transmitter(printing "Data Sent Message X  Acknowledge received") at 1 second, as intervals as a receiver in place, still the same problem.

Any help would oblige.

P.S: I am using Arduino clones, but they work for other purposes. The NRF's have "NRF24L01" stamped on the chip, and seem to be fine.

title: NRF24L01 receiver flooded with data packets

Answers: 0


body:
I don't have port, but when I want to compile my code (even empty files),
I encounter this error:

```
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
```
The code is:
```cpp
int LED_red=4;
int LED_yellow =2;
int green =0;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED_red,OUTPUT);
  pinMode(LED_yellow,OUTPUT);
  pinMode(green,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(LED_red,HIGH);
  digitalWrite(LED_yellow,LOW);
  digitalWrite(green ,LOW);
  delay(5000);
  digitalWrite(LED_yellow,HIGH);
  digitalWrite(LED_red,LOW);
  digitalWrite(green,LOW);
  delay(5000);
  digitalWrite(green,HIGH);
  digitalWrite(LED_yellow,LOW);
  digitalWrite(LED_red,LOW);
  delay(5000);
}
```
```
Sketch uses 998 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
```

I want a hex address for cordinate this code with Proteus, but it doesn't compile and dosn't give me hex address.

title: What should I do with stackOverflow in compile error?

Answers: 4

body:
What you are seeing is not an error.

Although your sketch is empty, there is Arduino framework code that gets created with it. This code actually calls your `setup()` and `loop()` functions so things operate as you would expect. It was designed this way to make it eaiser to get started.

body:
There is nothing to do.

What you are seeing is *not an error*. It is merely an informational message telling you how much of the available resources your sketch is using. Since it is using far less than the maximum available (as you would expect from an empty sketch) you have no problem.

You only need to worry about those figures when the "amount left" gets too small.

body:
> `Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.`

> `Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.`

This is not an error message. Rather, it's a message that results from a successful compile of your empty programme.

> `Sketch uses 998 bytes (3%) of program storage space. Maximum is 32256 bytes.`

> `Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.`

Neither is this an error message. Rather, it's a message that results from a successful compile of your more substantial programme.

To export the HEX file from the Arduino IDE for Proteus, go to:

- Menu bar -> Sketch -> Export compiled Binary

The short-cut is `Ctrl+Alt+S`.

You will find the .hex file in the same directory as your sketch.

body: You can change the processor settings from Tools-->Processor-->Atmega328P(Bootloader). It solved my problem.


body:
I have 3rd party device that create PWM output which I want to measure it with Arduino, the problem I have is when I shared ground between the two boards which cause the Pulsein output to become zero. (why this is happening, and how to fix it)

The reason I am connecting the ground since I need measure other signals on that board. (All other signals are responding fine)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/GaJd8.png)

<!-- End schematic -->

code:
```cpp
#define pulse_ip 3
unsigned long duration;
int ontime,offtime,duty;
float freq,period;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(pulse_ip, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  ontime = pulseIn(pulse_ip, HIGH);
  offtime = pulseIn(pulse_ip, LOW);
  period = ontime + offtime;
  freq = 1000000.0 / period;
  duty = (ontime / period) * 100;
  Serial.print(offtime);
  Serial.print("-");
  Serial.print(ontime);
  Serial.print("-");
  Serial.print(period);
  Serial.print("-");
  Serial.print(freq);
  Serial.print("-");
  Serial.print((duty * 255) / 100);
  Serial.print("-");
  Serial.println(duty);
  delay(1000);

}
```

title: Pulsein not working when share ground

Answers: 1

body:
Without connected grounds the signal on the input pin you read with pulseIn must be random noise.

Two `pulseIn` one waiting for HIGH change and second waiting for LOW don't make sense because for parameter HIGH, `pulseIn` **waits for the pin to go from LOW to HIGH**, starts timing, **then waits for the pin to go LOW** and stops timing. Then it returns the length of the pulse in microseconds.


body:
I have two Arduino Unos. On the first I can upload my sketch wittout any error, but with my second Arduino I always get this error, altough Im using the same settings:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xbf

What I tried:

 - different Usb Port
 - different Usb Cable
 - swapped the MCU on the board
 - restarted VSCODE

title: Why do I get this error when uploading a sketch on my arduino uno?

Answers: 0


body:
this code works perfectly if connected with usb cable. but as soon as i connect my **Arduino nano** with battery (two 18650 batteries in series connected to **VIN**) it runs loop only once. it sends only 0 to another **LoRa** module (3.3v) and i assume it runs loop only once. blink works without a problem.

    #include <SPI.h>
    #include <LoRa.h>

    int counter = 0;

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

      Serial.println("LoRa Sender");

      if (!LoRa.begin(433E6)) {
        Serial.println("Starting LoRa failed!");
        while (1);
      }
    }

    void loop() {
      Serial.print("Sending packet: ");
      Serial.println(counter);

      // send packet
      LoRa.beginPacket();
      LoRa.print(counter);
      LoRa.endPacket();
      counter ++;
      delay(3000);
    }

**Edit**

*battery pack voltage is 7.01v*.

connections I've tried so far:

 1. 2x **18650** -> **VIN** = Does **not** work
 2. 2x **18650** + regulator -> **5v** = Does **not** work
 3. 2x **18650** + regulator -> **USB** = Does work
 4. **USB** -> **USB** = Of course works

when I say it works I mean it **Arduino** powers up and **LoRa** module sends data but only once and looks like loop is running only once.

title: arduino nano with lora only runs once if connected to battery

Answers: 1

body:
Again, it would be nice to looking at how you have it set up.  You didn't mention any proper signal level conversion, so I'm going to assume there isn't any.  My best guess is one of the signals being produced by the Lora module is near the edge of being correct on the ATMega328P.

In comments I asked:
> If you measure the "5V" pin does the measured value read appear to be
> lower in the working scenarios and higher in the failing scenarios?

The reason for the question is that the logic levels of the ATmega328P are dependent on its VCC, what we're nominally calling "5V".

> when in working condition 5v output reads 4.48 but when using
> regulator and its failing 5v pin is constantly at 5.05v

By operating the 328P closer to 3.3V (when you're at 4.48), you're lowering the threshold voltage needed for the Lora's signals to reliably register as a HIGH on the Nano's pins.

You will likely need proper level conversion between the Nano and Lora module, but that will depend on the exact module.  Keep in mind that *if* your module says it has "5V tolerant" data pins, that doesn't mean it *produces* logic levels acceptable to a 5V Arduino Nano; it just means the module will accept 5V signals at its own inputs.