body:
I have the following fingerprint sensor: Rugged Panel Mount Fingerprint Sensor with Bi-Color LED Ring [R503] : ID 4651 : $39.95 : Adafruit Industries, Unique & fun DIY electronics and kits
Also during the enrollment process, it keeps waiting till the user places the finger and completes the enrollment. Due to this piece of code : while (! getFingerprintEnroll() ) is there a way that I could put a timer for 60 seconds and if there is no enrollment within that time exit that function?

Can someone please help me with that. Thanks!

Below is the code
````#include <Adafruit_Fingerprint.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2
#include <EEPROM.h>

//#define WHITE_LED 43

//D v16 debounce algorithm
Bounce2::Button button = Bounce2::Button(); // INSTANTIATE A Button OBJECT
#define BUTTON_PIN 7 // WE WILL attach() THE BUTTON TO THE FOLLOWING PIN IN setup()

//D v15 for audrino to connect to fingerprint sensor
//D v2
#if (defined(__AVR__) || defined(ESP8266)) && !defined(__AVR_ATmega2560__)
// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
// Set up the serial port to use softwareserial..
SoftwareSerial mySerial(2, 4);

#else
// On Leonardo/M0/etc, others with hardware serial, use hardware serial!
// #0 is green wire, #1 is white
#define mySerial Serial1

#endif

//D v15 for audrino to connect to display
#if defined(ARDUINO_FEATHER_ESP32) // Feather Huzzah32
#define TFT_CS         14
#define TFT_RST        15
#define TFT_DC         32

#elif defined(ESP8266)
#define TFT_CS         4
#define TFT_RST        16
#define TFT_DC         5

#else
// For the breakout board, you can use any 2 or 3 pins.
// These pins will also work for the 1.8" TFT shield.
#define TFT_CS        10
#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
#define TFT_DC         8
#endif

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 use:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.14", 1.3", 1.54", and 2.0" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
//#define TFT_MOSI 11  // Data out
//#define TFT_SCLK 13  // Clock out

// For ST7735-based displays, we will use this call
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

// OR for the ST7789-based displays, we will use this call
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

// D v15 need to add the following section back to determine the steps and the adc value
//DONT DELETE THE FOLLOWING SECTION
/*
  //D v1
  int readPin=A4;
  int V2=0; //D v5, v2-> analog voltage read by the pin
  int V1=0; //D v5, v1-> v2 converted into feet/hr
  int delayTime=500;

  //D v6
  int batt_ref_pin=A6; // D v6-> pin A6 connected to the vesc temp pin
  int battery_ref=80; // D v6-> comparing it to less than 0.3V
  int low_batt;
*/

//D v16 this to detect it the switch is on or off state.. if high then searching(default) and if low then enrolling
const int DIN_PIN = 7;

//D v8.. initialize sum with 1 and ID with 1
int sum1 = 0; //D v8 initilally put that as 1, so when it went into the sum(), it started as print 2 and not print 1, so modifying that to 0
int sum();
int id = 1;

//D v19 storing data in eeprom, so need extra variables to stores those data
int addr1 = 0; // D v19 storing the value of sum1 in this addr. initally started with 0 value
int var1 = 0; //D v19 storing the value which is retrieved from sum1 and then comparing to see if it is 0 (when the code runs for the first time) and nth number when running it for n-1 time
int var2 = 0; //D v19 storing the value which is retrieved from addr1 and then comparing to see if it is 0 (when the code runs for the first time) and nth number when running it for n-1 time
int addr2 = 205; //D v19 constant address where I can store and read data from.. this is used to write the data to sum and read it back
int addr3 = 206; //D v19 constant address where I can store and read data from.. this is used to write the data to addr1 and read it back

//D v20 stop the fingerprint enrolling after 60 seconds
unsigned long myTime;
unsigned long myTime60 = 60001;

void setup() {

  //D v16 debounce algo
  button.attach( BUTTON_PIN, INPUT ); // USE EXTERNAL PULL-UP
  button.interval(5);// DEBOUNCE INTERVAL IN MILLISECONDS
  button.setPressedState(HIGH); // INDICATE THAT THE LOW STATE CORRESPONDS TO PHYSICALLY PRESSING THE BUTTON // code modifed from Low to high in order to make the fingerprint sensor work

  pinMode( DIN_PIN, INPUT_PULLUP );
  tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240

  // tft print function!
  tftPrintTest();

  //D v2
  Serial.begin(9600);
  /*while (!Serial);  // For Yun/Leo/Micro/Zero/...
    delay(100);*/ // Adding these 2 lines breaks the clue and does not display half of the code below it
  /*Serial.println("\n\nAdafruit finger detect test nAdafruit Fingerprint sensor enrollment");*/

  // set the data rate for the sensor serial port
  finger.begin(57600);
  delay(5);
  if (finger.verifyPassword()) {
    // tft.println("Found fingerprint sensor!");
  } else {
    tft.println("Did not find fingerprint sensor :(");
    while (1) {
      delay(1);
    }
  }

  //arcada.display->println(F("sensor parameters"));
  finger.getParameters();
  finger.getTemplateCount();

  if (finger.templateCount == 0) {
    // arcada.display->print("Sensor doesn't contain any fingerprint data. Please run the 'enroll' example.");
  }
  else {
    //arcada.display->println("Waiting for valid finger...");
  }
}

void loop() {
  button.update();// D v16 debounce algo
  int value;
  value = digitalRead( DIN_PIN );
  tft.setTextColor(ST77XX_GREEN);
  tft.setCursor(0, 10);

  //D v16 make a pin work as a button press

  getFingerprintID();
  delay(50);
  //D v6 button A pressed
  if ( value == HIGH && button.pressed()) {
    /*  tft.setTextWrap(false);
      tft.fillScreen(ST77XX_BLACK);*/

    //D v18 added this scetion to avoid overwrite of data when the fringer print sensor is searching for data and user presses a button
    delay(100);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
    getFingerprintID();
    delay(50);

    //D v16 need to remove the comment from  line below
    //tft.println("Ready to enroll!");

    //D v6 removing this section. So it will always enroll as ID 1
    //Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");

    id = sum(); //D v8 calling this function to mention the ID number
    tft.println("Enrolling ID # ");
    tft.println(id);

    //D v20
    myTime = millis();
    if ((unsigned long)(myTime60 - myTime) >= 1)
    {
      //while (!  getFingerprintEnroll() );
      getFingerprintEnroll();
    }
    else {}
  }
  //D v6 button B pressed
  else {
    /*     tft.setTextWrap(false);
      tft.fillScreen(ST77XX_BLACK);*/
    Serial.begin(9600);
    /* while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);*/ // Adding these 2 lines breaks the clue and does not display half of the code below it
    /*  delay(500);
      tft.setCursor(0, 0);
      tft.fillScreen(ST77XX_BLACK);*/
    tft.println("fingerprnt detect tst");

    // set the data rate for the sensor serial port
    finger.begin(57600);
    delay(5);
    if (finger.verifyPassword()) {
      /*  delay(500);
        tft.setCursor(0, 0);
        tft.fillScreen(ST77XX_BLACK);*/
      tft.println("Found fingerSensor");
    } else {
      tft.println("Did not find fingerprint sensor :(");
      while (1) {
        delay(1);
      }
    }

    //arcada.display->println(F("sensor parameters"));
    finger.getParameters();
    finger.getTemplateCount();

    if (finger.templateCount == 0) {
      // arcada.display->print("Sensor doesn't contain any fingerprint data. Please run the 'enroll' example.");
    }
    else {
      tft.println("Waiting for valid finger...");
      /*    delay(50);
        tft.setCursor(0, 0);
        tft.fillScreen(ST77XX_BLACK);*/

      // arcada.display->print("Sensor contains "); arcada.display->print(finger.templateCount); arcada.display->println(" templates");
    }
  }
}

// D v6 enroll fingerprint
uint8_t getFingerprintEnroll() {

  int p = -1;
  // arcada.display->println("Waiting for valid finger to enroll as 1"); /*Serial.println(id); */ // D v6 commenting this line
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
      case FINGERPRINT_OK:
        tft.println("Image taken");
        break;
      case FINGERPRINT_NOFINGER:
        //tft.println(".");
        break;
      case FINGERPRINT_PACKETRECIEVEERR:
        tft.println("Communication error");
        break;
      case FINGERPRINT_IMAGEFAIL:
        tft.println("Imaging error");
        break;
      default:
        tft.println("Unknown error");
        break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      //tft.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      tft.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      tft.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      tft.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      tft.println("Could not find fingerprint features");
      return p;
    default:
      tft.println("Unknown error");
      return p;
  }

  tft.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID 1"); /*Serial.println(id); */// D v6 commenting this line
  p = -1;
  tft.println("Place finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
      case FINGERPRINT_OK:
        tft.println("Image taken");
        break;
      case FINGERPRINT_NOFINGER:
        // tft.println(".");
        break;
      case FINGERPRINT_PACKETRECIEVEERR:
        tft.println("Communication error");
        break;
      case FINGERPRINT_IMAGEFAIL:
        tft.println("Imaging error");
        break;
      default:
        tft.println("Unknown error");
        break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      //  tft.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      tft.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      tft.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      tft.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      tft.println("Could not find fingerprint features");
      return p;
    default:
      tft.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    tft.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    tft.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    tft.println("Fingerprints did not match");
    delay(500);
    // delay(500);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
    return p;
  } else {
    tft.println("Unknown error");
    return p;
  }

  tft.print("ID # "); tft.print(id); // D v6 commenting this line
  p = finger.storeModel(id); // D v6 commenting this line
  if (p == FINGERPRINT_OK) {
    {
      int sum();
    }
    tft.println("Stored!");
    delay(1500);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    tft.println("Communication error");
    delay(500);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    tft.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    tft.println("Error writing to flash");
    return p;
  } else {
    tft.println("Unknown error");
    return p;
  }
  return true;
}

// D v6 search fingerprint
uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      // tft.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      tft.println("No finger detected");

      //arcada.display->setTextColor(ARCADA_RED); // D v4
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      //tft.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      //tft.println("Imaging error");
      return p;
    default:
      // tft.println"Unknown error");
      return p;
  }

  // OK success!

  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      //tft.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      //tft.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      //tft.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      //tft.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      //tft.println("Could not find fingerprint features");
      return p;
    default:
      // tft.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerSearch();
  if (p == FINGERPRINT_OK) {
    tft.setCursor(0, 60);
    tft.println("Found print match!");
    /*    delay(5000);
      tft.setCursor(0, 0);
      tft.fillScreen(ST77XX_BLACK);*/
    //arcada.display->setTextColor(ARCADA_GREEN); // D v4
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    //tft.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    tft.println("Unknown fingerprnt");
    //arcada.display->setTextColor(ARCADA_BLUE); // D v4
    return p;
  } else {
    //tft.println("Unknown error");
    return p;
  }

  // found a match!
  //tft.print("Found ID #"); tft.print(finger.fingerID);
  //tft.print(" with confidence of "); tft.print(finger.confidence);

  return finger.fingerID;
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;

  // found a match!
  //tft.print("Found ID #"); tft.print(finger.fingerID);
  //tft.print(" with confidence of "); tft.print(finger.confidence);
  return finger.fingerID;
}

