# Question
Title: Animation of led strip with ESP32 does not work when WiFi is in use
I am using the ESP32 for a simple project. I know how to animate an led strip using atmega328p with arduino but when I animate it on the ESP32 it does not work that great. It will be nice if I can use the same ESP32 to run my entire project without having to include another MCU. **Has someone managed to be able to animate an led strip meanwhile using wifi on the ESP32** ?

This is the code I use to animate an LED stip meanwhile using wifi. I wrote this code myself so maybe I am doing something wrong. It works better than any of the libraries I have found online. The library that works best is esp32WS2811-master. But still this code works better than that library in my case.

```
#include <Arduino.h>
#include "WiFi.h"
#include <Adafruit_NeoPixel.h>

// we will runt the task that animates led strip on a separate core of arduino
TaskHandle_t Task1;

// where led pin is connected and number of leds to animate
#define PIN 32
#define NUM_LEDS 80

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

// mutex that helps enter critical sections meanwhile we animate led strip
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

// it will run on core 0 of esp32. Responsible for animating led strip.
void loop2(void *parameter)
{
   uint32_t _color = strip.Color(0, 0, 0);

   for (;;) // infinite loop
   {
      _color = strip.Color(0, 0, 255);

      // animation 1
      for (uint16_t i = 0; i < strip.numPixels(); i++)
      {
         strip.setPixelColor(i, _color);

         //portDISABLE_INTERRUPTS();      // arternative to portENTER_CRITICAL
         portENTER_CRITICAL(&mux);        /* start critical section */

         strip.show();

         //portENABLE_INTERRUPTS();       // alternative to portEXIT_CRITICAL
         portEXIT_CRITICAL(&mux);         /* end critical section */

         vTaskDelay(15);                  // one tick delay (15ms) in between reads for stability
      }

      // animation 2
      _color = strip.Color(0, 255, 0);
      for (uint16_t i = 0; i < strip.numPixels(); i++)
      {
         strip.setPixelColor(i, _color);

         //portDISABLE_INTERRUPTS();      // arternative to portENTER_CRITICAL
         portENTER_CRITICAL(&mux);        /* start critical section */

         strip.show();

         //portENABLE_INTERRUPTS();       // alternative to portEXIT_CRITICAL
         portEXIT_CRITICAL(&mux);         /* end critical section */

         vTaskDelay(15);                  // one tick delay (15ms) in between reads for stability
      }
   }
}

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

   // disabling wifi helps but we need it
   // WiFi.mode(WIFI_OFF);

   // init led strip
   strip.begin();
   strip.setBrightness(4);
   strip.show(); // Initialize all pixels to 'off'

   // create a task that runs on core 0 of esp32
   xTaskCreatePinnedToCore(
       loop2,
       "Task_1",
       1000,
       NULL,
       2, // priority of 0 is the lowest.
       &Task1,
       0 // use core 0. Core 1 is the default core
   );

   // continue running code on default core 1 of esp32

   // Set WiFi to station mode and disconnect from an AP if it was previously connected
   WiFi.mode(WIFI_STA);
   WiFi.disconnect();

   Serial.println("Setup done");
}

// on main loop scan network just to show how led strip does not work great when wifi is in use
// This code I copied and pasted from the WiFi examples of the esp32
void loop()
{
   Serial.println("scan start");

   // WiFi.scanNetworks will return the number of networks found
   int n = WiFi.scanNetworks();
   Serial.println("scan done");
   if (n == 0)
   {
      Serial.println("no networks found");
   }
   else
   {
      Serial.print(n);
      Serial.println(" networks found");
      for (int i = 0; i < n; ++i)
      {
         // Print SSID and RSSI for each network found
         Serial.print(i + 1);
         Serial.print(": ");
         Serial.print(WiFi.SSID(i));
         Serial.print(" (");
         Serial.print(WiFi.RSSI(i));
         Serial.print(")");
         Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
         delay(10);
      }
   }
   Serial.println("");

   // wait 5 seconds for next network scan
   auto end = millis() + (unsigned long)5000;
   while(millis() < end)  {
      vTaskDelay(1);
   }

}

```

When I run this code the first led flickers. The other LEDs animate great 99.99% of the time. When I disable WiFi this code works great. I still need `portENTER_CRITICAL(&mux);` or `portDISABLE_INTERRUPTS();` for it to work even if I disable WiFi. Has anyone managed to be able to animate an led-strip with the ESP-32 successfully meanwhile using WiFi?

If I am required to use a separate micro controller which one do you guys recommend? The ATtiny85?

# Answer
I used the FastLed library and it works now. For some reason the adafruit library only works when I am not using the WiFi. This code works:

```
#include "Arduino.h"
#include <FastLED.h>
#include "WiFi.h"

// we will runt the task that animates led strip on a separate core of arduino
TaskHandle_t Task1;

#define LED_PIN 32
#define NUM_LEDS 108
#define BRIGHTNESS 10
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];

#define UPDATES_PER_SECOND 100

// scan the network every 5 seconds
void loop2(void *parameter)
{
    for (;;)
    {
        Serial.println("scan start");

        // WiFi.scanNetworks will return the number of networks found
        int n = WiFi.scanNetworks();
        Serial.println("scan done");
        if (n == 0)
        {
            Serial.println("no networks found");
        }
        else
        {
            Serial.print(n);
            Serial.println(" networks found");
            for (int i = 0; i < n; ++i)
            {
                // Print SSID and RSSI for each network found
                Serial.print(i + 1);
                Serial.print(": ");
                Serial.print(WiFi.SSID(i));
                Serial.print(" (");
                Serial.print(WiFi.RSSI(i));
                Serial.print(")");
                Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
                delay(10);
            }
        }
        Serial.println("");

        vTaskDelay(5000);
    }
}

void setup()
{

    Serial.begin(115200);

    delay(1000); // power-up safety delay
    FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
    FastLED.setBrightness(BRIGHTNESS);

    // Set WiFi to station mode and disconnect from an AP if it was previously connected
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();

    // create a task that runs on core 0 of esp32
    xTaskCreatePinnedToCore(
        loop2,
        "Task_1",
        1000,
        NULL,
        2, // priority of 0 is the lowest.
        &Task1,
        1 // use core 0. Core 1 is the default core
    );

    Serial.println("Setup done");
}

void loop()
{

    // red
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0xFF0000;
        FastLED.show();
        FastLED.delay(25);
    }

    // green
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0x00FF00;
        FastLED.show();
        FastLED.delay(25);
    }

    // blue
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0x0000FF;
        FastLED.show();
        FastLED.delay(25);
    }

    // rgb red green blue

    //ChangePalettePeriodically();
    //FillLEDsFromPaletteColors( startIndex);
}

```
> 0 votes

---
Tags: c++, interrupt, esp32, led-strip
---


# Question
Title: How to count the number of rising edges on DS3231 rtc?
I am using a DS3231 rtc and I would like to get millisecond accuracy from it so I decided to use the 32kHz generated clock from it. I wrote a code that would count the rising edges or falling edges using an interrupt with (RISING or FALLING parameters) but I get only zeros on my Serial board for the count.

Here is the code I am using :

```
#include <DS3231.h>
#include <RTClib.h>
#include <Wire.h>
#include "rtc.h"
#define InterruptPin 3

volatile long lcnt = 0;

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  Serial.begin(74880); // init serial port
  pinMode(InterruptPin, INPUT_PULLUP);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
  attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
}
void loop() {
  unsigned long a=millis();
  if (a<1000){
  Serial.println(lcnt);
  }
}

void fcnt(){
  lcnt+=1;
}

```

I just want to check how many rising edges I have in 1s. What is strange is that this code used to work and now it doesn't ^^'... I don't know if I changed something by mistake or deleted something useful.

Can somebody help me to resolve this little problem ?

Thanks a lot for your time !

# Answer
I'm not sure why you're getting 0 as such, but your interrupt and variable methodology leaves a lot to be desired (probably the cause of the "tutorials" you followed).

My primary concern is that you are using a 32-bit "long" variable in an interrupt, and referencing that directly outside the interrupt. The Arduino is an 8-bit system, which means that all accesses to that variable take many instructions to arrange (splitting it down into 4 8-bit values, manipulating it, recombining it, etc). Because of this no operations on that variable are "atomic".

You need to make them atomic. If you don't then it's perfectly possible for the interrupt to trigger and modify the value in the middle of you doing something with that value.

The simplest way of making it atomic is to disable interrupts, then copy the value to another variable and/or modify it, and enable interrupts again.

Here's an example that I would consider stable:

```
#include <DS3231.h>
#include <RTClib.h>
#include <Wire.h>
#include "rtc.h"
#define InterruptPin 3

volatile uint32_t lcnt = 0;

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  Serial.begin(74880); // init serial port
  pinMode(InterruptPin, INPUT_PULLUP);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
  attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
}

void loop() {
  static uint32_t ts = millis();
  uint32_t a = millis();
  if (a - ts >= 1000) {
    ts = a;
    noInterrupts();
    uint32_t currentCount = icnt;
    icnt = 0;
    interrupts();
    Serial.println(currentCount);
  }
}

void fcnt(){
  lcnt+=1;
}

```

That should print the number of pulses over successive 1 second periods.
> 1 votes

# Answer
I used the same code as yours and simply changed the datatype from uint32\_t to unsigned long and it started working. May be you can try the same.
> 0 votes

---
Tags: arduino-mega, rtc, atmega2560, oscillator-clock, ds3231-alarms
---


# Question
Title: Linux can not open arduino IDE - java.lang.NullPointerException
I use arch linux. I installed arduino ide with pacman. When I try to run it, loading window will show for few socends and than program crashes. There are logs:

```
john@arch-thinkpad ~ [1]> arduino
Picked up JAVA_TOOL_OPTIONS:
Set log4j store directory /home/john/.arduino15
java.lang.NullPointerException
    at processing.app.Base.rebuildProgrammerMenu(Base.java:1705)
    at processing.app.Base.<init>(Base.java:286)
    at processing.app.Base.main(Base.java:150)
john@arch-thinkpad ~ [255]>

```

```
john@arch-thinkpad ~> arduino --version
Picked up JAVA_TOOL_OPTIONS:
Loading configuration...
Initializing packages...
Preparing boards...
Arduino: 1.8.13

```

What should I do to fix it ?
Thank you for your help

# Answer
I had to install `arduino-avr-core` package:

```
sudo pacman -S arduino-avr-core

```