void tftPrintTest() {
  tft.setTextWrap(true);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(1);
  // tft.println("Hello World!");
}

//D v8 function to start counting the ID number
/*int sum()
  {
  sum1=sum1+1;
  EEPROM.write(sum1, sum1);
  return sum1;
  }*/

//D v19 updating the above logic to store data in eeprom and retrieving the data after reset or poweroff.. Refer to page 27, 28 for code and flowchart
//EEPROM data from : https://roboticsbackend.com/arduino-store-int-into-eeprom/   , https://www.norwegiancreations.com/2017/02/using-eeprom-to-store-data-on-the-arduino/
//https://roboticsbackend.com/how-to-save-values-on-arduino-with-eeprom/     , audrino forum and adafruit forum,
// EEPROM get(): https://www.arduino.cc/en/Reference/EEPROMGet   ; EEPROM put(): https://www.arduino.cc/en/Reference/EEPROMPut ; EEPROM read and write: https://randomnerdtutorials.com/arduino-eeprom-explained-remember-last-led-state/
int sum()
{
  var1 = EEPROM.read(addr2); // D v19 read the value from addr 205 and see if it has any ID already stored in it
  var2 = EEPROM.read(addr3); // D v19 read the value from addr 205 and see if it has any ID already stored in it

  if (var1 != 0 && var2 != 0) // D v19 check if this code is running for the first time. If yes then the ID should be set to sum1 and addr1 would be 0, so that ID is 1. If not continue from where it was left
  {
    sum1 = var1;
    addr1 = var2;
  }
  else
  {
    sum1 = 0;
    addr1 = 0;
  }

  sum1 = sum1 + 1;
  addr1 = addr1 + 1;
  EEPROM.write(addr1, sum1); //D v19 store the ID value in the corresponding addr
  EEPROM.write(addr2, sum1); // D v19 store the sum1 value in address 205
  EEPROM.write(addr3, addr1); // D v19 store the addr1 value in address 205
  return sum1;
}
````

title: Adafruit fingerprint sensor timer to exit out of enrolling

Answers: 0


body:
Doing some research about SD card adapters, I found these boards with a chip on them.

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

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

They are actually very common. They have a linear voltage regulator because UNO for example use 5V but SD card adapters use 3.3V. The voltage regulator has two capacitors one on the input one on the output. but what is C3? Looks like it is between the output and GND.

The other question is what is the other chip? I guess it turns sd card signals from 3.3 to 5v and viceversa. What is the name of this and what could be this chip model?

title: What is the chip in this board?

Answers: 1

body:
> **but what is C3? Looks like it is between the output and GND.**

C3 is likely a 10 uF cap for the 3v3 output of the regulator.