Now it works fine
> 12 votes

# Answer
The first thing to do is delete your `preferences.txt` file. This is the most common cause of startup issues - some corruption or an invalid setting in that file can break the IDE completely.

```
rm ~/.arduino15/preferences.txt

```

If that doesn't fix it then you can delete your entire Arduino working directory, which will remove all installed cores and boards and give you a fresh installation:

```
rm -rf ~/.arduino15

```
> 0 votes

---
Tags: arduino-ide, java
---


# Question
Title: What is the maximum size of Static Json Document in Arduino JSON?
I'm trying to do serial communication between Arduino mega and a esp8266, and having issues with determining the size of the JSON document. I have read that the receiver buffer size should be greater than the sender buffer, but what's the maximum buffer size we can use for the JSON document?

# Answer
> 2 votes
The Arduino Mega has 8 KB of RAM, all of which you could use in a StaticJsonDocument.

The ESP8266 has 80 KB of RAM, but the core limits the stack to 4 KB. If you need something bigger, switch to a DynamicJsonDocument.

In both cases, you need to leave a lot of room for other variables and libraries. As an example, I wouldn't create a StaticJsonDocument bigger than 6 KB on the Mega, and 2 KB on the ESP8266.

By the way, I heard this library is very well documented, did you have a look?
Do you know you can use the ArduinoJson Assistant to help you decide the capacity of the JsonDocument?

---
Tags: serial, esp8266, arduino-mega, json, buffer
---


# Question
Title: what library should I #include when using switch-case statement
I receive an error code of: `'switch' was not declared in this scope`

The code is correct so I assume that the necessary library was not included.

Please tell me the correct `#include` to use.

```
swith(pwm){
  case 0:   Serial.print(pwm); Serial.print("   ");_delay_ms(2000);
            break;
  case 31:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 63:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 95:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 127:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 159:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 191:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 124:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 156:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 188:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 220:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 252:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  default:  break;
}

```

# Answer
It seems you have a syntax error: write `switch` instead of `swith`.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: how to convert the following code into one using direct port manipulation
Following is the program for scanning a keyboard for MIDI transfer. At present the code works fine, but it could be faster. I need to know how to use direct port manipulation inside the for loop.

```
boolean keypressed[6][6]; //for storing key states
int midinote[6][6] ={ 60 ,61 ,62 ,63 ,64 ,65
                 ,66 ,67 ,68 ,69 ,70 ,71
                 ,72 ,73 ,74 ,75 ,76 ,77
                 ,78 ,79 ,80 ,81 ,82 ,83
                 ,84 ,85 ,86 ,87 ,88 ,89
                 ,90 ,91 ,92 ,93 ,94 ,95  }; //code for various midi notes C3 to C6

void setup() {

   Serial.begin(38400);
   for(int i=0; i<6; i++){
      pinMode(i+2,OUTPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i<6; i++){
      pinMode(i+8,INPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i<6; i++){
      for(int j=0; j<6; j++){
          keypressed[i][j] = false;
          }
      }
   }
void loop() {

   for(int i=0; i<6; i++){
      digitalWrite(i+2, LOW);
      for(int j =0; j<6; j++){
         if ((digitalRead(j+8) == LOW) && !keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(127);
            keypressed[i][j] = true;
           }
         if ((digitalRead(j+8) == HIGH) && keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(0);
            keypressed[i][j] =false;
         }
      }
digitalWrite(i+2, HIGH);
   }

 }

```

# Answer
> 2 votes
It is better to use interrupts instead of pooling pins. but this is related to your arduino controller. what is you arduino core controller? if you can select I prefer "Nano 33 IoT " which has 9 pins (2, 3, 9, 10, 11, 13, 15, A5, A7) available for interrupt. this page may be usable: https://playground.arduino.cc/Main/PinChangeInterrupt/

---
Tags: arduino-uno, midi, port-mapping
---


# Question
Title: Whats the best way to keep an Arduino in a waterproof junction box and prevent overheating?
I am trying to make an automatic garden gate unlock that runs on a timer. I plan on running an arduino uno 24/7 with a software timer that activates a motor to release a bolt lock. I am going to fit all the electronics and extension cord into a waterproof junction box. Will this cause over heating? Is there a need for some kind of waterproof cooling system? Has anyone ever built outdoor electronics and ran into this problem?

# Answer
> 0 votes
The linear regulator on an Arduino works by converting excess voltage to heat. If you power it with 12V and draw a full amp from it it will turn (12-5)\*1a or 7 watts of power to heat, and quickly overheat even if it's not in a box.

If you power it from 6.5V and only draw 300mA from it, it will turn (6.5-5)\*.3, or a little under half-a-watt. While the Arduino is idling it will probably only draw 50mA, so less than 1/10th of a watt of heat.

For infrequent, short bursts of a few seconds you can probably get away with drawing 500mA of power without overheating.

Or skip the internal regulator and use a buck style voltage regulator. Those generate a LOT less heat.

## Edit:

For a project I did recently, I used an external 5V regulated supply for everything. I cut a USB cable and soldered the red and black (+5V and ground) to the 5V supply, and plugged that into the Arudino's USB connector. That feeds 5V into the Arduino.

# Answer
> 0 votes
The simplest selection is Aluminum water proof box.

You can make it yourself, using aluminum U profiles, and mount arduino heat generator parts on the internal surface of the box.

---
Tags: arduino-uno, project, heat
---


# Question
Title: Sending and receiving different types of data via I2C in Arduino
I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.

In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.

here is the code for the master

```
#include <Wire.h>

const int SLAVE_ADDRESS = 8; //Slave arduino ID
int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
void setup ()
{
Wire.begin ();
Serial.begin (9600);  // start serial for output
}  // end of setup
void loop()
{
Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

for(int i=0;i<3;i++)//organizes the data from the slave in the table
{
int c = Wire.read(); // receive a byte as character
table[i]=c;
}
//displays the data
 Serial.print('\n');
   Serial.print(table[0]);
    Serial.print('\t');
   Serial.print(table[1]);
    Serial.print('\t');
   Serial.print(table[2]);
   Serial.print('\n');

delay (500);

// transmit just this variable to the slave
int Work=1;
Wire.beginTransmission (8);
Wire.write (Work);
Wire.endTransmission ();
}

```

here is the code for the slave

```
#include <Wire.h>
int table[]={0,0,0};
int Work=0;

void setup() {
Wire.begin(8);                // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent); // register event
}

void loop() {
int x=120;
int y=1200;// gets converted to an strange # because is larger than 255
int z=3;
  table[0]=x;
  table[1]=y;
  table[2]=z;
}

void requestEvent()
{
  uint8_t Buffer[3];
  Buffer[0]=table[0];
  Buffer[1]=table[1];
  Buffer[2]=table[2];
  Wire.write(Buffer,3);
}

void receiveEvent(int howMany)
{Work = Wire.read();}

```

# Answer
> 3 votes
I2C is truly a powerful option of Arduino, for too many reasons; yet the amount of tutorials available are not that many and unfortunately are too complicated for the average person.

After working on this for 2 days, I think I have a way to transfer pretty much anything between master and slaves and viceversa. Note that I2C does not transfer floats or even integers larger than 255, there are several ways to go about this and here is a good tutorial http://www.gammon.com.au/i2c and even a library: http://forum.arduino.cc/index.php?topic=171682.0

The solution I found was simpler. Basically we convert any value, string, number, text, float, you name it, and turn into a variable char, which can be transferred via I2C. Once transferred, you can convert back to a number although in my case below, I just wanted to display the data from the slave.

Here is the code. I provide comments on different parts for clarity. I hope this helps. it worked for me.

```
//master
#include <Wire.h>

char t[10]={};//empty array where to put the numbers comming from the slave
volatile int Val; // varaible used by the master to sent data to the slave

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 3);    // request 3 bytes from slave device #8

//gathers data comming from slave
int i=0; //counter for each bite as it arrives
  while (Wire.available()) {
    t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
    i=i+1;
  }

Serial.println(t);   //shows the data in the array t
delay(500); //give some time to relax

// send data to slave. here I am just sending the number 2
  Val=2;
  Wire.beginTransmission (8);
  Wire.write (Val);
  Wire.endTransmission ();
}

```

here the other part //slave

```
#include <Wire.h>

char t[10]; //empty array where to put the numbers going to the master
volatile int Val; // variable used by the master to sent data to the slave

void setup() {
  Wire.begin(8);                // Slave id #8
  Wire.onRequest(requestEvent); // fucntion to run when asking for data
  Wire.onReceive(receiveEvent); // what to do when receiving data
  Serial.begin(9600);  // serial for displaying data on your screen
}

void loop() {
  int aRead = analogRead(A0); //plug a potentiometer or a resistor to pin A0, so you can see data being transfer
  float x = aRead/1024.0*5.0; //generate a float number, with this method you can use any time of data pretty much

  dtostrf(x, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  Serial.println(Val);         // print the character
 delay(500);
}

// function: what to do when asked for data
void requestEvent() {
Wire.write(t);
}

// what to do when receiving data from master
void receiveEvent(int howMany)
{Val = Wire.read();}

```

# Answer
> 0 votes
I believe that for your scenario, i.e. sending different types of variables, the EasyTransfer library (by Bill Porter) would be an elegant solution. The library can be found here: https://github.com/madsci1016/Arduino-EasyTransfer. There are implementations for serial, I2C, and VirtualWire and the examples provided are pretty self-explanatory.

The handling is very easy. After including the library, you create an EasyTransfer object, define a data structure that basically represents a "container" of your data and this can consist of different variables.

```
struct RECEIVE_DATA_STRUCTURE{
  //put your variable definitions here for the data you want to receive
  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
  int blinks;
  int pause;
};

```

Once the "container" is filled, i.e. the variables are set on the sender side, they are sent with a simple command

```
  ET.sendData(I2C_SLAVE_ADDRESS);

```

On the receiver side, you define an identiacl data structureand receive the data by

```
ET.receiveData();

```

Hope this helps.

# Answer
> 0 votes
Use the 'I2C\_Anything' library, available here. I use it in all my I2C projects. It is extremely simple and works great. Here's the entire .h file

```
// Written by Nick Gammon
// May 2012

#include <Arduino.h>
#include <Wire.h>

template <typename T> unsigned int I2C_writeAnything (const T& value)
  {
  Wire.write((byte *) &value, sizeof (value));
  return sizeof (value);
  }  // end of I2C_writeAnything

template <typename T> unsigned int I2C_readAnything(T& value)
  {
    byte * p = (byte*) &value;
    unsigned int i;
    for (i = 0; i < sizeof value; i++)
          *p++ = Wire.read();
    return i;
  }  // end of I2C_readAnything

```

---
Tags: arduino-uno, i2c, wire-library, float
---


title: Arduino CH340 Driver Problem

text:
# Question
Title: Arduino CH340 Driver Problem
I'm trying to connect my Arduino Uno to the Arduino IDE in Windows, but the only way it works is with a CH340 driver.

I am concerned about this as I can only find a download of it published by two Chinese companies- wch.cn or Jiangsu Qinheng Co., Ltd.- maybe they're both 1 company; even when Windows looked for a driver on the web that was the one it downloaded.

When I went to Device Manager to look for the driver in the official Arduino download zip, Windows said it couldn't find any drivers.

I am concerned about the security implications of the driver being Chinese and wonder if there are any other CH340 drivers (unless CH stands for China...)

Anyway thx for answering!!! :)

# Answer
> 1 votes
WCH is the manufacturing company that first produced the CH340. They are Chinese.

---
Tags: arduino-uno, ide, windows
---


title: How do I know the sampling frequency?

text:
# Question
Title: How do I know the sampling frequency?
I am beginning to get a bit confused about sampling rates and baudrates etc. I have this Arduino code:

```
#include <eHealth.h>

extern volatile unsigned long timer0_overflow_count;
float fanalog0;
int analog0;
unsigned long time;

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

void loop() {
  while (Serial.available()>0){
    serialByte=Serial.read();
    if (serialByte=='S'){
      while(1){
        fanalog0=eHealth.getECG();
        // Use the timer0 => 1 tick every 4 us
        time=(timer0_overflow_count << 8) + TCNT0;
        // Microseconds conversion.
        time=(time*4);
        //Print in a file for simulation
        //Serial.print(time);
        //Serial.print(" ");
        Serial.print(fanalog0,5);
        Serial.print("\n");

        if (Serial.available()>0){
          serialByte=Serial.read();
          if (serialByte=='F')  break;
        }
      }
    }
  }
}

```

Since there is no delay interrupt, what is the sampling rate/frequency? Is it based on the Arduino ADC speed? When I increase the baudrate am I increasing the sampling frequency or just the rate at which I send data over the serial port?

# Answer
> 24 votes
The Arduino ADC clock speed is set in ..arduino-1.5.5\hardware\arduino\avr\cores\arduino\wiring.c

Here is the relevant part

```
#if defined(ADCSRA)
    // Set A/D prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
    sbi(ADCSRA, ADPS1);
    sbi(ADCSRA, ADPS0);

    // Enable A/D conversions
    sbi(ADCSRA, ADEN);
#endif

```

For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz.

That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.
Since you read the result and send it through the serial port, you are getting a delay that increases as the baud rate decreases. The lower the baud rate the longer it will take to send the same length of data and the longer it will take to call the next ADC conversion.

The actual sampling rate in your application can be determined with the use of a debugger or a simulator, but an easier solution is to toggle a digital pin every time you execute a conversion and measure the frequency that the digital pin toggles at.

# Answer
> 9 votes
I also wanted to get a high sampling rate, for a project. turns out that the ADPS2,ADPS1,ADPS0 bits of the ADCSRA register can be configured to get a sampling rate of 76923 s/s or 76.8 ks/s. But, beware that I am running my arduino's ADC in free running mode, the following lines worked for me.

```
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

void setup() {
// Set the Prescaler to 16 (16000KHz/16 = 1MHz)
// WARNING: Above 200KHz 10-bit results are not reliable.
//ADCSRA |= B00000100;
sbi(ADCSRA, ADPS2);
cbi(ADCSRA, ADPS1);
cbi(ADCSRA, ADPS0);

// Set ADIE in ADCSRA (0x7A) to enable the ADC interrupt.
// Without this, the internal interrupt will not trigger.
//ADCSRA |= B00001000;
sbi(ADCSRA,ADIE)
}

```

At this frequency the usual 10-bit results are not reliable. It means that increasing the sample rate will decrease the precision of the results. So I only use the upper 8 bits because at this prescalar the upper 8-bits are reliable. You can go into more detail on this page, this dude rocks! he made a high sample rate oscilloscpe using UNO http://www.instructables.com/id/Girino-Fast-Arduino-Oscilloscope/

# Answer
> 4 votes
Sending 11 bits over serial at a baud of 9600, but for the sampling, I store it in an array with as little delay as possible, then once it's done, I send it through the serial port to be read by a python script. I'm doing this for an FFT using matplotlib. I listen to a 0-5V signal, then without using the delay() function, I store the analogRead() values into that array. In a split second the reading is done, then the serial data dump starts. When I calibrated the input frequency using tone() from another connected Arduino, I realized that I had to divide the index by 8915 in order to get accuracy to within .1 Hz. Because one would have to divide by the frequency of the sampling to get the proper index intervals, my guess is the Arduino sampling frequency (at least mine with my code) is 8915Hz.

# Answer
> 3 votes
Each loop you are printing 8 characters over a 9600bps serial link. Each character takes 10 bits (1 start, 8 bits for the character, 1 stop). That means you can only go through this loop ~120 times/sec.

The `analogRead()` function can sample at about 9600 times/sec in theory, realistically it is about 8600 times/sec.

You are being bounded by the serial communication.

# Answer
> 1 votes
Referring to the part about the difference between sample rate and baud rate, they are different measurements.

Sample Rate is the frequency at which the device (arduino) can recreate a digital representation of incoming analog values.

Baud Rate is the rate at which information is transferred in a communication channel. It describes the rate of communication between the microcontroller and the outside world (the computer).

I would recommend this electronics\_stack\_exchange link. https://electronics.stackexchange.com/questions/135056/sampling-rate-data-rate-and-bandwidth

# Answer
> 0 votes
8915Hz - it is very close to 125000/14 ~= 8928.6 My initial guess that exactly one gap is required between adjacent conversions One ADC clock for sampling and 13 ADC clocks for conversion itself. Small error could be effect of not perfect clock source of Arduino. I am not sure yet. This topic is actual for me now as sampled data must feed digital filter.

# Answer
> 0 votes
Have you considered getting A Saleae or similar logic analyzer. The simple inexpensive ones work great and allow you to make these measurements quite easily. This works better then a scope in most of my applications. If there is signal overlap it will show. I simply devote one pin for testing and call it testpin. Just set it high when starting the routine and then low when finished. It has 8 inputs so you can see the relationship between signals. You could monitor the A/D, starting the trigger and place the serial on another pin. You still have 6 left for other things. Spend a few hours with it and it will become one of your most important tools. I use Linux Mint so I just keep it on another screen so a simple click brings it in view and it will run whether the window is in view or not. Be careful if you have unused inputs they will act as antenna and pick up stray signals especially from switching power supplies. Just select the channels you want or ignore the ones that are not relevant. The built in analyzers make short work of serial signals.

---
Tags: arduino-uno, serial
---


# Question
Title: Accessing struct's variable parametrically on ESP8266
I have 2 instances of a struct. One has def values stored and second stores values read from a file on `SPIFFS`.

I'm trying to use a for loop over all struct's variables - if file was read OK and key was found, store its value in `final_par` else get value from `def_par`.

For that, I've created `keys` array - but I can't find a way to iterate, in a for loop

as `final_par.keys[i] = def_par.keys[i]` \- but this is not possible.

How can it be done ?

```
struct parameters
{
  bool ext_inputs;
  bool auto_relay_off;
  bool useSerial;
  bool useWDT;
  bool useOTA;
  bool useResetKeeper;
  bool useFailNTP;
  bool useDebugLog;
  char deviceTopic[20];
  char groupTopic[20];
  char prefixTopic[20];
  int inputUpPin;
  int inputDownPin;
  int outputUpPin;
  int outputDownPin;
  int inputUpExtPin;
  int inputDownExtPin;
  int auto_relay_off_timeout;
};
char *keys[] = {"ext_inputs", "auto_relay_off", "useSerial", "useWDT", "useOTA", "useResetKeeper",
                "useFailNTP", "useDebugLog", "deviceTopic", "groupTopic", "prefixTopic", "inputUpPin",
                "inputDownPin", "outputUpPin", "outputDownPin", "inputUpExtPin", "inputDownExtPin",
                "auto_relay_off_timeout"};

parameters def_par{false, false, false, true, true, false, true, "devTopic", "noGroup", "myHome", 2, 1, 14, 12, 0, 2, 60};

parameters final_par;

```

# Answer
> 1 votes
You can create a 'hardcoded' copy function:

```
void CopyParameter(int parameterIndex)
{
    switch (parameterIndex)
    {
    case 0: final_par.ext_inputs = def_par.ext_inputs; break;
    case 1: final_par.auto_relay_off = def_par.auto_relay_off; break;
    ...
    default: // Error
    }
}

```

Of course you can also pass `final_par` and/or `def_par` as arguments.

If you don't want to use an index, create an `enum` with the index values for each parameter, like:

```
enum EParameters
{
    ExtInputs,
    AutoRelayOff
    ...
};

void CopyParameter(EParameter parameter)
{
    switch (parameter)
    {
    case ExtInputs   : final_par.ext_inputs     = def_par.ext_inputs    ; break;
    case AutoRelayOff: final_par.auto_relay_off = def_par.auto_relay_off; break;
    ...
    default: // Error
    }
}

```

The disadvantage is that you have to keep the structure and the copy function manually synchronized.

The advantage is that you can do a shallow, deep copy or even add more logic depending on each struct member.

# Answer
> 1 votes
You can do it but it can be awkward. You'll need an array of structs, each member of which describes one member of your 'struct parameters' - essentially, an expansion of your present 'keys\[\]'.

Then you can consult this array randomly or in order to find the name, data-type, and memory offset of a given parameter (indexed by parameter order), or search it, to access the same information by parameter name.

Here's your parameter struct with some (incomplete but runnable) code to list the descriptor array, and incidentally, show how to build and use the array. Note that the code compiles but with a warning that a member of your 'parameters' was not initialized. I chose not to fix that; it isn't used here and doesn't prevent compilation.