[![schematic][1]][1]
(Source: [datasheet for Sunrom SD module](https://www.sunrom.com/get/192293) (PDF))

> The circuit design used in the AMS1117 series requires the use of
an output capacitor as part of the device frequency compensation.
The addition of 22µF solid tantalum on the output will ensure
stability for all operating conditions.
When the adjustment terminal is bypassed with a capacitor to
improve the ripple rejection, the requirement for an output
capacitor increases. The value of 22µF tantalum covers all cases of
bypassing the adjustment terminal. Without bypassing the
adjustment terminal smaller capacitors can be used with equally
good results.

(Source: [datasheet for AMS1117 voltage regulator](http://www.advanced-monolithic.com/pdf/ds1117.pdf) (PDF))

---

> **The other question is what is the other chip? I guess it turns sd card signals from 3.3 to 5v and viceversa. What is the name of this and what could be this chip model?**

At least some of these modules use the LVC125A quad bus buffer gate.

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

  [1]: https://i.stack.imgur.com/ik85c.png
  [2]: https://i.stack.imgur.com/DdJ1T.jpg


body:
I have installed Arduino IDE on Ubuntu 20.04 LTS. I have installed it from the tar file (ie not from snap) and I have added myself to the dialout and tty groups. When I look at groups I get:

`adm tty dialout cdrom sudo dip plugdev lpadmin lxd sambashare`

I am trying to upload a simple bluetooth script to a Nano 33 BLE, and I have installed the `mbed board driver` and the `ArduinoBLE library`.

Whatever I try, I get an error, preventing me from uploading to the board.

```
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM0; Method name - openPort(); Exception type - Port not found.
```
I dont know what else to try, so if anyone has any suggestions, I would really appreciate it. I have googled for a while, and havent been able to find anything that works.

Thanks!

title: Cant upload, port not found error, ubuntu 20.04 LTS

Answers: 0


body:
Let me just start off by saying that this is the first time I've attempted a project at this scale. I'm not sure that I'm even taking the right approach on this.

I'm attempting a project inspired by [Daniel Rozin][1]. This is basically an array of small stepper motors representing display pixels, where it's lighter when pointing towards a reference light and darker as it's points away. Each Arduino controls two steppers through two ULN2003 drivers. These nodes will be given instructions by a raspberry-pi via i2c or spi.

*My question is this:* One of my goals is to reprogram the ATmega328Ps through the raspberry pi without taking down the entire display and reprogramming each of the nodes individually. I would expect my code to go through a number of iterations, and reprogramming these individually sounds like a nightmare. Is it possible to reprogram these nodes by address from the raspberry-pi? Is this a problem that should be tackled using some standard mechanism?

Here is what I'm currently thinking about. And I'm not an expert here. I could be way off base. I don't know... According to [this writeup][2], when the application starts, the bootloader is looking for a series of byes to kick off the reprogramming process. What I'm thinking about is forking the arduino bootloader project and defining a different expected series of bytes for each node.

  [1]: https://www.youtube.com/watch?v=kV8v2GKC8WA
  [2]: https://www.baldengineer.com/arduino-bootloader.html

title: Reprogram By Address: Arduino Node Array

Answers: 0


body:
I am designing simple "Simon Says game" using Arduino. Simon says is a game in which a LED pattern is played and user has to mimic the pattern. There are 10 Rounds. First Round = 1 led, second round = 2 leds and so on. When the first round is played, one led blinks and player has to press the corresponding button. Then if it presses the right button, next round plays in which two LEDs glow and player has to press 2 buttons in sequence. I am having problem in detecting the button press in a loop for more than 1 round. Here is snippet of the code:

    void loop() {
      for (int i = 1; i <= ROUNDS; i++)
      {
        digitalWriteGeneric(i);
        bool wait = 1;
        int expected = Sequence[i - 1];
        while (wait)
        {
          int value = digitalReadGeneric();
          if (expected == value)
          {
            Serial.print("Right");
            wait = 0;
            break;
          }
        }
      }
    }
    int digitalReadGeneric()
    {
      for (int i = 0; i < NUM_LIGHTS; i++)
      {
        Readings[i] = digitalRead(buttonPin[i]);
        if (Readings[i] == 1)
        {
          return i;
        }
      }

    }

Here, ROUNDS = 10
digitalwritegeneric is working fine, it plays the pattern for corresponding pattern. For round more than one how can i detect button press in sequence?. Kindly tell, what I am doing wrong.

title: Detect button press in a loop

Answers: 1

body:
Looking into your `for`-loop:
```c
for (int i = 1; i <= ROUNDS; i++)
  {

    // Write sequence
    digitalWriteGeneric(i);

    // Read sequence
    bool wait = 1;
    int expected = Sequence[i - 1];
    while (wait)
      {
        int value = digitalReadGeneric();
        if (expected == value)
          {
            Serial.print("Right");
            wait = 0;
            break;

            // Setting vlag to false will exit the while loop
            // break will also exit the while loop
            // so only need to do 1 of the 2
            // but then you won't be able to read anymore, it exited the while-loop
          }
      }
  }
```

You only check the first button, and if this one is correct you go out of the `while` loop, ending the reading.

You can change the type of variable `wait` to an `uint8_t` (init to `0`) and if the `value` is right, increment `wait`. The while-loop becomes: `while (wait < i) {}`. You can use `break` to stop reading when the player clicked a wrong button.

To see if the player did the sequence correctly:
`if (wait == i) {"GOOD";} else {"BAD";}`


body:
I'm trying to transfer data between a Arduino Uno board to a NodeMCU ESP8266 board, using nRF24L01+ transceivers module and RF24 library on both side. The data I'm transferring are stored in a ```struct``` defined this way:
```
// Struct declared in both code
struct sensorData {
    bool doorOpened;
    int light;
    int temperature;
    int humidity;
    float voltage_battery;
};
// Variable in Uno code (source node)
sensorData dataToSend;
// Variable in ESP8266 code (dest node)
sensorData dataToReceive;
```
But the data are not transferred properly between the two boards and I get random values or 0 when trying to display them from ESP8266 (values are correctly displayed from Uno).

Display in Uno (using ```signed short``` as data type, see following paragraphs):
[![Data displayed from Arduino UNO][1]][1]

Display in ESP8266 (using ```signed short``` as data type, see following paragraphs):
[![Data displayed from NodeMCU ESP8266][2]][2]

After some testing, I found out that memory-allocation on both boards are different, as Uno takes *2 bytes* to store ```int``` while ESP8266 takes *4 bytes*. Moreover, sensorData takes *11 bytes* of memory on Uno (1 for ```bool```, 2 for ```int``` and 4 for ```float```, which sums up to *11 bytes*), but takes *20 bytes* of memory on ESP8266 (1 for ```bool```, 4 for ```int``` and 4 for ```float```, which does NOT sum up to 20 !).

Trying to solve this, I tried changing ```int``` for ```signed int```, ```byte```, ```short```, ```signed short``` but the transmission problem remains. When using ```short``` or ```signed short``` (which takes *2 bytes* on both boards), my structure ```sensorData``` still takes *11 bytes* of memory on UNO while it takes *12 bytes* of memory on ESP8266. For some reason, ESP8266 always takes more space than needed to store ```sensorData```, probably causing bits to be wrongly placed when receiving data.

I'm sure that both boards, radio module and transmission protocol work as I successfully tested the same code with a smaller struct (```text``` was "Hello World !" and ```cmp``` was increased at each transmission):
```
struct Package {
    char text[16];
    long cmp;
};
```
Does anyone have faced this issue before ? How could I solve that ?

  [1]: https://i.stack.imgur.com/QaYxi.png
  [2]: https://i.stack.imgur.com/V2eSd.png

title: Same structure taking different memory space on Uno and NodeMCU ESP8266, leading to data corruption when transferring via nRF24L01+

Answers: 5

body: The esp8266 has a 32 bit mcu and the uno an 8 bit mcu so their variables have different storage requirements. You need to allow for this in your code.

body:
`int`, `long`, etc have different sizes depended on the compiler and target.

Use explicit sizes to make sure you're variables have the size you want. Eg. `uint8_t`, `int16_t` or `int32_t`, ... (as @Mat commented)

Also, I wouldn't use `bool` (if writing in `C`) as it's not really standard in `C` and the size is also implementation dependent: https://stackoverflow.com/questions/1608318/is-bool-a-native-c-type

Extra, there are different types of explicit sizes: https://stackoverflow.com/questions/5254051/the-difference-of-int8-t-int-least8-t-and-int-fast8-t
(but don't use it here otherwise you'll have again the same problem :))

body:
In addition to the rule of always using fixed and predictable sizes across different architectures, it's also a good idea to *pack* your structs. This prevents the compiler from padding smaller variables with blanks to align them with the architecture's word boundary when needed.  For example:

```c++
struct Package {
    uint8_t doorOpened;
    uint16_t light;
    int16_t temperature;
    uint8_t humidity;
    float voltage_battery;
} __attribute__((packed));
```

Depending on what "bytewise access" instructions are available on your target 32-bit architecture, without the packing you may end up with (worst case) the equivalent of:

```c++
struct Package {
    uint8_t doorOpened;
    // 3 bytes padding
    uint16_t light;
    // 2 bytes padding
    int16_t temperature;
    // 2 bytes padding
    uint8_t humidity;
    // 3 bytes padding
    float voltage_battery;
} __attribute__((packed));
```

Of course there may be a granular enough access method in the architecture which means the packing is irrelevant - but it's better to have it and it be ignored than to not have it and need it.

body:
There are three main issues you may need to deal with when passing structures between systems that use different processors.

The first is that data types vary in size between architectures. You can avoid this for integers by avoiding the basic C types and instead using the fixed size types from stdint.h/cstdint. For floating point types this is less of a problem as most systems use the IEEE single and double precision types for float and double.

The second is padding, according to the C standard padding is implementation dependent. In practice most compilers will insert the minimum amount of padding needed to meet alignment requirements. Exactly what the alignment requirements are also depend on the implementation, but the alignment requirement of a type is always a factor of it's size.

You can thus avoid compiler-generated padding on most architectures by designing your structure to place types on "natural" alignment (that is their offset in the structure is a multiple of their size) and to have a size that is a multiple of the largest type in the structure. So you might design your structure as.

    struct sensorData {
        int8_t doorOpened; //size 1 offset 0
        int8_t spare; //size 1 offset 1
        int16_t light; //size 2 offset 2
        int16_t temperature; //size 2 offset 4
        int16_t humidity; // size 2 offset 6
        float voltage_battery; //size 4 offset 8
    };

Another option is to use packed structures, but extreme care is needed when using such, especially in C++. It is easy to create unaligned pointers or references.

The final issue is byte order (also known as endian), if your systems use different byte orders for integer or floating point values you will need to insert conversions to deal with this.

body:
For all the reasons mentioned in the other answers (different types sizes, alignment requirements and endianness), it's often a bad idea to use structs for data that needs to be sent/received (be it over the network or stored in files), as interoperability is often a problem.

Using a plain array of bytes (i.e. uint8_t[]) is often a much better solution, together with functions to read/write data with specific types at specific offsets.

In many higher-level languages (perl, php, python...) this is often done using `pack`/`unpack` or equivalents, but as far as I know there is no direct equivalent in C.

You then end up using temporary variables, [`htons`/`ntohs`/`htonl`/`ntohl`](https://linux.die.net/man/3/htons) and `memcpy` to copy data between the temporary variables and the transmit buffer. Floats are a bit more tricky because even though their format is well defined, they endianness is not, and may not be the same as integers, but `htonf`/`ntohf` are rare. In your case, I would recommend converting to integers with a factor of 10 (if you need one digit) or 100 (if you need 2) for instance.

If you're using C++ you could consider using Google's [Protocol buffers](https://developers.google.com/protocol-buffers)


body:
Trying to get the duty cycle % from an input (pin27) on my ESP32 that is currently used for analog input to read out the voltage provided by a GM driver.

Anybody has an idea on how could I achieve this?

 - Used controller: https://heltec.org/project/wifi-kit-32/
 - Used HV driver: https://rhelectronics.net/store/high-voltage-400v-geiger-tube-driver-two-channels-with-signal-buffer-for-muon-cosmic-ray-coincidence-detector.html

Thanks!

title: How to correctly measure the duty from an interrupt that is used for counting

Answers: 0


body:
```
import muvium.compatibility.arduino.*;

public class Class0 extends Arduino{

/*
Author: First Name MI. Last Name
Date: June 25, 2021
Title: Arduino Experiment 2
Description: Writing to the Output Pins using the FOR statement

Create a program that will display four different LED sequences having
different transition states repeated at different number of times and
that the whole program will repeat itself continuously

Apply the concept of using funcions for each of the four LED sequences,
 each of which are to be called upon from the main program.

This time simplify the LED sequence functions using FOR control statements
to achieve the required iterations

Pin modes of each LED pins are to be iterated together using a FOR statement

The circuit:
 * LEDs connected from digital pin 4-11, all with respect to ground.
*/
// ---------------------------------------------------------
// Declaration of Global Variables:
  int led1 = 4; // LED1 connected to digital pin 4
  int led2 = 4; // LED2 connected to digital pin 4
  int led3 = 4; // LED3 connected to digital pin 4
  int led4 = 4; // LED4 connected to digital pin 4
  int switchPin1 = 2; // PushButton connected to digital pin 2
  int switchPin2 = 3; // PushButton connected to digital pin 3
  int buttonState1 = 0; // variable for reading pushbutton status
  int buttonState2 = 0; // variable for reading pushbutton status
// ---------------------------------------------------------
  public void setup() {
    // the setup() method runs once, when the sketch starts
    // initialize the digital pins as outputs;

    for (led1 = 4; led1 < 12; led1++) {
      pinMode(led1, OUTPUT); // Configure pin 4 to 11 as outputs
    }
    pinMode(switchPin1, INPUT);// Configure pin 2 as input
    pinMode(switchPin2, INPUT);// Configure pin 3 as input
  }
// ---------------------------------------------------------
  public void loop() {
    // the loop() method runs over and over again,
    // as long as the Arduino has power

    // read the state of pushbutton value
    buttonState1 = digitalRead(switchPin1);
    buttonState2 = digitalRead(switchPin2);

    switch (buttonState1) {
      case (0):
        for (led1 = 7, led2 = 8; (led1 > 3) && (led2 < 12); led1--, led2++) {
        digitalWrite(led1, HIGH); // set the LED on
        digitalWrite(led2, HIGH); // set the LED on
        delay(500); // wait for 500 milliseconds
        digitalWrite(led1, LOW); // set the LED off
        digitalWrite(led2, LOW); // set the LED off
        }
        break;

      case 1:
        for (led1 = 11, led2 = 9, led3 = 7, led4 = 5; (led1 > 9) && (led2 > 7) && (led3 > 5) && (led4 > 3); led1--, led2--, led3--, led4--) {
        digitalWrite(led1, HIGH); // set the LED on
        digitalWrite(led2, HIGH); // set the LED on
        digitalWrite(led3, HIGH); // set the LED on
        digitalWrite(led4, HIGH); // set the LED on
        delay(500); // wait for 500 milliseconds
        digitalWrite(led1, LOW); // set the LED off
        digitalWrite(led2, LOW); // set the LED off
        digitalWrite(led3, LOW); // set the LED off
        digitalWrite(led4, LOW); // set the LED off
        }
        break;

      case 2:
        for (led1 = 11, led2 = 10, led3 = 9, led4 = 8; (led1 > 6) && (led2 > 5) && (led3 > 4) && (led4 > 3); led1-=4, led2-=4, led3-=4, led4-=4) {
          digitalWrite(led1, HIGH); // set the LED on
          digitalWrite(led2, HIGH); // set the LED on
          digitalWrite(led3, HIGH); // set the LED on
          digitalWrite(led4, HIGH); // set the LED on
          delay(500); // wait for 500 milliseconds
          digitalWrite(led1, LOW); // set the LED off
          digitalWrite(led2, LOW); // set the LED off
          digitalWrite(led3, LOW); // set the LED off
          digitalWrite(led4, LOW); // set the LED off
          }
          break;

      default:
        for (led1 = 11, led2 = 4; (led1 > 7) && (led2 < 8); led1--, led2++) {
          digitalWrite(led1, HIGH); // set the LED on
          digitalWrite(led2, HIGH); // set the LED on
          delay(500); // wait for 500 milliseconds
          digitalWrite(led1, LOW); // set the LED off
          digitalWrite(led2, LOW); // set the LED off
          }
    }
  }
}
```

title: how to use switch case with two push buttons, I don't know how to combine buttonState1 and buttonState2

Answers: 1

body:
I don't know what that code is, but it's not Arduino code. It looks like it's wrapped in some other class.  But in *real* Arduino code...

To "combine" your two button states it helps to think of them as two individual bits within a byte. A byte is made up of 8 bits, and any of them can be on or off. If you associate your two buttons with two of those bits you can represent them as a single number in a byte.

For example if you use:

```c++
uint8_t buttonStates = (digitalRead(switchPin2) << 1) | digitalRead(switchPin1);
```

you create a single variable containing both states.  In simple terms that means "Read switchPin2, shift the result one bit to the left, then read switchPin1 and superimpose the two results together".

So the result is a byte where bit 1 is switchPin2 and bit 0 is switchPin1.

It gives you, then, a truth table of:

```
SP1 | SP2 | Variable
----+-----+----------
 0  |  0  | 0b00000000
 1  |  0  | 0b00000001
 0  |  1  | 0b00000010
 1  |  1  | 0b00000011
```

Which of course is the numbers 0-3 in decimal.

So then you can use a switch:

```c++
switch (buttonStates) {
    case 0: // switchPin1 == 0, switchPin2 == 0
        // do something
        break;
    case 1: // switchPin1 == 1, switchPin2 == 0
        // do something
        break;
    case 2: // switchPin1 == 0, switchPin2 == 1
        // do something
        break;
    case 3: // switchPin1 == 1, switchPin2 == 1
        // do something
        break;
}
```


body: Last week I got my new Arduino nanao ble sense. Today I was executing a code on it which reads every sensor data on it and print it on serial monitor. I changed some parameters in my code and upload my code, while the code was uploading I opened the serial monitor and code was fully uploaded. Suddenly i got an error on terminal saying cannot find upload port. After that my Arduino board was never detected by the system. I tried to $lsusb to check whether the device is mounted on usb port but it didn't show up.... I tried on different PC and even that not detected... Plzz let me know if my hardware is damaged in someway? OR is there a solution to this???

title: Arduino nano BLE sense Serial port Suddenly stopped working

Answers: 1

body:
All that has happened is that you don't have a sketch running. When you have a board with a native USB connection a sketch has to be running to make that USB connection *be* anything.

You corrupted your sketch, so it's not executing.

All you need to do is manually trigger the bootloader to install a new sketch. According to the "Getting started" page:

> NOTE: If the board does not enter the upload mode, please do a double press on the reset button before the upload process is initiated; the orange LED should slowly fade in and out to show that the board is waiting for the upload.


body:
In [this tutorial][1] the writer used digital pin 2-5 and pin 11 and 12, can I use other I/O pins if I define it in the library?

    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

  [1]: https://www.arduino.cc/en/Tutorial/LibraryExamples/HelloWorld

title: Quick noob question about connecting 16x2 LCD

Answers: 1

body: Yes, you can. There is nothing special about the pins an LCD like this uses, it's just simple IO.  You can even use the "Analog" pins for digital IO.  The only pins to stay away from, which is a good rule in general, are the TX and RX pins (pins 0 and 1 on the UNO) as they are used for communication with the PC through USB.  All the other pins are fare game for something as simple as an LCD.


body:
As part of my application, I need to be able to update the code on my mega 2560 in the field with a download from the internet.

I have found this code in the AT Mega 2560 data sheet

     ;-the routine writes one page of data from RAM to Flash
     ; the first data location in RAM is pointed to by the Y pointer
     ; the first data location in Flash is pointed to by the Z-pointer
     ;-error handling is not included
     ;-the routine must be placed inside the Boot space
     ; (at least the Do_spm sub routine). Only code inside NRWW section can
     ; be read during Self-Programming (Page Erase and Page Write).
     ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24),
     ; loophi (r25), spmcrval (r20)
     ; storing and restoring of registers is not included in the routine
     ; register usage can be optimized at the expense of code size
     ;-It is assumed that either the interrupt table is moved to the Boot
     ; loader section or that the interrupts are disabled
    ..equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words
    .org SMALLBOOTSTART
    Write_page:
        ; Page Erase
        ldi  spmcrval, (1<<PGERS) | (1<<SPMEN)
        call Do_spm

        ; re-enable the RWW section
        ldi  spmcrval, (1<<RWWSRE) | (1<<SPMEN)
        call Do_spm

        ; transfer data from RAM to Flash page buffer
        ldi  looplo, low(PAGESIZEB) ;init loop variable
        ldi  loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256

    Wrloop:
        ld   r0, Y+
        ld   r1, Y+
        ldi  spmcrval, (1<<SPMEN)
        call Do_spm
        adiw ZH:ZL, 2
        sbiw loophi:looplo, 2 ;use subi for PAGESIZEB<=256
        brne Wrloop

        ; execute Page Write
        subi ZL, low(PAGESIZEB)       ;restore pointer
        sbci ZH, high(PAGESIZEB)      ;not required for PAGESIZEB<=256
        ldi  spmcrval, (1<<PGWRT) | (1<<SPMEN)
        call Do_spm

        ; re-enable the RWW section
        ldi  spmcrval, (1<<RWWSRE) | (1<<SPMEN)
        call Do_spm

        ; read back and check, optional
        ldi  looplo, low(PAGESIZEB)   ;init loop variable
        ldi  loophi, high(PAGESIZEB)  ;not required for PAGESIZEB<=256
        subi YL, low(PAGESIZEB)       ;restore pointer
        sbci YH, high(PAGESIZEB)
    Rdloop:
        elpm r0, Z+
        ld   r1, Y+
        cpse r0, r1
        jmp  Error
        sbiw loophi:looplo, 1         ;use subi for PAGESIZEB<=256
        brne Rdloop

        ; return to RWW section
        ; verify that RWW section is safe to read
    Return:
        in   temp1, SPMCSR
        sbrs temp1, RWWSB     ; If RWWSB is set, the RWW section is not ready yet
        ret
        ; re-enable the RWW section
        ldi  spmcrval, (1<<RWWSRE) | (1<<SPMEN)
        call Do_spmr
        jmp Return

    Do_spm:
        ; check for previous SPM complete
    Wait_spm:
        in   temp1, SPMCSR
        sbrc temp1, SPMEN
        rjmp Wait_spm
        ; input: spmcrval determines SPM action
        ; disable interrupts if enabled, store status
        in   temp2, SREG
        cli
        ; check that no EEPROM write access is present
    Wait_ee:
        sbic EECR, EEPE
        rjmp Wait_ee
        ; SPM timed sequence
        out  SPMCSR, spmcrval
        spm
        ; restore SREG (to enable interrupts if originally enabled)
        out  SREG, temp2
        ret

I am trying to convert this to code I can use in my arduino project under wiring. My first question is the register. It looks like `spmcrval` is register 20, but how can I access that register from within my arduino project?

I have found constants like `SPMEN` in the arduino header, but not these register names.

Also, feel free, if you wish, to avoid the drama and say, "Here's the C source code," which will be worth a certain amount of hero worship.

Everything appears to use avrdude and so I'm trying to parse that as well.

title: Loading code to a mega 2560

Answers: 1

body:
Only from bootloader section is it possible to write to flash on ATmega2560. Optiboot 8 has a do_spm function to write to flash. It is accesible over a header file available in [examples in the Optiboot GithHub repository][1].

After the updated application binary is written to free part of the flash by the running application it is necessary to copy the updated application to run location from address 0. This must be done again by the bootloader.

Optiboot builds in [MCUdude Mega Core][2] and Mighty Core have Optiboot enhanced with my copy_flash_pages function which copies the pages and then resets the MCU.

[My ArduinoOTA library][3] uses do_spm and copy_flash_pages function to store and apply uploaded sketch binary. The InternalStorage object can be used to [apply a downloaded binary][4] too.

  [1]: https://github.com/Optiboot/optiboot/tree/master/optiboot/examples/demo_dospm
  [2]: https://github.com/MCUdude/MegaCore
  [3]: https://github.com/jandrassy/ArduinoOTA
  [4]: https://github.com/jandrassy/ArduinoOTA/blob/master/examples/Advanced/OTASketchDownload/OTASketchDownload.ino


body:
I'm trying to retrieve the current selected/saved index of my `AutoConnectSelect` Right now i'm creating a type that reads the saved json:

     AutoConnectSelect& bright = settingsAux["scr_brightness"].as<AutoConnectSelect>();

How can i get the index of the element selected in `bright` as an integer?

`bright.value` and `bright.value()` are both invalid in this context.

Any help or insight into how these types work would be appreciated.

title: ESP8266 AutoConnect ACSelect selection index

Answers: 1

body: The member i was looking for is `AutoConnectSelect.selected` I just subtract the value by one to get the index, as `.selected` starts from 1.


body:
I'm running into an issue where when I try to set up a BLE service my tflite inference seems to hang/crash. I used https://experiments.withgoogle.com/tiny-motion-trainer to train a model to recognize a few gestures with my nano. The code I'm using is mostly sample code generated by the site. Here's the code that correctly outputs gestures to the Serial monitor:

```
/**
* TinyML Trainer Example.
* Version: v005
*
* This is an example generated by Tiny Motion Trainer
* It is pre-filled with your trained model and your capture settings
*
* Required Libraries:
* - TensorFlow Lite for Microcontrollers (tested with v2.4-beta)
* - Arduino_LSM9DS1
*
* Usage:
* - Make sure the Arduino BLE 33 board is installed (tools->board->Board Manager) and connected
* - Make sure you have the required libraries installed
* - Build and upload the sketch
* - Keep the Arduino connected via USB and open the Serial Monitor (Tools->Serial Monitor)
* - The sketch will log out the label with the highest score once detected.
*
* This is meant as an example for you to develop your own code, and is not production ready.
*
**/

//==============================================================================
// Includes
//==============================================================================

#include <Arduino_LSM9DS1.h>
#include <ArduinoBLE.h>
#include <TensorFlowLite.h>
#include <tensorflow/lite/micro/all_ops_resolver.h>
#include <tensorflow/lite/micro/micro_error_reporter.h>
#include <tensorflow/lite/micro/micro_interpreter.h>
#include <tensorflow/lite/schema/schema_generated.h>
#include <tensorflow/lite/version.h>

//==============================================================================
// Your custom data / settings
// - Editing these is not recommended
//==============================================================================

// This is the model you trained in Tiny Motion Trainer, converted to
// a C style byte array.
#include "model.h"

// Values from Tiny Motion Trainer
#define MOTION_THRESHOLD 0.2
#define CAPTURE_DELAY 200 // This is now in milliseconds
#define NUM_SAMPLES 20

// Array to map gesture index to a name
const char *GESTURES[] = {
    "gesture1", "gesture2", "gesture3"
};

//==============================================================================
// Capture variables
//==============================================================================

#define NUM_GESTURES (sizeof(GESTURES) / sizeof(GESTURES[0]))

bool isCapturing = false;

// Num samples read from the IMU sensors
// "Full" by default to start in idle
int numSamplesRead = 0;

//==============================================================================
// TensorFlow variables
//==============================================================================

// Global variables used for TensorFlow Lite (Micro)
tflite::MicroErrorReporter tflErrorReporter;

// Auto resolve all the TensorFlow Lite for MicroInterpreters ops, for reduced memory-footprint change this to only
// include the op's you need.
tflite::AllOpsResolver tflOpsResolver;

// Setup model
const tflite::Model* tflModel = nullptr;
tflite::MicroInterpreter* tflInterpreter = nullptr;
TfLiteTensor* tflInputTensor = nullptr;
TfLiteTensor* tflOutputTensor = nullptr;

// Create a static memory buffer for TensorFlow Lite for MicroInterpreters, the size may need to
// be adjusted based on the model you are using
constexpr int tensorArenaSize = 8 * 1024;
byte tensorArena[tensorArenaSize];

//==============================================================================
// Setup / Loop
//==============================================================================

// Variables to hold IMU data
float aX, aY, aZ, gX, gY, gZ;

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

  Serial.begin(9600);

  // Wait for serial monitor to connect
  while (!Serial);

  // Initialize IMU sensors
  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }

  // Print out the samples rates of the IMUs
  Serial.print("Accelerometer sample rate: ");
  Serial.print(IMU.accelerationSampleRate());
  Serial.println(" Hz");
  Serial.print("Gyroscope sample rate: ");
  Serial.print(IMU.gyroscopeSampleRate());
  Serial.println(" Hz");

  Serial.println();

  // Get the TFL representation of the model byte array
  tflModel = tflite::GetModel(model);
  if (tflModel->version() != TFLITE_SCHEMA_VERSION) {
    Serial.println("Model schema mismatch!");
    while (1);
  }

  // Create an interpreter to run the model
  tflInterpreter = new tflite::MicroInterpreter(tflModel, tflOpsResolver, tensorArena, tensorArenaSize, &tflErrorReporter);

  // Allocate memory for the model's input and output tensors
  tflInterpreter->AllocateTensors();

  // Get pointers for the model's input and output tensors
  tflInputTensor = tflInterpreter->input(0);
  tflOutputTensor = tflInterpreter->output(0);
}

void loop() {
  // Wait for motion above the threshold setting
 if (!isCapturing) {
    if (IMU.accelerationAvailable() && IMU.gyroscopeAvailable()) {

      IMU.readAcceleration(aX, aY, aZ);
      IMU.readGyroscope(gX, gY, gZ);

      // Sum absolute values
      float average = fabs(aX / 4.0) + fabs(aY / 4.0) + fabs(aZ / 4.0) + fabs(gX / 2000.0) + fabs(gY / 2000.0) + fabs(gZ / 2000.0);
      average /= 6.;

      // Above the threshold?
      if (average >= MOTION_THRESHOLD) {
        isCapturing = true;
        numSamplesRead = 0;
        //break;
      }
    }
  }

  if (isCapturing) {

    // Check if both acceleration and gyroscope data is available
    if (IMU.accelerationAvailable() && IMU.gyroscopeAvailable()) {

      // read the acceleration and gyroscope data
      IMU.readAcceleration(aX, aY, aZ);
      IMU.readGyroscope(gX, gY, gZ);

      // Normalize the IMU data between -1 to 1 and store in the model's
      // input tensor. Accelerometer data ranges between -4 and 4,
      // gyroscope data ranges between -2000 and 2000
      tflInputTensor->data.f[numSamplesRead * 6 + 0] = aX / 4.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 1] = aY / 4.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 2] = aZ / 4.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 3] = gX / 2000.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 4] = gY / 2000.0;
      tflInputTensor->data.f[numSamplesRead * 6 + 5] = gZ / 2000.0;

      numSamplesRead++;

      // Do we have the samples we need?
      if (numSamplesRead == NUM_SAMPLES) {

        // Stop capturing
        isCapturing = false;

        // Run inference
        Serial.println("invoking");
        TfLiteStatus invokeStatus = tflInterpreter->Invoke();
        Serial.println("invoked");
        if (invokeStatus != kTfLiteOk) {
          Serial.println("Error: Invoke failed!");
          while (1);
          return;
        }

        // Loop through the output tensor values from the model
        int maxIndex = 0;
        float maxValue = 0;
        for (int i = 0; i < NUM_GESTURES; i++) {
          float _value = tflOutputTensor->data.f[i];
          if(_value > maxValue){
            maxValue = _value;
            maxIndex = i;
          }
          Serial.print(GESTURES[i]);
          Serial.print(": ");
          Serial.println(tflOutputTensor->data.f[i], 6);
        }

        Serial.print("Winner: ");
        Serial.print(GESTURES[maxIndex]);

        Serial.println();

        // Add delay to not double trigger
        delay(CAPTURE_DELAY);
      }
    }
  }
}
```
When I add the declaration `BLEService service("4798e0f2-0000-4d68-af64-8a8f5258404e");` before the `setup` function, this code no longer works. I see
```
Accelerometer sample rate: 119.00 Hz
Gyroscope sample rate: 119.00 Hz

invoking

```
in my Serial monitor and then nothing. It seems like just declaring this service is somehow causing the inference code to crash. Does anyone have any idea why that would be happening? I'd really appreciate any help!

title: Arduino Nano 33 BLE Sense TFlite inference hangs when using bluetooth

Answers: 0


body:
I am making "Simon says" game using Arduino on TinkerCad.
I am facing issue in Buzzer sound function.
I want something like this:

 1. Use the following steps to generate the tone for the red LED:
    Play 440 Hz for 150ms
     Wait for 1136us
     Play 440 Hz for 150ms

 2. Use the following steps to generate the tone for the yellow LED:
 Play 784 Hz for 150ms
 Wait for 638us
 Play 784 Hz for 150ms
3. Use the following steps to generate the tone for the blue LED:
 Play 587 Hz for 150ms
 Wait for 851us
 Play 587 Hz for 150ms
4. Use the following steps to generate the tone for the green LED:
 Play 880 Hz for 150ms
 Wait for 568us
 Play 880 Hz for 150ms

I have following functions for the above:

     void playTone2(int tone, int duration) {
      Serial.println(tone);
      for (long i = 0; i < duration * 1000L; i += tone * 2) {
        digitalWriteGeneric(buzzer, true);
        delayMicroseconds(tone);
        digitalWriteGeneric(buzzer, false);
        delayMicroseconds(tone);
      }
    }

    void playTone(int tone1) {
      Serial.println(tone1);
      if (tone1 == 440) {
        playTone2(440, 150);
        delayMicroseconds(1136);
        playTone2(440, 150);
      }
      if (tone1 == 784) {
        playTone2(784, 150);
        delayMicroseconds(638);
        playTone2(784, 150);
      }
      if (tone1 == 587) {
        playTone2(587, 150);
        delayMicroseconds(851);
        playTone2(587, 150);
      }
      if (tone1 == 880) {
        playTone2(880, 150);
        delayMicroseconds(568);
        playTone2(880, 150);
      }
      if (tone1 == 2700) {
        playTone2(250, 250);
        delay(250);
        playTone2(150, 250);
      }

    }

First there was only playTone code but I needed different values for different LEDs so I included playTone function and called playTone2 to it.
But the tones that I am getting are not accurate may be because of two functions. I will be able to resolve it if I could understand the working of playTone2 function. I tried but no use, kindly share how exactly playtone2 functions here so that I can edit my playTone function accordingly.

title: playTone function of Buzzer

Answers: 1

body:
Here is a simple sketch to test the tones used for each color of LED. I have not tested it with a speaker, but it compiles in the Arduino IDE, so perhaps it will work as is.

The call to `delayMicroseconds()` is "blocking" code, so you may want to change it to use "non-blocking" code, e.g. Use the `BlinkWithoutDelay` example in the IDE to make a `micros()` based timer.

```lang-c++
/* Arduino Uno. IDE 1.8.9
   Sketch uses 2540 bytes (7%) of program storage space.
   Global variables use 28 bytes (1%) of dynamic memory.

   red    LED: Play 440 Hz for 150ms Wait for 1136us Play 440 Hz for 150ms
   yellow LED: Play 784 Hz for 150ms Wait for 638us Play 784 Hz for 150ms
   blue   LED: Play 587 Hz for 150ms Wait for 851us Play 587 Hz for 150ms
   green  LED: Play 880 Hz for 150ms Wait for 568us Play 880 Hz for 150ms
*/
byte tonePin = 8;

void setup(){
  pinMode(tonePin, OUTPUT);
  RedLEDSound();
  YellowLEDSound();
  BlueLEDSound();
  GreenLEDSound();
}

void loop(){}

void PlayTone(unsigned int m_frequency, unsigned long m_duration, unsigned long m_pause){
  tone(tonePin, m_frequency, m_duration);
  delayMicroseconds(m_pause);
  noTone(tonePin);
}

void RedLEDSound(){
  PlayTone(440, 150, 1136);
  PlayTone(440, 150, 0);
}

void YellowLEDSound(){
  PlayTone(784, 150, 638);
  PlayTone(784, 150, 0);
}

void BlueLEDSound(){
  PlayTone(587, 150, 851);
  PlayTone(587, 150, 0);
}

void GreenLEDSound(){
  PlayTone(880, 150, 568);
  PlayTone(880, 150, 0);
}
```


body:
I have an ESP32, the current program running on it uses WiFi but, if I use WiFi and Analog read at the same time, Analog read does not work.

Why does this happen and what's the way around it?

Hardware - ESP32, Pin 25 for the ADC

Code-
```
#include <WiFi.h>

void setup() {
  Serial.begin(115200);
  WiFi.begin("You really", "Want to know"); // If this line is commented then it works
}

void loop() {
  Serial.println(analogRead(25));
}
```

title: Analog read not working while using WiFi

Answers: 1

body:
The ESP32 has two ADCs. One of them, ADC2, is actively used by the WiFi.

From the IDF documentation:

> Since the ADC2 module is also used by the Wi-Fi, only one of them could get the preemption when using together, which means the adc2_get_raw() may get blocked until Wi-Fi stops, and vice versa.

That means you can't use the ADC on any of the ADC2 channels while WiFi is on: GPIO4, GPIO0, GPIO2, GPIO15, GPIO13, GPIO12, GPIO14, GPIO27, GPIO25 and GPIO26.

But you can use ADC1, which uses pins GPIO36, GPIO37, GPIO38, GPIO39, GPIO32, GPIO33, GPIO34 and GPIO35.


body:
so i bought a DS3231 clock which i am using with [This][1] famous library .

    // DS3231_Serial_Easy
    // Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
    // web: http://www.RinkyDinkElectronics.com/
    //
    // A quick demo of how to use my DS3231-library to
    // quickly send time and date information over a serial link
    //
    // To use the hardware I2C (TWI) interface of the Arduino you must connect
    // the pins as follows:
    //
    // Arduino Uno/2009:
    // ----------------------
    // DS3231:  SDA pin   -> Arduino Analog 4 or the dedicated SDA pin
    //          SCL pin   -> Arduino Analog 5 or the dedicated SCL pin
    //
    // Arduino Leonardo:
    // ----------------------
    // DS3231:  SDA pin   -> Arduino Digital 2 or the dedicated SDA pin
    //          SCL pin   -> Arduino Digital 3 or the dedicated SCL pin
    //
    // Arduino Mega:
    // ----------------------
    // DS3231:  SDA pin   -> Arduino Digital 20 (SDA) or the dedicated SDA pin
    //          SCL pin   -> Arduino Digital 21 (SCL) or the dedicated SCL pin
    //
    // Arduino Due:
    // ----------------------
    // DS3231:  SDA pin   -> Arduino Digital 20 (SDA) or the dedicated SDA1 (Digital 70) pin

    #include <DS3231.h>

    // Init the DS3231 using the hardware interface
    DS3231  rtc(SDA, SCL);

    void setup()
    {
      // Setup Serial connection
      Serial.begin(9600);
      // Uncomment the next line if you are using an Arduino Leonardo
      //while (!Serial) {}

      // Initialize the rtc object
      rtc.begin();

      // The following lines can be uncommented to set the date and time
      //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
      //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
      //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
    }

    void loop()
    {
      // Send Day-of-Week
      Serial.print(rtc.getDOWStr());
      Serial.print(" ");

      // Send date
      Serial.print(rtc.getDateStr());
      Serial.print(" -- ");

      // Send time
      Serial.println(rtc.getTimeStr());

      // Wait one second before repeating :)
      delay (1000);
    }

Now the problem is, after i set a time it shows the time and date perfectly until i cut the power of the DS3231. while being connected to my PC when i disconnected the power of DS3231, i see the timer getting reset while it should have recorded and continued the timer. It outputs 'Monday 1.1.2021 0.0.0'

Is it the problem of my module? or i am doinng something mistake here? or the module works in this way?

whenever i disconnect arduino power from PC, it still continues to count but whenever i disconnect DS3231 from 5 v pin of Arduino, it resets back. Does that mean that the DS3231 need to use the 16Mhz crystal from Arduino to function properly??

  [1]: http://www.rinkydinkelectronics.com/library.php?id=73

title: DS3231 is unable to keep record of time

Answers: 1

body:
So you disconnect the 5V to the DS3231, but keep the SDA and SCL pins connected? By doing that, you are working outside of the recommended operating conditions.

If you leave the SDA and SCL pins connected, those pins will be at around 5V. The datasheet specifies that those pins shouldn't be higher that Vcc+0.3V. Where Vcc is 0V, in your case.

Removing power from the Arduino board will also remove the power from the I2C pins, keeping things within specifications.


body:
I have an Arduino UNO and SIM808 and I'm trying to send my GPS data to the Firebase. I have successfully created a website which I can post data from the website to the Firebase. However I'm trying to send my data from Arduino to the website which failed constantly. I have no idea what is the error.

These are my codes:

      /*
        ### Get GPS data
        1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
        2. Open the SIM808_GetGPS example or copy these code to your project
        3. Download and dial the function switch to Arduino
        4. open serial helper
        4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

        create on 2016/09/23, version: 1.0
        by jason

      */
      #include <DFRobot_sim808.h>
      #include <SoftwareSerial.h>

      #define PIN_TX    10
      #define PIN_RX    11
      SoftwareSerial mySerial(PIN_TX, PIN_RX);
      DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

      #define APN "diginet"
      #define USER ""
      #define PASS ""
      unsigned long previousMillis = 0;
      long interval = 60000;

      String the_year, the_month, the_day, the_hour, the_minute, the_second, the_time;
      String latitude, longitude;

      //DFRobot_SIM808 sim808(&Serial);

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

        //******** Initialize sim808 module *************
        while (!sim808.init()) {
          delay(1000);
          Serial.print("Sim808 init error\r\n");
        }

        //************* Turn on the GPS power************
        if ( sim808.attachGPS())
          Serial.println("Open the GPS power success");
        else
          Serial.println("Open the GPS power failure");

      }

      void loop() {
        //************** Get GPS data *******************
        getGPS();

        unsigned long currentMillis = millis();
        if (currentMillis - previousMillis > interval) {
          previousMillis = currentMillis;
          sendtoFirebase();
        }

      }

      void getGPS() {

        if (sim808.getGPS()) {
          delay(500);
          the_year = sim808.GPSdata.year;
          the_month = sim808.GPSdata.month;
          the_day = sim808.GPSdata.day;
          the_hour = sim808.GPSdata.hour;
          the_minute = sim808.GPSdata.minute;
          the_second = sim808.GPSdata.second;
          the_time = the_year + " / " + the_month + " / " + the_day + " " + the_hour + ": " + the_minute + ": " + the_second;
          Serial.print(the_time);
          //Serial.print(sim808.GPSdata.year);
          //types(sim808.GPSdata);

          latitude = String(sim808.GPSdata.lat, 6);
          longitude = String(sim808.GPSdata.lon, 6);
          Serial.println(latitude);
          Serial.println("longitude : ");

          Serial.println(longitude);

          sim808.latitudeConverToDMS();
          sim808.LongitudeConverToDMS();
          //Serial.print("latitude : ");
          //        Serial.print(sim808.latDMS.degrees);
          //        Serial.print("\^");
          //        Serial.print(sim808.latDMS.minutes);
          //        Serial.print("\'");
          //        Serial.print(sim808.latDMS.seconeds,6);
          //        Serial.println("\"");
          //    Serial.print("longitude :");
          //    Serial.print("longitude :");
          //    Serial.print(sim808.longDMS.degrees);
          //    Serial.print("\^");
          //    Serial.print(sim808.longDMS.minutes);
          //    Serial.print("\'");
          //    Serial.print(sim808.longDMS.seconeds, 6);
          //    Serial.println("\"");

          //    Serial.print("speed_kph :");
          //    Serial.println(sim808.GPSdata.speed_kph);
          //    Serial.print("heading :");
          //    Serial.println(sim808.GPSdata.heading);

          //************* Turn off the GPS power ************
          //sim808.detachGPS();
        }
      }

      void sendtoFirebase() {

        boolean newData = false;
        for (unsigned long start = millis(); millis() - start < 2000;) {
          while (sim808.getGPS()) {
            newData = true;
          }
        }

        if (newData) {
          newData = false;

          String deviceId = "ABC1235";

          Serial.print("Device ID:");
          Serial.println(deviceId);

          Serial.print("Time:");
          Serial.println(the_time);
          Serial.print("latitude:");
          Serial.println(latitude);
          Serial.print("longitude:");
          Serial.println(longitude);

          String temp;

          //build the URL to the proxy
          String url = "http://myfypproject.epizy.com/firebase.php?arduino_data=25.00";
          //  url += "&deviceid=";
          //  url += String(deviceid);
          //  url += "&lat=";
          //  url += String(latitude);
          //  url += "&lon=";
          //  url += String(longitude);

          Serial.println(url);
          sendATcommand("AT+CFUN=1", "OK", 2000);
          //AT+CGATT = 1 Connect modem is attached to GPRS to a network. AT+CGATT = 0, modem is not attached to GPRS to a network
          sendATcommand("AT+CGATT=1", "OK", 2000);
          //Connection type: GPRS - bearer profile 1
          sendATcommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\"", "OK", 2000);
          //sets the APN settings for your network provider.
          sendATcommand("AT+SAPBR=3,1,\"APN\",\"diginet\"", "OK", 2000);
          //enable the GPRS - enable bearer 1
          sendATcommand("AT+SAPBR=1,1", "OK", 2000);
          //Init HTTP service
          sendATcommand("AT+HTTPINIT", "OK", 2000);
          sendATcommand("AT+HTTPPARA=\"CID\",1", "OK", 1000);
          //Set the HTTP URL sim800.print("AT+HTTPPARA="URL","http://ahmadssd.000webhostapp.com/gpsdata.php?lat=222&lng=222"\r");
          //sendATcommand("AT+HTTPPARA=\"URL\",\"http://myfypproject.epizy.com/firebase.php?arduino_data=25.00\"", "OK", 1000);
          mySerial.print("AT+HTTPPARA=\"URL\",\"");
          mySerial.print(url);
          sendATcommand("\"", "OK", 1000);
          //Set up the HTTP action
          sendATcommand("AT+HTTPACTION=0", "0,200", 1000);
          //Terminate the HTTP service
          sendATcommand("AT+HTTPTERM", "OK", 1000);
          //shuts down the GPRS connection. This returns "SHUT OK".
          //sendATcommand("AT+CIPSHUT", "SHUT OK", 1000);

        }

        return 1;
      }

      int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout) {
        uint8_t x = 0, answer = 0;
        char response[100];
        unsigned long previous;

        //Initialize the string
        memset(response, '\0', 100);
        delay(100);

        //Clean the input buffer
        while (mySerial.available() > 0) mySerial.read();

        if (ATcommand[0] != '\0') {
          //Send the AT command
          mySerial.println(ATcommand);
        }

        x = 0;
        previous = millis();

        do {
          //if there are data in the UART input buffer, reads it and checks for the asnwer
          if (mySerial.available() != 0) {
            response[x] = mySerial.read();
            //Serial.print(response[x]);
            x++;
            // check if the desired answer (OK) is in the response of the module
            if (strstr(response, expected_answer) != NULL) {
              answer = 1;
            }
          }
        } while ((answer == 0) && ((millis() - previous) < timeout));

        Serial.println(response);
        return answer;

      }

I keep get the error of 603.

    AT+HTTPACTION=0
    OK
    +HTTPACTION: 0, 603, 0

Below are my PHP, website to firebase codes:

        <?php
    require_once 'firebaseLib.php';
    // --- This is your Firebase URL
    $url = 'https://projectname-default-rtdb.asia-southeast1.firebasedatabase.app/';
    // --- Use your token from Firebase here
    $token = 'XXXXXXXXXXJYszyqIJxr3UuGl1Zr6qHG03K';
    // --- Here is your parameter from the http GET
    $arduino_data = $_GET['arduino_data'];
    // --- Set up your Firebase url structure here
    $firebasePath = '/GPSdata';

    /// --- Making calls
    $fb = new fireBase($url, $token);
    $response = $fb->set($firebasePath, $arduino_data);
    echo $url;
    sleep(2);

**UPDATE:**

I can get code 200, but there isn't any result in my firebase or my website.

title: How to GET HTTP Request from Arduino to Firebase?

Answers: 1

body: It is just the server problem. I just changed a website and it works.


body:
I've been trying to follow this example code for interfacing my atmega328P with Mpu6050:
https://www.instructables.com/Accelerometer-MPU-6050-Communication-With-AVR-MCU/

And was wondering a couple of things. First of all, the sensors on an MPU6050 are 16-bit, which means that each sensor value such as Ax, Ay etc. are 2 byte each (8-bit + 8-bit = 16-bit = 2 bytes).

The code itself reads from the following line when obtaining the values: `AcX = Wire.read()<<8 | Wire.read();` where the MSB (8-bit) are first read, and then the LSB (8-bit); which gives us 2 bytes.

So what I don't understand is why he uses float values for storing the sensor-data and not a 16-bit int? Since Floats are 4 byte long; won't that just add a bunch of zeros to the obtained 2 bytes?

title: Why float and not 16-bit Integer? Mpu6050 with atmega328P

Answers: 2

body:
We can't know this writer's reasons, but a typical reason why someone might use floats vs. ints is that they prefer not to manage the binary-point location and any possible overflows during the following calculations. Instead, they are willing to accept the tradeoff of execution-time vs. programming time, and the increased memory requirements (both RAM and Flash) of letting the floating-point library do it for them.

Update:

Or, as implied elsewhere, the programmer doesn't know how to calculate with integer arithmetic (which to be fair, is a little more complicated than just writing out the formula).

body:
In the instructables code he's using a `float` because he wants to scale the value to a range of ±2g. The values the accelerometer gives are not the actual values but, like the Arduino's ADC, a representation of the value using a range.  By dividing that representation by 16384 you get the actual G value, which is a decimal value.

That value can be more useful than the raw data.

As for that other snippet of code you provide, it cannot work. Not only does it use global variables that don't exist, but it returns a value from a `void` function which cannot happen. I don't know quite what it hopes to achieve.


body:
I want to rewire a battery powered LED strip (as shown in the picture below) to power via an ESP32's GPIO pin. I have a ESP32 NodeMCU Development Board, powered via USB.

The LED strip has specified 3,2V/20mA for the 100 LEDs. It originally uses three AA batteries. From what I've gathered the ESP32 should have a max current output of 40mA.

Other than the LED strip, the ESP32 uses WiFi and addresses a DHT22.

The goal would be to turn the LEDs on/off via a GPIO, for example:

    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);
    digitalWrite(4, LOW);