```
struct parameters
{
  bool ext_inputs;
  bool auto_relay_off;
  bool useSerial;
  bool useWDT;
  bool useOTA;
  bool useResetKeeper;
  bool useFailNTP;
  bool useDebugLog;
  char deviceTopic[20];
  char groupTopic[20];
  char prefixTopic[20];
  int inputUpPin;
  int inputDownPin;
  int outputUpPin;
  int outputDownPin;
  int inputUpExtPin;
  int inputDownExtPin;
  int auto_relay_off_timeout;
};
//char *keys[] = {"ext_inputs", "auto_relay_off", "useSerial", "useWDT", "useOTA", "useResetKeeper",
//                "useFailNTP", "useDebugLog", "deviceTopic", "groupTopic", "prefixTopic", "inputUpPin",
//                "inputDownPin", "outputUpPin", "outputDownPin", "inputUpExtPin", "inputDownExtPin",
//                "auto_relay_off_timeout"};

parameters def_par{false, false, false, true, true, false, true, "devTopic", "noGroup", "myHome", 2, 1, 14, 12, 0, 2, 60};

parameters final_par;

// A couple of functions to extract data from an array or struct:
#define countof(a) (sizeof(a)/sizeof(a[0]))                             // ret # of array elements (not bytes)
#define offsetof(struc, member) ((int)(&(((struc*)(0))->member)))   // ret byte-offset from start of struct to the given member

// Enumerate possible parameter types
typedef enum {
   t_bool,
   t_char,
   t_int
} parType;

// Descriptor table - contains name, type, and offset of each parameter
// Could go in flash to save a bunch of RAM
struct descriptor {
   const char *name;
   parType pType;
   uint8_t offset;
} Descriptors[] = {
   { "ext_inputs", t_bool, offsetof(parameters, ext_inputs) },
   { "auto_relay_off", t_bool, offsetof(parameters, auto_relay_off) },
   // ...
   { "inputUpPin", t_int, offsetof(parameters, inputUpPin) },
   // ...
   { "auto_relay_off_timeout", t_int, offsetof(parameters, auto_relay_off_timeout) }
};

void setup() {
    Serial.begin(115200);
    Serial.println("parameter        type          offset\n");
    // List the parameters' names, types, and offsets within 'struct parameters'
    for( uint8_t i = 0;  i < countof(Descriptors);  ++i ){
        Serial.print(Descriptors[i].name);    Serial.print(", ");
        Serial.print(Descriptors[i].pType);   Serial.print(", ");
        Serial.println(Descriptors[i].offset);
    }
}

void loop(){
    ;
}

```

---
Tags: struct
---


# Question
Title: How do I connect 4 or more Arduinos to a single shared GSM Module?
Is it possible to connect 4 or more Arduinos to a single GSM Module.? All the Arduinos need to send SMS at a specific time daily. How do I make sure thet don't time collide with each other, other than sending sms at different times for each Arduino?. I want the SMS to be queued up, and be sent one by one.

# Answer
You should consider connecting one Arduino to the GSM module, and connect the 4 Arduinos together using SPI, I2C, or any other inter-hardware comms protocol. Before I knew these options existed, I once wrote a bit of code to send data between Arduinos by having one pin represent the data being sent and another pin changing every time a new bit was available. You could do something similar with an extra line per pairing, so an Arduino could tell the primary that it had new data to send.

Anyway, check out the "Wire Library" - it's basically for this kind of work. I think you'll be happier trying to have one Arduino "in charge" and connected to the CSM while the rest vie for its attention.
> 3 votes

---
Tags: arduino-uno, gsm
---


# Question
Title: Longruner Nano ATMega 328P input stays HIGH for 1s longer than the reality
I have a Longruner Nano ATMega 328P (copy of arduino nano, main difference being the USB connector, CH340 instead of the usual FT232, from what I could find using google searches).

I wrote a super basic code to test its signal detection capabilities:

```
setup(){
  pinMode(13, OUTPUT);
  pinMode(2, INPUT);
}

loop(){
  digitalWrite(13, digitalRead(2));
}

```

Hard to make it simpler to test a simple thing: when I give a HIGH signal to D2, D13 is HIGH too.

To test it, I used a simple male-male jump cable and connected VIN pin to the D2 one, for a very brief moment. And I notice D13 stays HIGH for around a second (measured with serial, lowest I could get was 996ms after super quickly touching D2 with the jump cable).

I tried to change the pinMode to INPUT\_PULLUP following a similar question I found, but it didn't change anything regarding this delay.

Am I doing something wrong? Maybe a wrong configuration? Or is this just a hardware issue due to the fact that I'm using a copy and there's more than just the USb connector that changes?

I can adapt and work with this if it's required, but being able to have an accurate signal detection would help me greatly.

# Answer
> 3 votes
Don't use Vin as a logic source. Use the +5V pin.

Also, disconnecting the pin is not the same as grounding it. It is "floating". For a proper test, connect a +5V to the pin, and follow it with a Gnd.

A floating pin has an undefined logic level.

What would work in your case is to have a (say) 1k resistor between D2 and Gnd. That way, the moment you disconnect the voltage input the "pull-down" resistor will return it to 0V.

---
Tags: arduino-nano, input
---


# Question
Title: Having difficulty uploading sketch to an Arduino Pro Mini
Having developed and tested a project using an Arduino Uno, I would now like to upload it to an Arduino Pro Mini (5V, 328, 16MHz) for semi-permanent, long-term use, but I can't get any sign of life from the Pro Mini.

I'm using the latest Arduino IDE (v1.6.0 with Java 6, on Mac OS X Mavericks), and I've got a USB 2.0 to TTL UART 6PIN CP2102 Module Serial Converter to connect the Pro Mini to the Mac, and I've selected Tools —\> Board —\> Arduino Pro or Pro Mini (5V, 16MHz) w/ ATmega328.

The problem is that I don't see a suitable serial port in the list. When I plug in the Arduino Uno, "/dev/tty.usbmodem1421" immediately pops up in the Tools —\> Serial Port menu, but I don't see anything similar with the Mini Pro.

The problem is probably in the connection between the USB/TTL converter and the Mini Pro, so my question is: which pins should connect to which?

FWIW the USB/TTL converter was supplied with a 5-core (not 6-core) cable to connect its 6 pins.

So do I connect Tx—\>Tx and Rx-\>Rx, or should they be crossed over? It's fairly clear that "5V" connects to "Vcc" and "GND" goes to "GND", but what about CTS and DTR?

Also FWIW, I have googled this, and I have read a number of other posts and answers on StackExchange, but the fact that I'm here writing my question means that I'm still stuck. Any and all constructive suggestions will be appreciated. Thanks!

# Answer
> 5 votes
You need to hook it up with the Arduino TX --\> FTDI RX, and vise versa, so crossed over. If you take the FTDI and hook it up to the Ardiono pin to pin as you have it pictured it should work, provided the FTDI works.

No to your note about not having a serial port, you should have that as soon as you plug the FTDI into your computer, the Arduino is not necessary for this. First things first, check you drivers, and check your USB connection. You won't get anywhere until that Serial port is recognized on your computer.

# Answer
> 0 votes
If you still have any issues, try connecting the vcc and gnd to raw and gnd near the pins. Mine worked this way

---
Tags: pins, uploading, arduino-pro-mini
---


# Question
Title: Why do NRF24L01 modules only communicate in 1 direction
I have 2 NRF24L01 +pa +lna modules connected to 2 arduino mini pros. One of the modules is on a joystick and the other one is on a airplane. Everything worked perfectly until last week when they stopped communicating. So I wrote a simple receiver and transceiver code to see if they worked. The result is that if the module on the plane is the transceiver and the joystick is the receiver everything works fine. If they have the opposite roles then I only get empty messages onto the serial monitor way more often than the transceiver sends a message.

Receiver code:

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

RF24 radio(7, 8);

const byte address[6] = "00001";

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

  radio.begin();
  radio.openReadingPipe(0, address);
  radio.startListening();

}

void loop() {
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }

}

```

Transceiver code:

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

RF24 radio(7,8);

const byte address[6] = "00001";

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.stopListening();

}

void loop() {

  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay (1000);
  // put your main code here, to run repeatedly:

}

```

# Answer
> 1 votes
In receiving code....try only defining variable. char text\[32\];

You change the datarate , palevel and channel in nrf24l01. See datasheet for more info. Or visit https://howtomechatronics.com/tutorials/arduino/arduino-wireless-communication-nrf24l01-tutorial/

You may have power issue because pro mini might not deliver sufficient....to neglect use a 10uf Cap in nrf.

---
Tags: communication, arduino-pro-mini, nrf24l01+
---


# Question
Title: Heart Pulse sensor analog value doesn't change even if sensor pressed by finger
I have recently bought a Heart Pulse Sensor. Then, to check whether the sensor is working correctly or not, I uploaded this below code:

```
void setup() {

 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);

 Serial.println(sensorValue);
 delay(1);        // delay in between reads for stability
}

```

I know, that this code doesn't calculate the actual BPM. It sends 380-400 sensor value through the Serial monitor, while the sensor is not being pressed by my finger. But when I press it with my finger, the sensor value doesn't even come out of the range 380-400. But the sensor value was supposed to jump over 500 when a beat happened.

I think, that probably means my sensor is unable to detect beats. And now, my question is, why my sensor is unable to detect beats?

After looking at some forums, I learned that this sensor can be a clone. After looking at my sensor carefully, I found some little differences in my sensor than the sensors other people used in their tutorials. And, the most spottable differences were: \*the colors of my sensor's pre-soldered jumper wires were different than other sensors. \*"pulsesensor.com" was written in the other sensors, but it wasn't written on my sensor

There were also some other differences. I have given three pictures of my pulse sensor below.

My final questions:-

1. Why my pulse sensor is unable to detect beats?
2. Is my pulse sensor a clone or not?
3. If it is a clone, can it be fixed somehow?
4. Do I need to buy another one?

That's all I know. Can anyone help me! Any help appreciated.

Thanks a lot!

# Answer
Why my pulse sensor is unable to detect beats?

Chances are something wrong. The only way to tell what specifically is to keep debugging. If you don't have access to an Oscilloscope or Multimeter, this will involve checking your wiring and altering code. To check wiring, make sure:

1. Minus (-) is to ground
2. Plus (+) s to your + voltage
3. S is to the A0.

Is my pulse sensor a clone or not?

It is likely. Open-Source Hardware tends to have many clones.

If it is a clone, can it be fixed somehow?