[![LED strip][1]][1]

Would it be safe to power the LED strip via a GPIO pin?

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

title: Safe to power LED strip via ESP32 GPIO

Answers: 1

body:
Quick answer is probably not.  Why?  The numbers don't add up:

> ...3,2V/20mA for the 100 LEDs...

From [here][1] we find this comment:

> Most common LED’s require a forward operating voltage of between
> approximately 1.2 to 3.6 volts with a forward current rating of about
> 10 to 30 mA, with 12 to 20 mA being the most common range.

(Actually there are [low current LED on the market][2] now that only need about 3mA to operate.  Let us assume this is what you have for our calculations.)

So, given the above is true, and if your string of LEDs were all in parallel and had average specifications, we calculate the current and voltage of the string of 100 LEDs:

    Current: 100 x 3mA = 300mA or 0.3 Amps
    Voltage: About 2 Volts.

(Note: When designing with LED you should always refer to that LED's specification.  The above 30mA and 2 Volts is only a guess.)

So, even if your LEDs are of the low current type, you can see a string of 100 such LED in parallel exceeds the initial expected current for the entire string of 100 LEDs.

This assumes the LEDs are in parallel and the power source is a constant voltage.  What if the LEDs are in series?  Then you would need a constant current power source.  Again let's assume the individual LED specifications are 2 Volts and 3 mA.  Now the calculations might look like this:

    Current: About 3mA.
    Voltage: 100 x 2 Volts = 200 Volts

Obviously the voltage far exceeds the capability of three 1.5 Volt batteries.

Ah!  [Bigclivedotcom gives us some insight in his 2017 youtube video about repairing several variations of low voltage LED strings][3]. The 3 different strings he uses in his video address how these LED strings can be made such that different voltage and current sources can be used to power them.

In conclusion it is likely your string of LED will require more current to power then a GPIO pin who's maximum current rating is only 40mA can provide safely.

  [1]: https://www.electronics-tutorials.ws/diode/diode_8.html
  [2]: https://www.digikey.com/en/product-highlight/s/sunled/ultra-low-current-leds
  [3]: https://www.youtube.com/watch?v=DoRbHYJAwis


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

  [1]: https://i.stack.imgur.com/P9Ulq.png
There are four red LEDs and an Arduino in the picture. Each LED has a forward voltage of 2 V. My friend says that just `digitalWrite(9,HIGH)` will make the LEDs light without resistor and they won't be burnt. Is this true?

title: Can I wire LEDs without resistor with an Arduino like this?

Answers: 2

body:
I am assuming you only have 5VDC available. Your friend is almost correct, it will work for a while however in the long run it will probably fail unless you are one of the lucky ones. What is the Vf (forward voltage drop) range of the LEDS (you state 2V), and are they matched by pairs, if not they will not illuminate evenly. You are forcing the arduino to output its maximum on port D9. I believe the current will not be within the microprocessor specifications. You are assuming a LED is a voltage device, it is not it is a current device. A resistor or constant current source is normally used to drive LEDs.  The LED driving circuit must provide sufficient current to light the LED at the required brightness, but must limit the current to prevent damaging the LED and driver. Typically, the forward voltage (Vf) of an LED is between 1.8 and 3.3 volts. It varies by the color of the LED. A red LED typically drops around 1.7 to 2.0 volts, but since both voltage drop and light frequency increase with band gap, a blue LED may drop around 3 to 3.3 volts. across an LED is approximately constant over a wide range but can vary from LED to LED.

 LEDs are diodes and have a

body:
Depending on the LEDs, it might or it might not, who knows?
You'll be both safe and in control by adding a small resistor in series (either with each individual LED or, if the LED pairs are balanced, with the whole LED circuit). The resistor value depends on the LEDs and the Arduino's supply voltage.


body:
I have an Arduino due, I am trying to keep track of ticks on two wheel encoders, polling in an infinite loop results in terrible performance. Have any suggestions?

It looks like the due might have an internal counter but I don't know how to use it, is there a library?

title: Arduino DUE wheel encoder

Answers: 1

body:
You can use an interrupt handler to measure frequency. Works quite well.

```cpp
volatile int32_t _ticks = 0;
public void FrequencyIsr()
{
    _ticks++;
}

// Add this to setup()
// Mode can be FALLING, RISING or CHANGE
attachInterrupt(digitalPinToInterrupt(pin), FrequencyIsr, mode);

// Add this to loop()
int32_t currentTime = millis();
// Clear the interrupt flag, so that we can read out the counter
noInterrupts();
int32_t ticks = _ticks;
interrupts();
// and then calculate the amount of ticks since the last update (if you need the speed)
int32_t timeDelta = currentTime - _lastTime;
int32_t tickDelta = ticks - _lastTicks;
double ticksPerMs = (double)tickDelta/timeDelta;
_lastTime = currentTime;
_lastTicks = ticks;
```


body:
When I try to `#include <ArduinoBLE.h>` in my Arduino program, I get the error:

>WARNING: library ArduinoBLE claims to run on samd, megaavr, mbed, apollo3, mbed_nano, mbed_portenta architecture(s) and may be incompatible with your current board which runs on avr architecture(s).

Apart from potentially trying to import an incompatible library, am I doing something wrong? If not, are there any Arduino libraries for AVR architectures that will allow me to transfer data through Bluetooth via dealing with Services, Characteristics, Descriptors, etc...?

The Beetle Bluno BLE board is based on:

 - ICSP1: Atmega 328P
 - ICSP2: CC2540

More info about the board: https://wiki.dfrobot.com/Bluno_Beetle_SKU_DFR0339

title: BLE library for Beetle Bluno BLE with AVR architecture (Atmega328)

Answers: 1

body: The Device Is Not An Arduino Device (Uno,Mega,Nano,Mkr,etc)and arduinoBLE was made only arduino devices with builtin bluetooth


body:
If you go to the [official Arduino Nano Every page][1] and click the _Tech Specs_ tab, you'll see that it lists it as running at 20Mhz.

[![arduino nano every 20mhz][2]][2]

**Turn On Verbose Compile**

However, if you go into the Arduino IDE and go to File...Preferences... and turn on the _Show Verbose Output during: compilation_ then you can examine how the board is actually set when a program is uploaded.

[![show verbose output][3]][3]

**Examining the Output**

When you look at that output you will see that it seems to be setting the board to run at 16Mhz.

[![snapshot of compilation output][4]][4]

**Am I Looking At This Properly?**

It looks to me as if the board is actually set to run at 16Mhz, right?
Am I looking at that properly?

**Extra Question**

I'm attempting to confirm this because I am :

 1. writing code in Arduino IDE
 2. Compiling in Arduino IDE (to generate HEX file).
 3. Uploading to a stand-alone 40-pin ATMega4809

The ATMega4809 datasheet states the following:

[![16/20mhz datasheet][5]][5]

If I upload that sketch to the ATMega4809 40-pin chip, that means it will expect to run at 16Mhz, right?

**Set Fuses?**

Will the 40-pin chip be set to 16Mhz by the HEX file or will I need to set fuses on the chip to insure the chip is running at 16Mhz?

**FYI - Compiled For Correct Board**

Also you may wonder if I had the wrong board selected when I compiled, but here you can see I chose the Nano Every.

[![board set to nano every][6]][6]

  [1]: https://store.arduino.cc/usa/nano-every
  [2]: https://i.stack.imgur.com/VIr16.png
  [3]: https://i.stack.imgur.com/vRfpx.png
  [4]: https://i.stack.imgur.com/zkktV.png
  [5]: https://i.stack.imgur.com/TOBJP.png
  [6]: https://i.stack.imgur.com/oLL0g.png

title: ATMega4809 via Nano Every marked as 20Mhz, but does this confirm it is actually at 16Mhz?

Answers: 1

body:
With the Nano Every they went out of their way to make it look like as much like original Nano, to the point of providing that "register emulation" feature to make it appear that it has the 328P's older style of GPIO registers.  Running at 16MHz just make sense if you want to behave like the common Nano as much as possible.

If you want to convince yourself that it's running at 16 MHz, you can blink an LED with causes of `__builtin_avr_delay_cycles(16000000);` in between.  This [busy-waits for the requested number of cycles][1].  If it's running at 20 MHz instead of 16, you would see something faster than a 1 second delay.

<s>[They keep][2] the configuration fuse values in a file fuses_4809.bin.</s>  On further investigation, it's not entirely clear what that file is for, despite containing the correct values.  The actual OSCCFG value being used (which is the same in the file) is defined [there directly][3] in the boards.txt:
```none
nona4809.bootloader.OSCCFG=0x01
```

[![OSCCFG documentation from datasheet.][4]][4]

So you can see it's set for 16 MHz on the Nano Every.  The `-DF_CPU` in the command line [originates from a line in boards.txt][5] for the Nano Every:
```properties
nona4809.build.f_cpu=16000000L
```

and works its way into the compile command-lines via [a line in platfrom.txt][6]:
```none
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} "-I{build.core.path}/api/deprecated" {includes} "{source_file}" -o "{object_file}"
```

The `D_CPU` macro exists to inform the compiled code what frequency it will be running at.  The OSCCFG is controlling the actual frequency, it's important that they agree for any timing related code.

When you upload it's the `"-Ufuse2:w:{bootloader.OSCCFG}:m"` that becomes `"-Ufuse2:w:0x01:m"` in the avrdude command line generated from the [upload recipe][7] in platform.txt that has the actual effect of configuring the chip for 16 MHz.

If you really wanted to run at 20 MHz, you could try tweak the definitions of these, but it probably makes more sense to look at something like [MCUdude MegaCoreX][8] which appears to have a board definition for the [ATMega4809 at 20 MHz][9].

  [1]: https://gcc.gnu.org/onlinedocs/gcc/AVR-Built-in-Functions.html
  [2]: https://github.com/arduino/ArduinoCore-megaavr/blob/1.8.7/boards.txt#L69
  [3]: https://github.com/arduino/ArduinoCore-megaavr/blob/1.8.7/boards.txt#L68
  [4]: https://i.stack.imgur.com/E0lK1.png
  [5]: https://github.com/arduino/ArduinoCore-megaavr/blob/1.8.7/boards.txt#L56
  [6]: https://github.com/arduino/ArduinoCore-megaavr/blob/1.8.7/platform.txt#L58
  [7]: https://github.com/arduino/ArduinoCore-megaavr/blob/1.8.7/platform.txt#L107
  [8]: https://github.com/MCUdude/MegaCoreX
  [9]: https://github.com/MCUdude/MegaCoreX/blob/v1.0.8/megaavr/boards.txt#L84


body:
I have a stepper motor and at present it is controlled by a sketch all working fine. I need now to add it to a Win32 app to control it in circuit with existing Servo Motor. The servo Motor is working well via Firmata from Win32 app as follows

in setup part

    arduino.pinMode(9, Arduino.SERVO);

In loop

     private void btn_set_servo_Click(object sender, EventArgs e)
            {
                int angle = Convert.ToInt32(Math.Round(numupdwn_degrees.Value, 0));
                arduino.servoWrite(9, angle);//tell the servo motor go to the position
            }

How do you drive the stepper motor using Firmata has anyone got an example I can see please?

title: How to sue Arduino Nano to control Stepper motor with Firmata

Answers: 1

body:
**Update:** I have created a C# .Net App to connect and control the stepper Motor. The code and a Readme file is available at

https://github.com/zizwiz/Arduino_Projects/tree/main/FirmataStepperMotorTest

-------------------------------------
**Initial Answer:**

After a bit of thinking time I have managed to start the stepper motor running with Firmata protocol from my C# Win32 app. This post is just a basic outline I use to get it running I need lots more thinking and tinkering till I get what I need but in case this is helpful here it is.

Create a button to press to start.
Create a thread when the button is clicked

       private void btn_stepper_start_Click(object sender, EventArgs e)
            {
               var thread = new Thread(() =>
               {
                   while (true)
                   {
                       RunStepper();
                   }

               });

                thread.IsBackground = true;
                thread.Start();

            }

In the function RunStepper() create the following

     private void RunStepper()
            {
                while (true)
                {
                    arduino.digitalWrite(7, Convert.ToByte(255));
                    arduino.digitalWrite(8, 0);
                    arduino.digitalWrite(9, 0);
                    arduino.digitalWrite(10, 0);
                    Task.Delay(10);
                    arduino.digitalWrite(7, 0);
                    arduino.digitalWrite(8, Convert.ToByte(255));
                    arduino.digitalWrite(9, 0);
                    arduino.digitalWrite(10, 0);
                    Task.Delay(10);
                    arduino.digitalWrite(7, 0);
                    arduino.digitalWrite(8, 0);
                    arduino.digitalWrite(9, Convert.ToByte(255));
                    arduino.digitalWrite(10, 0);
                    Task.Delay(10);
                    arduino.digitalWrite(7, 0);
                    arduino.digitalWrite(8, 0);
                    arduino.digitalWrite(9, 0);
                    arduino.digitalWrite(10, Convert.ToByte(255));
                    Task.Delay(10);
                }
            }

As mentioned this small basic example is just a start to prove I may be able to do what I need.


body:
I think the issue is within the library because I have try to implement this code according to the tutorial that I found in YouTube [Youtube](https://www.youtube.com/watch?v=CtMBn5Td3us&t=2075s). The discussion of this tutorial is the first they implement the node js server for listening to specific event from socket io, second part they build a simple iOS application using swift to control an RGB light on the ESP8266 and the last part they make ESP8266 to listen to the event that have payload as RGB values. However, in my implementation, I use angular web application to control ON-OFF light on the Arduino but the problem when I try to listen to event that on and off, my ESP8266 don't connect to my server and print all of that message on the serial.

Here is the code for my ESP8266 to connect to my node server.
```

#include <SocketIoClient.h>
#include<ESP8266WiFi.h>
#include<Arduino.h>
#define USER_SERIAL Serial

SocketIoClient socket;
const char* ssid = "bunvath_guest";
const char* pass = "*************";
void setup() {
  USER_SERIAL.begin(115200);
  searchWifi();
  initWiFi();
  socket.on("message", handleMessage);
  socket.on("light_on",handleMessage);
  socket.emit("message","hello from esp");
  socket.begin("192.168.0.102",3000);
}

void loop() {
  socket.loop();
}
void handleMessage(const char* message, size_t length){
  USER_SERIAL.println(message);
}

  void initWiFi(){
      WiFi.mode(WIFI_STA);
      WiFi.hostname("ESP-host");
      WiFi.setPhyMode(WIFI_PHY_MODE_11G);
      WiFi.enableInsecureWEP(true);
      WiFi.begin(ssid,pass);
      while(WiFi.status() != WL_CONNECTED){
        USER_SERIAL.print(".");
        delay(1000);
      }
      USER_SERIAL.print("");
      USER_SERIAL.println("WiFi connected");
      USER_SERIAL.print("IP Address: ");
      USER_SERIAL.println(WiFi.localIP());
      WiFi.setAutoReconnect(true);
      WiFi.persistent(true);

  }
 void searchWifi(){
  int numberOfNetwork = WiFi.scanNetworks();
  USER_SERIAL.println("-----");
  for ( int i = 0; i< numberOfNetwork;i++){
    USER_SERIAL.print("Network name: ");
    USER_SERIAL.println(WiFi.SSID(i));
    USER_SERIAL.print("Signal Strength: ");
    USER_SERIAL.println(WiFi.RSSI(i));
    USER_SERIAL.println("-------------");
  }
}

```

Here is my node server code for receiving all connection from client and print the client id when new client is connecting. Moreover, this node server will listen to all the event that client emit and broadcast to other client.

```

var port = process.env.PORT||3000
const http = require('http')
const app = require('./app')

const cors = require('cors');
let message = ''
const server = http.createServer(app)
const io = require('socket.io')(server,{cors:{
    origin:'http://localhost:4200',
    credentials: true
}}
    )

server.listen(port,()=>{
    console.log("server run on ", port)
})

io.on("connection",(socket)=>{
    console.log(socket.id)
    socket.on('message', data =>{
        // console.log(data)
        socket.broadcast.emit('message',data)
    })
    socket.on('open_light',data=>{
        socket.broadcast.emit('open_light',data)
        console.log(data)
    })

})
```

Here is the message that I got from serial monitor, I feel like my Arduino has already connected to my server but it keep getting reconnect. Moreover, in my sever I did not see any new client connect to server so I am really what going on with this. Plus, I am sure that my node server is working perfectly fine because I have implement angular web application to emit event, and I saw that event printing in server.

```
12:57:13.083 -> Network name: Meas Nakry
12:57:13.083 -> Signal Strength: -85
12:57:13.083 -> -------------
12:57:13.083 -> Network name: bunvath_guest
12:57:13.083 -> Signal Strength: -57
12:57:13.083 -> -------------
12:57:13.083 -> Network name: BLaNKxD
12:57:13.083 -> Signal Strength: -89
12:57:13.121 -> -------------
12:57:13.121 -> Network name: Tuy vanny1
12:57:13.121 -> Signal Strength: -85
12:57:13.121 -> -------------
12:57:13.121 -> ....WiFi connected
12:57:17.165 -> IP Address: 192.168.0.100
12:57:17.165 -> [SIoC] add packet 42["message",hello from esp]
12:57:17.269 -> [SIoC] Disconnected!
12:57:17.269 -> [SIoC] event disconnected not found. 2 events available
12:57:17.787 -> [SIoC] Disconnected!
12:57:17.787 -> [SIoC] event disconnected not found. 2 events available
12:57:18.376 -> [SIoC] Disconnected!
12:57:18.376 -> [SIoC] event disconnected not found. 2 events available
12:57:18.992 -> [SIoC] Disconnected!
12:57:18.992 -> [SIoC] event disconnected not found. 2 events available
12:57:19.633 -> [SIoC] Disconnected!
12:57:19.633 -> [SIoC] event disconnected not found. 2 events available
12:57:20.217 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:20.217 -> [SIoC] packet "42["message",hello from esp]" emitted
12:57:20.251 -> [SIoC] Disconnected!
12:57:20.251 -> [SIoC] event disconnected not found. 2 events available
12:57:20.771 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:20.771 -> [SIoC] Disconnected!
12:57:20.771 -> [SIoC] event disconnected not found. 2 events available
12:57:21.435 -> [SIoC] Disconnected!
12:57:21.435 -> [SIoC] event disconnected not found. 2 events available
12:57:22.044 -> [SIoC] Disconnected!
12:57:22.044 -> [SIoC] event disconnected not found. 2 events available
12:57:22.596 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:22.596 -> [SIoC] Disconnected!
12:57:22.596 -> [SIoC] event disconnected not found. 2 events available
12:57:23.178 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:23.178 -> [SIoC] Disconnected!
12:57:23.178 -> [SIoC] event disconnected not found. 2 events available
12:57:23.798 -> [SIoC] Disconnected!
12:57:23.798 -> [SIoC] event disconnected not found. 2 events available
12:57:24.403 -> [SIoC] Disconnected!
12:57:24.403 -> [SIoC] event disconnected not found. 2 events available
12:57:24.945 -> [SIoC] Disconnected!
12:57:24.945 -> [SIoC] event disconnected not found. 2 events available
12:57:25.533 -> [SIoC] Disconnected!
12:57:25.533 -> [SIoC] event disconnected not found. 2 events available
12:57:26.201 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:26.201 -> [SIoC] Disconnected!
12:57:26.201 -> [SIoC] event disconnected not found. 2 events available
12:57:26.792 -> [SIoC] Disconnected!
12:57:26.792 -> [SIoC] event disconnected not found. 2 events available
12:57:27.380 -> [SIoC] Disconnected!
12:57:27.380 -> [SIoC] event disconnected not found. 2 events available
12:57:27.894 -> [SIoC] Disconnected!
12:57:27.894 -> [SIoC] event disconnected not found. 2 events available
12:57:28.711 -> [SIoC] Disconnected!
12:57:28.711 -> [SIoC] event disconnected not found. 2 events available
12:57:29.426 -> [SIoC] Disconnected!
12:57:29.426 -> [SIoC] event disconnected not found. 2 events available
12:57:30.131 -> [SIoC] Disconnected!
12:57:30.131 -> [SIoC] event disconnected not found. 2 events available
12:57:30.655 -> [SIoC] Disconnected!
12:57:30.655 -> [SIoC] event disconnected not found. 2 events available
12:57:31.254 -> [SIoC] Disconnected!
12:57:31.254 -> [SIoC] event disconnected not found. 2 events available
12:57:31.787 -> [SIoC] Disconnected!
12:57:31.787 -> [SIoC] event disconnected not found. 2 events available
12:57:32.375 -> [SIoC] Disconnected!
12:57:32.375 -> [SIoC] event disconnected not found. 2 events available
12:57:33.171 -> [SIoC] Disconnected!
12:57:33.171 -> [SIoC] event disconnected not found. 2 events available
12:57:33.731 -> [SIoC] Disconnected!
12:57:33.731 -> [SIoC] event disconnected not found. 2 events available
12:57:34.435 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:34.435 -> [SIoC] Disconnected!
12:57:34.435 -> [SIoC] event disconnected not found. 2 events available
12:57:34.978 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:34.978 -> [SIoC] Disconnected!
12:57:34.978 -> [SIoC] event disconnected not found. 2 events available
12:57:35.581 -> [SIoC] Disconnected!
12:57:35.581 -> [SIoC] event disconnected not found. 2 events available
12:57:36.180 -> [SIoC] Disconnected!
12:57:36.180 -> [SIoC] event disconnected not found. 2 events available

```

Hope anyone can find what is the issue in these codes, I am really frustrated about this for 3 days already.

title: Why when I try to connect my ESP8266 to my node sever in my localhost it keep getting disconnect and connect?

Answers: 1

body:
I think you need to allow all origins, at least to begin with. At the moment, only connections coming from the machine running node can access the sever.

Removing credentials as a next step, which I can't see being used, may also move your testing along.

```
const io = require('socket.io')(server,{cors:{
    origin:'*:*',
    credentials: true
}}
```