Clones sell repeatedly if they work. There is little point making a clone sensor that does not- if scamming was the point, one could ship empty envelopes. If two different people make the exact same electronics, we hope that they behave very similarly regardless of who made them.

Do I need to buy another one?

Possible but unlikely. If you can prove your sensor is defective, a seller might be willing to ship a replacement.

Try the following code to test the sensor. My guess is that you are missing something due to Serial spamming. Beyond that, taking a pulse may be tricky - the unskilled can easily pronounce some of the living as dead from just the wrist. I suggest putting it to your throat to be on the safe side.

```

int minSV;
int maxSV;
unsigned int Frame;

void setup() {
 minSV=500;
 maxSV=0;
 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);
 if(sensorValue > maxSV) maxSV = sensorValue;
 if(sensorValue < minSV) minSV= sensorValue;
 Frame = Frame +1;
 if(Frame > 10000) //would be 1s if frame takes 0.1 ms
 {
  //might want to reset min and max here after debug is complete and sensor is verified to work.  Until then, reset the arduino to reset min and max.
  Frame =0;
  Serial.print("Min: ");
  Serial.print(minSV);
  Serial.print("; Max: ");
  Serial.println(maxSV);
 }
 // removed: delay(1);        // delay in between reads for stability
}

```
> 1 votes

---
Tags: sensors
---


# Question
Title: Sending data struct with 2 int fields from Arduino to Raspberry via NRF24L01
I'm trying to do wireless thermometer on max31865 arduino and nrf24l01 but I'm having problem sending whole data struct I can send int or char arrays but when I try to send whole struct I got output as

```
id: 131073 temperature: 0

```

Is there error in my code or there is some issue with differences in how arduino and raspberry store data? I don't really have experience in this so my question is how do I send struct that contain two fields of int or there is some better way? I need to transmit id and temperature in one package.

Transmitter code(Arduino)

```
#include <SPI.h>
#include "RF24.h"
#include <Adafruit_MAX31865.h>

#define RREF      430.0
#define RNOMINAL  100.0

typedef struct{
  int id = 100;
  int temperature = 100;
}
temp;

temp data;

bool radioNumber = 0;
int i =0;
Adafruit_MAX31865 thermo = Adafruit_MAX31865(10, 11, 12, 13);
RF24 radio(7,8);

byte addresses[][6] = {"1Node","2Node"};
bool role = 0;

void setup() {
  Serial.begin(115200);
  thermo.begin(MAX31865_3WIRE);
  radio.begin();
  radio.setChannel(125);
  radio.setPALevel(RF24_PA_MIN);
  radio.powerUp();
  radio.setDataRate(RF24_1MBPS);
  if(radioNumber){
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1,addresses[0]);
  }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
  }
  radio.stopListening();
}

void loop() {
      data.id = 1;
      data.temperature = 2;
    //int temp = 2; //thermo.temperature(RNOMINAL, RREF);
    Serial.println(temp);
    if (!radio.write( &data, sizeof(data) )){
        Serial.println(F("failed"));
     }
     delay(1000);
}

```

Receiver code(Raspberry pi b3+)

```
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

typedef struct{
        int id = 99;   // debug value
        int temperature = 99;
}
temp;

RF24 radio(22,0);
temp data;

bool radioNumber = 1;
const uint8_t pipes[][6] = {"1Node", "2Node"};

int main(int argc, char** argv)
{
    radio.begin();
    radio.setChannel(125);
    radio.setPALevel(RF24_PA_MIN);
    radio.setDataRate(RF24_1MBPS);
    radio.setRetries(15, 15);
    radio.printDetails();
    if (!radioNumber) {
        radio.openWritingPipe(pipes[0]);
        radio.openReadingPipe(1, pipes[1]);
    } else {
        radio.openWritingPipe(pipes[1]);
        radio.openReadingPipe(1, pipes[0]);
    }

    radio.startListening();

    while (1) {
            if (radio.available()) {
                int tem = 0;
                while (radio.available()) {
                    radio.read(&data, sizeof(data));
                }
                cout << tem  << "  " << "id: "<< data.id<< " temperatura: " << data.temperature << endl;
                delay(925);

            }
        }
    return 0;
}

```

EDIT: Ok after running sizeof(data) on both devices, I notice that structs have different size 4 bytes for arduino and 8 for raspberry. So change on raspberry side to

```
typedef struct{
  uint16_t id = 100;
  uintt16_t temperature = 100;
}
temp;

```

And this is working but, may I ask why int have various size on arduino and raspberry?

# Answer
> 4 votes
Your problem is that you are communicating between an 8-bit and a 32-bit architecture.

On an 8-bit architecture `int` is 16 bits. On a 32-bit it's 32 bits. Why the difference? Because "it is". It's how it's always been since the dawn of C. The concept of `int` is a flexible idea with no fixed defined size - the size is largely defined by the architecture and the compiler. Although conventions now dictate that an `int` will be 16 bits on an 8-bit system and 32-bits on a 32-bit system.

You can think of it as the integer size being the same as the internal register width of the processor *but with a lower bound of 16 bits*.

This is precisely why the fixed width integer types `uint16_t` etc exist - so that you can enforce the same data size on different architectures.

Incidentally you should also be aware of the *endianness* of your systems. In your case they are both "little endian", but "big" (and even "middle") endian systems also exist. This defines what order each byte of an integer (and other multi-byte data types) is stored in memory. If you send an integer from a little-endian to a big-endian system and don't apply any transformation to the data to reverse the bytes then the values will be completely wrong.

---
Tags: arduino-mega, programming, communication, nrf24l01+, raspberrypi
---


title: WebSocket Server for MKR1000

text:
# Question
Title: WebSocket Server for MKR1000
I was looking for a websocket server for my MKR1000 but nothing I found works.

I tried all the libraries that come with Arduino but half of those don't compile on the MKR1000 and those that do it don't work at all.

Your help would be greatly appreciated!

# Answer
This relatively simple one has always worked for me on several Arduinos (but I haven't tried it on the MKR1000 specifically):

https://github.com/morrissinger/ESP8266-Websocket

I have forked it and made some changes, but nothing fundamental:

https://github.com/ocrdu/NINA-Websocket

Have a go; it will probably work for you. Note that it works on more Arduinos than the name suggests; it's quite universal.
> 0 votes

---
Tags: programming, library, websocket
---


title: Which Arduinos support ATOMIC_BLOCK?

text:
# Question
Title: Which Arduinos support ATOMIC_BLOCK?
Is there a definitive list of which Arduino architectures support the `ATOMIC_BLOCK()` macro, and a list of `#defines` for each architecture?

I've tried searching through the Arduino cores on GitHub to see where `ATOMIC_BLOCK` is used. If it's not used in a core, I've assumed it's not supported. I generated this list based upon that assumption, but how accurate is it?

```
ArduinoCore         Supported       Archived    #define
-------------------------------------------------------
  samd
  avr                  Yes                      __AVR__
  arc32
  sam                  Yes
  primo                               Yes
  megaavr              Yes
  API
  nRF528x-mbedos
  mbed

```

I would like to write some code, something like this (edited in response to comments):

```
#define ATOMIC_BLOCK_SUPPORTED (__AVR__ || __MEGAAVR__ || __SAM__)
.
.
.
#if ATOMIC_BLOCK_SUPPORTED
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#if ATOMIC_BLOCK_SUPPORTED
    }
#endif

```

For architectures that don't support `ATOMIC_BLOCK`, I would like to write my own code to save, disable and restore the global interrupt flag, something like this.

```
    asm
    {
        // Save interrupt flag.
    }
    // Clear interrupt flag.
    // Do not disturb.
    // Restore interrupt flag.

```

# Potential Solution?

```
#ifdef __AVR__
#include <util/atomic.h>
#elif defined(__ARCH2__)
#define ATOMIC_BLOCK(/* for architecture 2 */)
#elif defined(__ARCH3__)
#define ATOMIC_BLOCK(/* for architecture 3 */)
// etc
#endif
.
.
.
#ifdef ATOMIC_BLOCK
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#ifdef ATOMIC_BLOCK
    }
#endif

```

Is there a definitive list of code that saves, disables and restores the global interrupt flag for every Arduino architecture that could be dropped into each `#elif` branch?

# Answer
This answer covers: **Which Arduinos support ATOMIC\_BLOCK? And how can I duplicate this concept in C with `__attribute__((__cleanup__(func_to_call_when_x_exits_scope)))` and in C++ with class *constructors* and *destructors*?**.

# Which Arduino's support the `ATOMIC_BLOCK` macros?

> Which Arduinos support ATOMIC\_BLOCK?

Only AVR (ATmel AVR architecture) microcontrollers support the `ATOMIC_BLOCK` macros, because these macros are part of the avr-libc library, which, you guessed it!, supports only AVR microcontrollers.

AVR-based Arduinos include those based on the ATmega328 microcontroller (Arduino Uno, Nano, Mini, etc.), ATmega2560 (Arduino Mega 2560), ATmega32U4 (Arduino Leonardo, Pro Micro), etc.

# How are the `ATOMIC_BLOCK` macros implemented in C with the gcc compiler, and where can I see their source code?

avr-libc is available for download here: https://www.nongnu.org/avr-libc/ --\> "source code and documentation" link under the "Downloads" section. Ex: here is the tarball for v 2.0.0: http://download.savannah.gnu.org/releases/avr-libc/avr-libc-2.0.0.tar.bz2.

The entire source code for the `ATOMIC_BLOCK` macros is contained in **avr-libc-2.0.0/include/util/atomic.h**.

`ATOMIC_BLOCK` is an ingenious macro written in C and relying upon the gcc "cleanup" attribute C extension which can call a function you define when a variable goes out of scope. Essentially, this is identical to a C++ class destructor which gets called when an instance of a class in C++ goes out of scope. The gcc "cleanup" attribute extension is a way to get C++-like behavior in C.

Here is the official gcc documentation: https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html. It states:

> cleanup (cleanup\_function)
>
> The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
>
> If -fexceptions is enabled, then cleanup\_function is run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup\_function does not return normally.

Its format is like this:

```
int x __attribute__((__cleanup__(func_to_call_when_x_exits_scope))) = 0;

```

You use it like this:
RUN A REAL EXAMPLE OF THIS CODE IN C ONLINE HERE.

```
static __inline__ void cleanup_my_byte(uint8_t *my_byte_p)
{
    Serial.print("my_byte is going out of scope! Its value is ");
    Serial.println(*my_byte_p);
}

void setup()
{
    uint8_t my_byte __attribute__((__cleanup__(cleanup_my_byte))) = 7;
} // The following function call occurs automatically here as `my_byte`
  // exits its scope!:
  //    `cleanup_my_byte(&my_byte);`

```

Studying the **avr-libc-2.0.0/include/util/atomic.h** file referenced above, you can see how the `ATOMIC_RESTORESTATE` macro is implemented, using this attribute. I've put just the relevant pieces from that file here:

```
#include <avr/io.h>
#include <avr/interrupt.h>

#define ATOMIC_BLOCK(type) for ( type, __ToDo = __iCliRetVal(); \
                           __ToDo ; __ToDo = 0 )

static __inline__ uint8_t __iCliRetVal(void)
{
    cli();
    return 1;
}

#define ATOMIC_RESTORESTATE uint8_t sreg_save \
    __attribute__((__cleanup__(__iRestore))) = SREG

static __inline__ void __iRestore(const  uint8_t *__s)
{
    SREG = *__s;
    __asm__ volatile ("" ::: "memory");
}

```

Note that `cli()` clears (turns off) interrupts, and `sei()` sets (turns on) interrupts.

So, you can see that `ATOMIC_RESTORE_STATE` gets replaced by `uint8_t sreg_save __attribute__((__cleanup__(__iRestore))) = SREG`, which backs up the global interrupt state from the AVR `SREG` 8-bit register into `sreg_save`, then calls this function call when `sreg_save` exits its scope: `__iRestore(&sreg_save);`. That function call to `__iRestore()` then sets the `SREG` register back to where it was, restoring the interrupt state (turning it ON if it was ON before, or OFF if it was OFF before).

The official documentation for `ATOMIC_BLOCK` is here: https://www.nongnu.org/avr-libc/user-manual/group\__util\__atomic.html. An example usage is this:

```
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
    my_var_copy = my_var;
}

```

The `ATOMIC_RESTORESTATE` part backs up the `SREG` register and sets up the call for `__iRestore(&sreg_save);` to occur when `sreg_save` exits this block scope, as we've already discussed, and the `ATOMIC_BLOCK` part gets converted into this: `for ( ATOMIC_RESTORESTATE, __ToDo = __iCliRetVal(); __ToDo ; __ToDo = 0 )`. This means that the entire block is now an ingenious `for` loop which runs only once! Prior to entering the `for` loop block, `__iCliRetVal()` is called once, clearing (turning OFF) interrupts, and `__ToDo` is set to `1`, or `true`, so the `for` loop runs at least once, and then at the end of the first run it is set to `0`, or `false`, to stop the `for` loop after one single run! As we've already gone over, the `sreg_save` variable now goes out-of-scope at the closing brace and the call to `__iRestore(&sreg_save);` is made, via the gcc extension, to restore the interrupt state! Ingenious!

# How could you implement the `ATOMIC_BLOCK` functionality in Arduino in C++ (as opposed to avrlibc's gcc C version)?

In C++ (Arduino is C++, so we don't have to be limited to just C plus gcc extensions, as was the constraint in the avrlibc `ATOMIC_BLOCK` macros), you can get a similar effect using destructors in structs or classes (or, just use the avrlibc pattern shown above if you like, as that gcc C code is also perfectly valid gcc C++ code!).

## Option 1: example to create a usage style similar to C++'s `std::lock_guard`

This, for example, would implement a form of `ATOMIC_BLOCK(ATOMIC_FORCEON) {}`, using a simple class in C++:

It relies on Arduino's built-in functions `interrupts()` (same as avrlibc's `sei()` function) and `noInterrupts()` (same as avrlibc's `cli()` function). *I wish that Arduino also had built-in `saveInterrupts()` and `restoreInterrupts()` functions, but unfortunatley they don't. Someone will have to go file a feature request and request them, or implement them themselves and do a Pull Request (PR) on GitHub to try to get them back into the main Arduino branches.*

RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.

```
#define ATOMIC_BLOCK_FORCEON AtomicBlockForceOn atomicBlockForceOn_

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }
};

```

That's it! Now use it like this:

```
uint16_t my_var_copy;
{
    ATOMIC_BLOCK_FORCEON;
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `atomicBlockForceOn_` object's destructor is called here
  // and interrupts are automatically turned back ON!

```

Pretty cool!

This, I imagine, is probably exactly how C++'s `std::lock_guard` is implemented! Its usage is very similar:

```
void safe_increment()
{
    const std::lock_guard<std::mutex> lock(g_i_mutex);
    ++g_i;

    std::cout << std::this_thread::get_id() << ": " << g_i << '\n';

    // g_i_mutex is automatically released when lock
    // goes out of scope
}

```

## Option 2: example to create a usage style similar to avrlibc's `ATOMIC_BLOCK` macros

To obtain a usage style of `ATOMIC_BLOCK(ATOMIC_FORCEON) { }` in C++ one can definitely use the gcc C style which avrlibc uses, since that is also valid C++, but let's continue with the C++ class style shown just above instead, with just a few tweaks. We will add a couple more helper macros and a couple more functions to the class to make this work. Here it is, with a usage example shown at the end which is *identical* to how avrlibc's `ATOMIC_BLOCK` can be used! I think this is pretty cool too.

RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.

```
#define ATOMIC_BLOCK(type) for(type; type##_OBJECT_NAME.run(); \
    type##_OBJECT_NAME.stop())
#define ATOMIC_FORCEON_OBJECT_NAME atomicBlockForceOn_
#define ATOMIC_FORCEON AtomicBlockForceOn ATOMIC_FORCEON_OBJECT_NAME

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }

    // Can we run? Returns true to run the `for` loop or
    // `false` to stop it.
    inline bool run()
    {
        return run_now;
    }

    // Tell the `for` loop to stop
    inline void stop()
    {
        run_now = false;
    }

private:
    bool run_now = true;
};

```

Use it like avrlibc's `ATOMIC_BLOCK() { }` macro!

Usage example:

```
uint16_t my_var_copy;
ATOMIC_BLOCK(ATOMIC_FORCEON)
{
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `ATOMIC_FORCEON_OBJECT_NAME` (`atomicBlockForceOn_`) object's
  // destructor is called here and interrupts are automatically
  // turned back ON!

```

## Further reading:

1. Nick Gammon's excellent "Interrupts" page, which is how I first got started learning about interrupts in 2012~2014 or so: https://gammon.com.au/interrupts.
2. Other answer's I've done about interrupts, locks/guards, and things:
    1. global volatile variable not being updated in ISR
    2. My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
    3. My own race condition solution, demonstrating 3 (or 4, depending on how you look at it) ways to enforce **"atomic access guards"** on AVR-based 8-bit Arduinos: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278
3. What's that weird `type##_OBJECT_NAME` thing I did in the macro anyway? Read more about *macro token concatenation* using the `##` preprocessor operator in the official gcc C++ user manual here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html. Note: this also works in C of course.
4. gcc `inline` or `__inline__`, and `static inline` or `static __inline__` rules: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
> 6 votes

---
Tags: c++, interrupt, library, c
---


# Question
Title: Best strategy to parse 5 byte arrays to find a pattern
Ok here it goes, my first ever question posted to stackexchange! Please be gentle on me!

I am using an Arduino UNO (at the moment, will move to a faster micro later - but still use an Arduino sketch) to read in data as an SPI slave to extract the display data off of a commercial product that has no other exploitable data output that I can use. I am using a very generic sketch that Nick Gammon posted for the purpose of demonstrating the capability - and I can read the SPI data coming in ok. (Thanks Nick!)

The data is being pulled from a commercial product that has a 8 character, 5X7 dot matrix LED display that was specially made for this product and after exhaustive searches and emails to Broadcom/Avago - has no datasheet, but there are slightly similar products that I was able to use to get a bit of a handle on how the part works, I just went on the assumption that even if the interfaces are not the same, they probably didn't reinvent their command structure. However; the display doesn't have a nice driver chip embedded like your typical parallel LCD display.

I had to do a bit of reverse engineering using a logic analyzer to figure out:

1. It is SPI data at 4MHz.
2. The gist of the commands coming in and in what order
3. Used excel to convert the pixel mapping of the display to the font actually getting displayed on the device.
4. That the displayed font/text for each of the 8 characters is made up of 5 bytes - where the bit positions of those bites end up lighting a tiny LED in the display so the letter 'H' looks like 0x7F, 0x08, 0x08, 0x08, 0x7F. Each byte controls a column of 7 LEDs, ignoring a row.

Right now:

* I am using a modified version of Nick's slave sketch to simply extract the first 44 bytes of the command string to display something on the display
* all that is important to me is the 40 bytes after the first 4
* because those bytes are what get displayed. I am taking 5 elements of the 44 byte array that I know correspond to a character and spitting them out on the serial monitor such as:
```
0x00, 0x01, 0x5F, 0x11, 0x00 // i
0x7F, 0x08, 0x08, 0x08, 0x7F // H
etc...

```

And now after a lengthy introduction - my actual question:

*I need to parse the patterns of each of the 5 bytes that makes up a letter and convert it to ASCII text so that the actual word is displayed on the serial monitor.*

Back when I used to use another programming language / environment on PICs we had things like LOOKUP and LOOKDOWN which made comparing patterns a bit more abstracted, which is weird considering Arduinos...

I need help coming up with a function that takes the 5 bytes that I need to build each letter from and maybe compares it to an array that represents each possible letter and then maybe passes the matching result to another function to build / concatenate the displayed word out of those characters? That method sounds wildly inefficient, but it's all my little brain can come up with and I'm drawing a blank on how to even do that... I don't need a lot of error checking because thus far the data I'm getting is spot on with what I see on the actual display - we are also talking one 8 character word (max) at a time and it is fairly static, no scrolling words or a lot of chatter - just a single word or some data that changes relatively infrequently. But the displayed data can be different enough than the last to make trying to match entire words out of the question unless it's a side feature to speed things up. I think work properly it needs to work on one character out of 8 - one at a time. Another thought is maybe summing the 5 bytes to determine if we have a match or not, but I'm not sure if two different characters might end up having the same sum? Math is not my strong suit. Thanks for any and all help.

# Answer
This is really a pure programming problem rather than an Arduino one, but to get you started, you could do a table lookup, like this:

```
#include <stdio.h>
#include <string.h>

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

unsigned char patterns [] [5] =
  {

    { 0x7F, 0x08, 0x08, 0x08, 0x7F },   // H

    // other byte patterns here

  };  // end of patterns

char patterns_converted [] =
  {

  'H',

  // other letter equivalents here

  };  // end of patterns_converted

char convert_pattern (unsigned char what [5])
  {
  for (int i = 0; i < ARRAY_SIZE (patterns_converted); i++)
    if (memcmp (what, patterns [i], 5) == 0)
      return patterns_converted [i];

  return '?';

  } // end of convert_pattern

int main ()
{

  unsigned char test1 [5] = { 0x7F, 0x08, 0x08, 0x08, 0x7F };
  unsigned char test2 [5] = { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE };  // won't be found

  char x = convert_pattern (test1);

  printf ("Result for test1 is %c\n", x);

  x = convert_pattern (test2);

  printf ("Result for test2 is %c\n", x);

}

```

You would find out all your bit patterns and put them in the patterns array, and then put the equivalent letter in the patterns\_converted array.

The function convert\_pattern does a linear search of the table of patterns, returning the corresponding letter, or "?" if not found.

I coded that in pure C++, but since the Arduino IDE basically uses C++ you should be able to convert it for your use.
> 3 votes

---
Tags: c++, spi, array
---


# Question
Title: can i use L298N H bridge with 12v 7AH battery?
guys i am working on a rare project so i just need to ask some questions

I have a L298N H bridge motor driver, a Aduino uno board, 12v dc 4000rpm 2ampere motor and a 12v 7ah battery I just want to ask can i use 12v 7ah battery with my L298N H bridge motor driver please answer this project is very important to me please help

# Answer
> 1 votes
Yes, though at 2A you're at the top end of the L298N current limit. Expect excessive heating. You will have to manage your thermal environment appropriately.

You should consider a more capable driver with more current headroom and less heat problems. (Note: the L298N is a very old chip and uses old technology. It's not a good choice for modern drive systems and a more appropriate device should be investigated, for example the MC33931 as the first hit on google).

---
Tags: l298n
---


# Question
Title: How to output a true analog voltage at output pin
Regarding my program, it is a program that does some calculations and then outputs a voltage based on the result using analogWrite function. However my problem is that I had done my programming based on a misconception that analogWrite function via PWM does output an analog voltage, where in fact it only "simulates" the analog voltage instead.

Here are the relevant parts of my code :

```
int pwmOutput = 11;
int pwm = 0;

void compareNewOldVoltageYes(void)
{
  if(pv_Vnew > pv_Vold && pwm != 255)
  {
    ++pwm;           //increasing value
  }
  else if(pwm != 0)
  {
    --pwm;           //decreasing
  }
}

void compareNewOldVoltageNo(void)
{
  if(pv_Vnew > pv_Vold && pwm != 0)
  {
    --pwm;
  }
  else if(pwm != 255)
  {
    ++pwm;
  }
}

void loop()
{
   reading();
   PowerCalculation();

   if(pv_NewP > pv_OldP)
   {
      compareNewOldVoltageYes();
   }
   else
   {
      compareNewOldVoltageNo();
   }

   analogWrite(pwmOutput, pwm);           //analogWrite

   float displayPWMvolt = pwm * 0.0196;

   Serial.print("Output Voltage: ");
   Serial.print(displayPWMvolt);
   Serial.println(" V");

   pv_OldP = pv_NewP;

   Serial.print("Previous Power: ");
   Serial.print(pv_OldP);
   Serial.println(" W");

}

```

As for the circuitry, output pin 11 is being connected to a 1 ohm resistor and then to GND. (Where I measured the voltage) I am using Arduino Uno board.

**UPDATE**:

As said in the comments by @DatHa, pwm does not output voltage. **Is there a way to output voltage as said, without changing the board?**

# Answer
You basically have three options:

1. Switch to an Arduino Due which has a built-in DAC which outputs a real voltage.
2. Add an external DAC chip (such as the MCP4821/2) to create the voltage for you
3. Use a low-pass filter (R-C network) on a PWM pin.

Of the three options I usually use an MCP4822 since it gives the best results and doesn't cost as much as using a Due.
> 13 votes

# Answer
At 5V, a 1 ohm resistor will try to sink 1A and far exceed the 40mA specs. Please use at least a 5/0.040=125 ohm resistor to protect your pin. And if you put the a capacitor between your resistor and ground, the RC circuit of the capacitor will smooth out the PWM into an analog voltage.

Please try the suggested @russell answer with a 47K resistor and 1uF capacitor, you will get an analog voltage at the junction to use with your electronic load.
> 7 votes

# Answer
As far as I know Arduinos have ADC (Analog to Digital Converters) but do not have any DAC (Digital to Analog Converters). So you can not output a set voltage from any pins based on a digital value.
> 2 votes

# Answer
There is no direct way.

In addition to @Majenko

Alternative way: you can use H bridge like L293d to provide continuous level. Many diy inverter circuits are useing this technique.

http://www.instructables.com/id/How-to-Make-an-Inverter-Using-ARDUINO/?ALLSTEPS
> 1 votes

# Answer
NO.. There is no way to get an analog voltage from the Arduino. The best that you can do is to use Arduino as a Buck Voltage converter in linear or boost mode using a voltage regulator, inductor and the mosfet transistor. You will also might need to use a Mega or Dulorme which provide a PWM frequency other that the standard 50o Hz.

Best luck
> 0 votes

# Answer
I wondered if this would give a more stable output.
> 0 votes

---
Tags: arduino-uno, pwm, voltage-level, analogwrite
---


# Question
Title: Windows upload from command line gives Access Denied
saw somewhere that in order to upload a hex file to an arduino you can look at the Arduino IDE - see the command it runs, then replace the hex file with your file. this is the command I see in the output window:

`C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\yossi\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i`

I try running this from command (as admin):

```
cd "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

```

gives me `Access is denied.` in fact, just running `avrdude` gives the same error, so really - this has nothing to do with the COM port (which works fine from the IDE) I tried closing the IDE and running again, tried rebooting - the same.

\*** edit 1 \****

I actually ran this:

```
cd "C:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

```

since I didn't want to mess with wrapping the params - but I don't really think it matters - as the problem is running avrdude without any parameter still gives me the same error: `Access is denied.`

# Answer
> 1 votes
This is because you are running the Windows App Store version of the IDE.

Windows doesn't like you messing with the insides of App Store programs (I think it scares it...).

Install the *real* version of the IDE from the Arduino.cc website and it will work.

---
Tags: arduino-uno, uploading, windows, command-line
---


# Question
Title: What's the most direct way to assign Serial.read() bytes to an array?
I'm trying to send NMEA 0183 sentences through LoRa. Every dinstict NMEA message looks like several char arrays (sentences) followed by '\n'. In the below picture we see one NMEA distinct message:

This message arrives in the Arduino input buffer every 1 second with differentiated values (numbers) and it has to be sent over LoRa as fast as possible. In order to send it over LoRa I need to read all bytes on the input buffer and assign them to an array and send them as an array, not one by one. I know that Serial.read() reads only one byte, and that's the problem. How can I read all bytes and send them as a whole?

This is my code:

```
  if (Serial.available()) {
     c = Serial.read();
     rf95.send((char *)c, sizeof(c));
     rf95.waitPacketSent();

```

I use RadioHead library, and the definition of **rf.95.send** is: *RH\_RF95::send (const uint8\_t * data, uint8\_t len)*

**c** is of char type.

# Answer
I was missing a null termination character. That got me reading garbage from all over the buffer. Adding a '0' at the end of the buffer's length is mandatory. Plus, as David G. noticed, sizeof() function is incorrect. strlen() must be used.
> 0 votes

# Answer
@DataFiddler suggested something like `readBytesUntil`. In fact, you can just use `readBytesUntil`. It returns either when timeout happens or when you reach the specified terminator. It consumes, but does not include the terminator. The timeout defaults to 1000 milliseconds, and can be modified with the `setTimeout()` method.

One downside is that you can't differentiate timeout, full buffer, and terminator reached. This shouldn't be a problem except for serial transmission errors. If your data is coming in at the NMEA standard 4800 baud, you could reasonably change the timeout to 5 milliseconds and still work.

---

One thing that might bite you, is the line:

```
     rf95.send((char *)c, sizeof(c));

```

It is a mistake to cast the first parameter. The error you got indicated you should write:

```
     rf95.send(&c, sizeof(c));

```

But the sizeof is also wrong. The return type of `Serial::read()` is `int`, in part because there are 257 possible values. If you declared c as an int, its size would be 2, not 1.

In any case, if you are using readBytesUntil, you pass the same buffer you passed it to rf95.send(), and the return value from the first as the second parameter of the second.
> 1 votes

# Answer
All more complex Serial reading methods are based on `read()`.

Luckily there's a terminating character `'\n'` in your case, so you can implement something similar to `readBytesUntil` by yourself, if you want to.
> 0 votes

---
Tags: serial, programming, c++, communication, array
---


# Question
Title: Serial Monitor shows a continuous "word salad" without a loop
I have written a little program which should (at the end) host a little website. This is just my setup. But for some reason, it writes "srl?" endlessly onto the serial monitor. I just connected the ESP8266-01 to my Arduino UNO, using 115200 baud with the nodeMCU board. Using different boards results in an error telling me I should use nodeMCU.

As I have written in the title, I do not understand how it can produce an endless output without a loop with `Serial.print/write` in it.

```
#include <ESP8266WiFi.h>

const char* NAME = "x"; //ssid
const char* PWRT = "x"; //password

WiFiServer server(80);

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

  Serial.printf("connect with %s \n", NAME);
  WiFi.begin(NAME, PWRT);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }

  server.begin();
  Serial.printf("webserver open, access with %s\n", WiFi.localIP().toString().c_str());

}

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

}

```

# Answer
> 1 votes
The `ESP8266WiFi.h` is for running on an ESP8266 host, but your are trying to use it on an Arduino Uno. This caused the crash of your sketch on Arduino Uno.

Based on the connection diagram you provided, you are using the ESP-01 as an wifi-shield and the ESP-01 by default is having an AT commands firmware. In order to use the ESP-01 as a wifi shield, you need an library like WiFiEspAT.

---
Tags: arduino-uno, serial, esp8266
---


title: Four temperature SHT31 sensors on ESP32

text:
# Question
Title: Four temperature SHT31 sensors on ESP32
I have to read out the teperature and humidity of four independent SHT31 sensors with the help of an ESP32. Is there any prefered way to do this, since the only examples I can find online are only with one sensor. I have no access to the address pins of the sensors.

Thank you in advance for any help!

# Answer
> 0 votes
Try using TS3A5018, part from TI. You can then connect 4 independent I2C devices (SHT31).

There are also dedicated I2C channel multiplexers such as these.

Below is the example for I2C multiplexer from TI

# Answer
> 1 votes
Yes, reading 4 SHT31 is possible with an ESP32.

If you have the analog version, readout is quite trivial: you simply use 8 analog inputs (2 for each) to read the signal.

If you have the digital version, which has an I2C interface, you need to control each sensor's address pin separately to select the specific sensor you want to read. Otherwise, there will be an address collision on the bus.

---
Tags: i2c, esp32
---


# Question
Title: Switching a Solenoid Using Arduino's 5V Output?
I'm a bit stumped on how to switch on a solenoid using a transistor using my Arduino Nano's 5v Output. The solenoid runs on 12V, so I used an NPN transistor to connect the 12V source to the solenoid whenever Arduino sends current to the transistor's base. I connected all the grounds together to the Nano's ground pin, but the solenoid still doesn't switch.

I know the transistor works properly, because the solenoid switches when I use the battery to send base current instead of the Nano. I would think the Nano is capable of sending enough current to activate the Collector -\> Emitter path but might be wrong. I'm also wondering if it's an issue with grounding the circuit, but I've made sure there is a common ground. What do you think I'm doing wrong? BTW the transistor I am using is D882P. I would appreciate any help.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 7 votes
## Low-side switching an inductive load (such as a relay) using a microcontroller (such as Arduino), NPN BJT transistor (with full base resistor calculations), and snubber/flyback diode

*Note: this answer demonstrates using the 2N3904 NPN transistor for all of the calculations, since that's what's in the schematic in the question. However, after writing the answer, I noticed the words at the end of the question state it is a D882P (also an NPN type) transistor. So, just follow my methodology here but use the appropriate values for your NPN transistor type, which you can obtain from the datasheet. A quick Google search for "d882p datasheet" reveals this as a potential datasheet.*

2N3904 is an NPN transistor (datasheet), as opposed to a PNP transistor, so it must be connected directly to GND and switch the low side of the circuit only, so wire it like this instead:

simulate this circuit – Schematic created using CircuitLab

Notice I've added a diode, D1, to dissipate inductance-induced voltage spikes created when electromagnetic fields (a form of energy storage) collapse in the inductor each time you turn the switch OFF. This diode, due to its *function* (not type), is called a "flyback", "snubber", or "clamp" diode. Again, it protects the transistor and other components from inductance-induced voltage spikes from the relay coil/inductor. When a voltage spike occurs, it will simply travel around that loop through the diode, relay, and resistor R2 again and again and again until it has all been dissipated as heat in those components and there is no more voltage spike remaining.

I've also added a resistor R2 to limit current through the relay coil. You'll have to size this appropriately to get the correct current through your relay coil, based on the relay's datasheet. If your relay's datasheet says to hook up the relay to 12V directly, you can remove this resistor.

And you'll definitely need a base resistor (R1 in my circuit) or else you'll burn up your Arduino pin.

## First, let's collect some necessary values from the Datasheet. These will be used in the calculations below:

1. **VBE(sat)** = 0.65 to 0.95V.
    1. This is the diodic voltage drop from Base to Emitter when the transistor is "saturated", or fully ON.
2. **hFE\_min** = 30
    1. Notice in the screenshots below that I have crossed out all of the 2N3903 transistor hFE entries so they don't distract us from the 2N3904 entries, which is the transistor type I'm using for this example. I then chose the *lowest* hFE entry for this transistor, which is 30.
    2. This is the "guaranteed" minimum, or worst-case, DC current gain. The formula is simply: `I_max_permitted_from_Collector_to_Emitter = gain * I_Base_to_Emitter`. So, if your gain is 30, for example, and you drive a base current of 5mA from Base to Emitter, then the "guaranteed" maximum ***possible*** current allowed from the Collector to the Emitter will be `30 gain * 5mA = 150mA`. Again, this is not what you *will* get into the Collector, this is what you *could* get before the transistor itself starts limiting the current into the Collector rather than your load limiting the current through the Collector.
3. **Ic\_max\_continuous** = 200mA
    1. This is the max continuous current you can get from Collector to Emitter without overheating the transistor (assuming, I think, you have adequate cooling through conduction and possibly even convection and radiation via heat sinks--I need to brush up on the thermal and power equations myself). The datasheet may specify if a heat sink is required to achieve this current, but regardless, you should keep your continuous current down to about half this value or less if possible, as the device may reach crazy high temperatures of like 150 C or something with this current and no convective cooling or heat sink. For short bursts, hitting this current is just fine.

Here are some screenshots of where to find these values in the datasheet:

Notice in this next image I've crossed out all of the 2N3903 hFE lines so they don't distract us from the 2N3904 entries, which are for the transistor we care about in this example. Choose the lowest hFE value as the gain you will use in your estimates in order to have a "conservative" estimate, virtually guaranteed to fully turn on your transistor in all cases (ie: for all Collector current values you might like to switch on and off).

## Now, let's calculate a Base resistor value for an NPN BJT transistor, assuming your goal is to *fully turn on* (saturate the Base-Emitter channel of) the transistor:

VBE(sat) has a diodic voltage drop of **0.65 to 0.95V**, so your resistor would have to burn off `5 - 0.95 = 4.05V` to `5 - 0.65 = 4.35V`. Let's just use the lower 4.05V value so we will size for higher currents and faster turn-on speeds.

Your minimum hFE (gain) value for the 2N3904 transistor (not the 2N3903) is **30**. Maximum continuous Collector current, Ic is **200mA**, so let's **increase that by a factor of 2 to 4** and size for `200mA * 3 = 600mA` to 1) more fully saturate the Base to Emitter channel and get closer to full turn on under all cases, 2) get faster turn-on, and 3) overcome the fact that decreased gain occurs at higher Collector currents. In **Figure 15. DC Current Gain**, from the datasheet, for instance, shown below, it shows that the normalized gain decreases from ~0.28 at 100mA Collector current to ~0.13 at 200mA Collector current, which means that the gain of 30 found in the datasheet at 100mA Collector current indicates the gain at 200mA Collector current will actually be approximately `30 gain/(0.28/0.13) = 13.9 gain`. Simply multiplying the Collector current we are sizing for by a factor of 2 to 4 (3 in our case) accounts for this fact, so we will use 600mA instead of 200mA in our maximum Collector current calculations below.

So, `600mA / 30 gain = 20mA` Base to Emitter to get rock solid turn-on performance. Arduino can do up to **40mA** per pin so this is Ok. Note that I recommend **30mA** max per Arduino pin (for the ATmega328 microcontroller), and there is also a *combined output limit* for the ATmega328 microcontroller of ***200mA** for all pins combined*, which you should keep in mind. I describe this on my website in my article "Arduino Power, Current, and Voltage Limitations" here.

`V = IR`, so `R = V/I`, so resistor, R that we need `= 4.05V/0.020A = 202.5 Ohms`. This is the minimum recommended base resistor size. Don't go too much smaller than **200 Ohms**, if you go smaller than that at all. A 100 Ohm resistor, for instance, would allow a maximum base current of `I = V/R =` (I intentionally use the higher voltage value here) `4.35V/100 Ohms = 43.5mA`, which could damage your pin.

Don't go larger than **600 Ohms** or else you risk not turning on the transistor fully by not saturating the Base to Emitter channel. A 600 Ohm resistor would give you a guaranteed max Base to Emitter current of `I = V/R =` (I intentionally use the smaller voltage value here) `4.05V/600 Ohms = 6.75mA`, which with a gain of 30 would give you a max Collector current (based on your relay coil resistance now) of `6.75mA * 30 gain = 202.5 mA`. However, as indicated from Figure 15 shown above, a more realistic gain at 200mA Collector current might be only 13.9, which means your maximum allowed Collector current with a 600 Ohm resistor would be `6.75mA * 13.9 gain = 93.8mA`. But, at this current your gain would actually be \> 30, not 13.9, which leads back to the 200mA Collector current number. You can see this is a juggling game of numbers since the gain is NOT constant NOR linear, but rather is a function of Collector current, as shown by Figure 15 above. So, perhaps your actual maximum allowed Collector current with a resistor of 600 Ohms would be more like 130mA or something. The point is: any larger of a base resistor than 600 Ohms and you most likely won't be able to achieve the transistor's rated maximum continuous Collector current even if you wanted to. **So, there's a reasonable R value range!: 200 Ohms to 600 Ohms,** perhaps even leaning more towards the 200 Ohms side if you expect to have high momentary Collector currents anywhere near your maximum continuous Collector current rating of 200mA.

---

## Additional notes on high-side vs low-side driving with NPN BJT or N-Channel MOSFET transistors, for clarity:

An NPN transistor can switch high-side voltages too--you just have to drive the necessary Base to Emitter current is all (and don't exceed any maximum ratings)! That's it! So...if you try to drive the high side, think about it: you turn it on with 5V so your voltage from Collector to GND can't exceed ~5V now because as current starts to flow through the collector, voltage would come up on the Emitter side until your base current no longer flows. Your system would be fighting itself. Even if you gave it 12V before the Collector you'd never see more than ~5V at the Emitter, assuming your Base drive voltage was 5V. If you can design around it, go for it, but generally the "easy" or "normal" way to do things is to use NPN to switch low-side voltages and PNP to switch high-side voltages.

The same goes for N-channel and P-channel MOSFETS. Use N-channel to switch low-side voltages and P-channel to switch high-side voltages, UNLESS you are doing some fancy driving (again), of N-channel to switch high-side voltages, as N-channel MOSFETs are more efficient and can switch higher currents than their equivalent P-channel pairs, due to some electron hardware mumbo jumbo stuff.

Keywords: transistor sizing; BJT transistor circuit calculations, equations, and datasheet; arduino and electrical engineering: transistor (BJT) sizing, equations, datasheet, and calculations example

## Additional reading:

1. \[my answer\] Electronics Stack Exchange: When is a MOSFET more appropriate as a switch than a BJT? \[and a BJT more appropriate than a MOSFET\]

---
Tags: arduino-nano, relay, transistor
---