# Question
Title: converting comma delimited Serial message to 7 Unsigned Long variables
Working on a project where I get an input where its a comma delimited string like:

```
"255,10000000,42949672950254,12,22".

```

and then the numbers (no commas), would be split into 6 Long variables like

```
var1 = 255
var2 = 10000000
...

```

I wanted a function like this:

```
void extractIntegersFromString(String str, int& integer1, int& integer2, int& integer3, int& integer4, int& integer5, int& integer6, int& integer7) {
  int count = 0;
  String temp = "";

  for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);

    if (c == ',') {
      if (count == 0)
        integer1 = String(temp).toInt();
      else if (count == 1)
        integer2 = String(temp).toInt();
      else if (count == 2)
        integer3 = String(temp).toInt();
      else if (count == 3)
        integer4 = String(temp).toInt();
      else if (count == 4)
        integer5 = String(temp).toInt();
      else if (count == 5)
        integer6 = String(temp).toInt();
      else if (count == 6)
        integer7 = String(temp).toInt();

      count++;
      temp = "";
    } else if (c >= '0' && c <= '9') {
      temp += c;
    }
  }

  // Store the last integer if the string doesn't end with a comma
  if (temp != "") {
    if (count == 0)
      integer1 = String(temp).toInt();
    else if (count == 1)
      integer2 = String(temp).toInt();
    else if (count == 2)
      integer3 = String(temp).toInt();
    else if (count == 3)
      integer4 = String(temp).toInt();
    else if (count == 4)
      integer5 = String(temp).toInt();
    else if (count == 5)
      integer6 = String(temp).toInt();
    else if (count == 6)
      integer7 = String(temp).toInt();
  }
}

```

This function makes it work through ints, but I need the larger size of a Long.

P.S. I've tried the `atol()` function (and similar others), but that didn't work...

# Answer
First of all, it is worth noting that the third number in you example message (100000000000, i.e. 1011) is too large to fit in an `unsigned long`. On AVR-based Arduinos, and most non-64-bit platforms, an `unsigned long` is 32-bits wide and can only hold numbers up to 4294967295 (about 4.3×109). I do not know of any easy way to parse such a large number on AVR.

That being said, for parsing this kind of string into `unsigned long` numbers, I would recommend the `strtoul()` function. Compared to `atol()`, it has the benefit that it tells you where the number it read ended, so you know where to search for the next one: it saves you a call to `strchr()`. It also allows some error-checking, so you know whether the message does conform to the expected format.

Here is a tentative implementation:

```
/*
 * Parse up to `count` numeric values from `message`,
 * which must be in comma-separated-values format.
 *
 * Return the number of values successfully parsed.
 */
int parse_message(const char *message,
                  unsigned long *values, int count) {
    for (int i = 0; i < count; i++) {
        char *end;  // pointer to next non-digit
        values[i] = strtoul(message, &end, 10);
        if (end == message) return i;  // parsing failed
        if (*end == ',') end++;        // skip comma
        message = end;                 // move to the next field
    }
    return count;
}

```

And a small test sketch:

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

    unsigned long values[7];
    int count = parse_message("255,10000000,100000000000,0,255,12,22",
            values, 7);
    Serial.print(count);
    Serial.println(" numbers successfully parsed:");
    for (int i = 0; i < count; i++)
        Serial.println(values[i]);
}

void loop() {}

```
> 2 votes

# Answer
String.toInt actually returns a long. See the code:

```
long String::toInt(void) const
{
    if (buffer) return atol(buffer);
    return 0;
}

```

---

> I've tried the atol() function (and similar others), but that didn't work

Please post your "try", don't just say that you did it. Maybe you did it incorrectly.

---

Re your entire technique: There is a function strtok that is specifically designed to break up a string into substrings at a delimiter. You could use that rather than re-inventing the wheel.

However that doesn't solve your specific problem of converting the substrings into a long.
> 0 votes

---
Tags: arduino-uno, serial, arduino-nano, communication, variables
---


title: Serial plotting a pwm

text:
# Question
Title: Serial plotting a pwm
I'm trying to plot the value of the pwm that increases (every 2 sec) then decreases to compare it to the value of an encoder. I was expecting a continued value (like a step ) during 2 seconds but instead I have a triangle signal. Here is my code

```
const int pwmG = 2;
const int DirG = 8 ;
int a =0;

#define encoder1_CHA 18  //Left encoder
#define pin_channelB_left 6
int b =0;

void setup() {
  Serial.begin(9600);
  pinMode(pwmG,OUTPUT) ;
  pinMode(DirG,OUTPUT) ;
  attachInterrupt(digitalPinToInterrupt(encoder1_CHA),interruptUp,RISING);

  }

void interruptUp(){
  b = !b;

}

void loop() {
  Serial.println(b);
  //Serial.print(" ");
  pwm();

  //Serial.println(a);

  //Serial.println(b);
}

void pwm(){
   for (int i =0; i< 10; i++){
      a = a +5;
      analogWrite(pwmG, a);

      Serial.println(a);
      delay(200);
      }
      //Serial.println(b);

  for (int i =0; i< 10; i++){
    a = a -5;
    analogWrite(pwmG, a);

    Serial.println(a);
    delay(200);
  }
}

```

What I have :

What I expected (exemple found on the internet :

# Answer
> 3 votes
The first point here is, that the Serial Plotter will plot the values against time by connecting them with a straight line. This is just how it represents the data in the plot (it is just for ad-hoc visualization, not for detailed plotting and data analysis).

The second point is, that for each step you are sending only one value through the Serial interface, so only one data point per step. The Serial Plotter then plots this data point against time and connects it with the points for the other steps with a straight line. Thus you get sloped lines/triangle signal in the Serial Plotter.

The image, that you expected, looks like from an oscilloscope. This will have many more data points along the x-axis, not just one per step. Thus you can actually see the steps. If you want to reproduce the image with your code, then you can send the current value of `a` more often in each iteration of the for loop (like looping 20 times over sending the value and delaying about 10ms).

---
Tags: serial, arduino-mega, pwm
---


# Question
Title: How to change partition scheme with arduino-cli
I'm using arduino-cli to program an ESP32-S2. If I compile my sketch using the default partition scheme

```
> arduino-cli compile -b esp32:esp32:esp32s2 sketch

```

a lot of space is allocated for SPIFFS and OTA, which I don't use.

```
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.

```

Thus. I'd like to use the `huge_app` scheme, as defined in the boards.txt:

```
esp32s2.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32s2.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32s2.menu.PartitionScheme.huge_app.upload.maximum_size=3145728

```

However, selecting it doesn't have any effect:

```
> arduino-cli compile -b esp32:esp32:esp32s2 sketch --build-property build.partitions=huge_app
Sketch uses 646558 bytes (49%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39540 bytes (12%) of dynamic memory, leaving 288140 bytes for local variables. Maximum is 327680 bytes.

```

Is my command line incorrect? Why is arduino-cli not using the specified partition scheme?

# Answer
So, it turns out I have to add another build property:

```
> arduino-cli compile --build-property build.partitions=huge_app --build-property upload.maximum_size=3145728 sketch

```

where the `upload.maximum.size` is from the `boards.txt` file. Indeed, a maze of twisty little files, all alike.
> 2 votes

---
Tags: esp32, arduino-cli
---


# Question
Title: Sending values with pyserial does not function if there is also sensing on Arduino Due
I'm using an Arduino Due to make a feedback loop using python, but this does not seem to function. The python code I'm using is the following:

```
from serial import Serial
board = Serial('COM11',9600)
board.write('100'.encode()) # 100 is taken as an example

```

In fact, if I just use Arduino to measure the sensor voltage, it succeeds. It's the same if the voltage is sent without measuring the sensor. But, as soon as I put both simultaneously, the sensor is good but nothing is read by the Arduino. However, if I send the voltage not using Python but using the Arduino IDE, everything is okay.

It seems that the Arduino can't do the two operations at the same time, but this is weird. Here is my Arduino code:

```
int const controller = DAC0; // Set the controller output pin
int const sensor = A1; // Set the sensor pin
double MeanNumber = 500;

void setup() {
  Serial.begin(9600);
  pinMode(controller, OUTPUT);
  analogReadResolution(12);
}

double get_voltage(int Measure)
{
  double voltage;
  voltage = Measure * 3.3 / 4095.0;
  return voltage;
}

void loop() {
  double Measure = 0;

  double voltage;
  for (int i = 0; i < int(MeanNumber); i++) // Realize an average each MeanNumber value
  {
    Measure = Measure + analogRead(sensor) / MeanNumber;
    delay(1);
  }

  // Send the averaged measure to python
  voltage = get_voltage(Measure);
  Serial.println(voltage,4);

  // Get the feedback from python
  if (Serial.available() > 0)
  {// Verify if data are available
    String receivedData = Serial.readString(); // Read the voltage value from bytes to string
    float value = receivedData.toFloat(); // Convert the voltage into float
    analogWrite(controller,value); // Send the signal via the Arduino
  }

}

```

Do you have an idea of what is wrong with my job?

# Answer
> 2 votes
Opening a Serial connection will reset the Arduino. The python code may be doing that when it creates the port. Put a Serial.print("Starting") line in your setup function to see if that's what is happening.

---
Tags: arduino-due, python, loop
---


title: ESP32-CAM OV2640 AS A SUN SENSOR

text:
# Question
Title: ESP32-CAM OV2640 AS A SUN SENSOR
I want to use the ESP32-CAM as a sun sensor, the problem is that I would need to remove the lenses in order to put a membrane with a pinhole (like it's illustrated in the image) upon the CMOS, but I want to know first, will this make unoperable the OV2640? I want it to be working fine without the lenses, the second image is an illustrative of what I want to do.

# Answer
Consider using the ESP32-CAM as is. Instead use a pin hole camera box. Put the ESP32-CAM inside the box pointing it at the image of the sun at the back of the box. This approach mitigates problems associated with exposing the sensor to the elements and direct exposure to sun light.

In order to measure azimuth and elevation, consider mounting the device such that it points directly up from the surface of the earth. And such that it is aligned to true North. Consider using an accelerometer to detect the device is normal to the surface of the earth. And a magnetometer to detect magnetic north. And a GPS receiver to detect the position on earth. Combine the GPS data with World Magnetic Model (WMM) data to correct for magnetic declination.
> 1 votes

---
Tags: esp32-cam
---


# Question
Title: How much maximum current do the Arduino Wemos D1 (R1 & R2) consume?
I have been powering my WeMos D1 R1 and D1 R2 Arduinos (with ESP8266) using a simple USB cable connected to a standard charger whose rating is 3.1 amps. Is this sufficient to charge two such Arduino boards (it has two USB slots) simultaneously?

Also, should I be using the other Power Input which I understand is 9V?

All the specs I have seen specify the voltage but not the current usage.

Either way, what is the maximum amperage that the board might need/is rated for? Is it different for the R1 vs. R2? Is it possible to measure how much it is using from any of the pins?

# Answer
> 1 votes
> It is possible to measure how much it is using from any of the pins?

Put an ammeter (multimeter in current mode) in series with the power supply and measure it, when configured in the way you intend to use it.

---
Tags: esp8266, power, current
---


# Question
Title: MacBook + BLE Microcontroller Incompatibility?
I've programmed an Adafruit Feather nRF52840 board to send MIDI signals to my computer via BLE. I can confirm that the board pairs successfully with an Android phone and a Windows PC, but my laptop (MacBook Pro 2021) will not recognize the board; it does not appear in the Bluetooth menu as an option for pairing. I've tried the following troubleshooting options:

1. Turned bluetooth off & on on laptop
2. Turned device off & on
3. Added the name of the board in the code (advertisement.complete\_name = "BOARD\_NAME")
4. Downloaded Bluefruit Buddy, Bluefruit Connect & Bluetility to find any BLE signals coming from the board (verdict: no trace!)
5. Tried a BLE smart dongle
6. Unpaired/forgot device from Android phone, attempt to re-pair with laptop
7. Attempted to connect the device via Apple’s Audio MIDI setup (https://support.apple.com/guide/audio-midi-setup/set-up-midi-devices-ams875bae1e0/mac)
8. Tried steps 1-7 with two additional MacBooks (2016 & 2022)

I know that the BLE pairing functionality of the board is working, since it consistently pairs with an Android phone and a PC laptop; I just cannot figure out why it won't pair with my MacBook. I want to resolve this issue and ensure that the board can be used across platforms.

Are there any other troubleshooting actions I should try?

# Answer
> 0 votes
Have you tried Bluefruit Connect from Adafruit? It is available in the Apple store. Don't quote me on this, but I read a long time ago, that Mac requires encryption for a BLE device to be recognized, whereas, most of the out-of-the-box Adafruit example doesn't use it.

I had a similar issue. And I used Bluefruit Connect to connect my device to my Mac.

---
Tags: bluetooth, adafruit, ble, feather
---


# Question
Title: Making a servo work for just once after a specific time period without hindering the sensors that are reading the data in a loop
I am making a cansat which will be launched on a sugar rocket. The cansat's Arduino nano will be operating sensors which will read the data and store it in an sd card and also a servo to deploy the parachute.

The problem is that I am not able to make code where I want all the sensors to be logging data in the sd card in a loop and a mini servo should perform a sweep angle of 90 degrees after 2 minutes of power supply to the Arduino.

I have made the code for sensors inputting data into sd card but the servo part is confusing me due to no possibility of putting servo code in void setup as the setup will first do the servo sweep after 2 minutes and then record data, neither can I put it in the loop as that also records the data after 2 minutes and I tried to put that into a new function but that's also not working.

Please give me a solution for this. The code that I have made is below : ( just for sensors logging data in sd card )

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <DHT.h>
#include <SD.h>

#define DHTPIN 10
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

const int MQ2 = A0;

File dataFile;

void setup() {
  Serial.begin(9600);
  dht.begin();
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  if (!SD.begin(4)) {
    Serial.println("SD card initialization failed!");
    while (1) {}
  }
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println("Temperature, Humidity, Pressure, Gas");
    dataFile.close();
  } else {
    Serial.println("Error opening data file!");
  }
}

void loop() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  sensors_event_t event;
  bmp.getEvent(&event);
  float pressure = event.pressure;
  float gas = analogRead(MQ2);
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.print(temperature);
    dataFile.print(",");
    dataFile.print(humidity);
    dataFile.print(",");
    dataFile.print(pressure);
    dataFile.print(",");
    dataFile.println(gas);
    dataFile.close();
  } else {
    Serial.println("Error opening data file!");
  }
  delay(1000);
}

```

# Answer
I assumed you would want to collect the data after you opened the parachute. And as Delta\_G suggested, you would want to open the parachute as fast as possible and not gradually.

I also assumed you want to collect the data every second, based on your provided code, because it has a 1000-millisecond delay. With all that here is a code that might work: (I haven't tested it, but it should give an idea of how to get going)

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <DHT.h>
#include <SD.h>

#define DHTPIN 10
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

const int MQ2 = A0;
const long parachute_timeout_ms = 2 * 60 * 1000;   // Open parachute after two minutes.
bool parachute_opened = false;

const long data_collection_interval_ms = 1 * 1000; // Collect data every second.
bool start_collecting_data = false;
unsigned long previous_ms = 0;

File dataFile;

void setup()
{
  Serial.begin(9600);
  dht.begin();
  if (!bmp.begin())
  {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  if (!SD.begin(4))
  {
    Serial.println("SD card initialization failed!");
    while (1) {}
  }
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile)
  {
    dataFile.println("Temperature, Humidity, Pressure, Gas");
    dataFile.close();
  }
  else
  {
    Serial.println("Error opening data file!");
  }

  previous_ms = millis();
}

void loop()
{

  // Check to see if it's time to open the parachute.
  unsigned long current_ms = millis();

  if ((parachute_opened == false) && (current_ms - previous_ms >= parachute_timeout_ms))
  {
    // Your code to open the parachute
    // ... ... ..

    // Make sure this code doesn't execute again.
    parachute_opened = true;

    //...and then set the flag that tells the other part of the code
    // that it should start collecting data.
    start_collecting_data = true;
  }

  if ((start_collecting_data) && (current_ms - previous_ms >= parachute_timeout_ms))
  {
    collect_data();
    previous_ms = current_ms;
  }
}

void collect_data()
{
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  sensors_event_t event;
  bmp.getEvent(&event);
  float pressure = event.pressure;
  float gas = analogRead(MQ2);
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile)
  {
    dataFile.print(temperature);
    dataFile.print(",");
    dataFile.print(humidity);
    dataFile.print(",");
    dataFile.print(pressure);
    dataFile.print(",");
    dataFile.println(gas);
    dataFile.close();
  }
  else
  {
    Serial.println("Error opening data file!");
  }
}

```
> 1 votes

---
Tags: arduino-nano, servo
---


title: Pass typedef to a function

text:
# Question
Title: Pass typedef to a function
I'm working with a ESP32S3 that will manage 2 I2S ports, so for the cleanness of my code and also because i'll work multiple I2S installations - deinstallations, i want to move all the functions to and ".cpp .h" file.

something like this

1. I2S\_functions.h

```
#ifndef I2S_FUNCTIONS_H
#define I2S_FUNCTIONS_H
#include <Arduino.h>
#include <driver/i2s.h>

void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,int buf_count, int buf_len, bool apll);

#endif

```
2. I2S\_functions.cpp

```
#include "I2S_functions.h"

void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,
i2s_bits_per_sample_t I2S_SAMPLE_BITS,i2s_channel_fmt_t I2S_CHANNEL,i2s_comm_format_t I2S_COMM_FORMAT_STAND_I2S,
int buf_count, int buf_len, bool apll)
{
  const i2s_config_t i2s_config =
  {

    .mode = I2S_MODE,
    //.mode = (i2s_mode_t)(I2S_MODE),
    .sample_rate = I2S_SAMPLE_RATE,

    .bits_per_sample = I2S_SAMPLE_BITS,
    .channel_format = I2S_CHANNEL,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),

    .intr_alloc_flags = 0, // default interrupt priority
    .dma_buf_count = buf_count,//cambiado de 8 a 64
    .dma_buf_len = buf_len,
    .use_apll = apll
  };

  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
}

```
3. main.ino

```
#include "I2S_functions.h"

// I2S config //////
#include <driver/i2s.h>

#define I2S_PORT I2S_NUM_0
//#define I2S_SAMPLE_RATE  (44100)
float I2S_SAMPLE_RATE=44100;
int I2S_SAMPLE_BITS=32;
//#define I2S_SAMPLE_BITS  (32)
#define bufferLen 1024
#define I2S_READ_LEN (16*1024)

void setup ()
{
  i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
I2S_BITS_PER_SAMPLE_32BIT,I2S_CHANNEL_FMT_ONLY_LEFT,I2S_COMM_FORMAT_STAND_I2S,8,bufferLen,false);

}

```

But when i compile this, i got errors passing the second argument which is "I2S\_MODE\_MASTER|I2S\_MODE\_RX,I2S\_SAMPLE\_RATE"

a copy from the error:

```
C:\Users\.ino: In function 'void setup()':
test_10seg_V2:52:39: error: invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]
   i2s_install(I2S_PORT,I2S_MODE_MASTER|I2S_MODE_RX,I2S_SAMPLE_RATE,
                        ~~~~~~~~~~~~~~~^~~~~~~~~~~~
In file included from C:\Users\.ino:2:
C:\Users\I2S_functions.h:6:50: note:   initializing argument 2 of 'void i2s_install(i2s_port_t, i2s_mode_t, float, i2s_bits_per_sample_t, i2s_channel_fmt_t, i2s_comm_format_t, int, int, bool)'
 void i2s_install(i2s_port_t I2S_PORT, i2s_mode_t I2S_MODE, float I2S_SAMPLE_RATE,

exit status 1
invalid conversion from 'int' to 'i2s_mode_t' [-fpermissive]

```

**Essentially i have 2 questions**. While i looked in the github from the esp32 i found off that there is some typedef of the I2S config (https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/esp32/include/hal/include/hal/i2s\_types.h). I've never worked with this type of structs before so i am guessing how should i use it and specially how should i pass this type of variables to a function.

```
typedef enum {
    I2S_BITS_PER_SAMPLE_8BIT    = 8,            /*!< data bit-width: 8 */
    I2S_BITS_PER_SAMPLE_16BIT   = 16,           /*!< data bit-width: 16 */
    I2S_BITS_PER_SAMPLE_24BIT   = 24,           /*!< data bit-width: 24 */
    I2S_BITS_PER_SAMPLE_32BIT   = 32,           /*!< data bit-width: 32 */
} i2s_bits_per_sample_t;

/**
 * @brief I2S bit width per chan.
 *
 */
typedef enum {
    I2S_BITS_PER_CHAN_DEFAULT        = (0),      /*!< channel bit-width equals to data bit-width */
    I2S_BITS_PER_CHAN_8BIT           = (8),      /*!< channel bit-width: 8 */
    I2S_BITS_PER_CHAN_16BIT          = (16),     /*!< channel bit-width: 16 */
    I2S_BITS_PER_CHAN_24BIT          = (24),     /*!< channel bit-width: 24 */
    I2S_BITS_PER_CHAN_32BIT          = (32),     /*!< channel bit-width: 32 */
} i2s_bits_per_chan_t;

```

my questions are

**1.-** I would like to understand how this structs works. I want to clean my code the most that i could, and that mean passing a lot of functions out of the main file. So any resource is well welcome to improve my coding skill.

**2.-** Why the code fails passing this 2 variables "I2S\_MODE\_MASTER|I2S\_MODE\_RX" ?. Is there any special way of passing this variables when are 2 options at once?.

Thanks for your replies!

# Answer
Answer to Question 1: The `typedef` code you posted is `enum` and not `struct`. Look up C++ Enumeration and you will find lots of good tutorials. Here is one video.

Answer to Question 2: You need to typecast the argument for your function to accept it as `i2s_mode_t`.

```
i2s_install(I2S_PORT, (i2s_mode_t)(I2S_MODE_MASTER|I2S_MODE_RX), ... ... ...);

```
> 2 votes

---
Tags: esp32
---


# Question
Title: Reading Multiple RFID tags / Reading and ignoring/holding the tag
I'm currently doing a project where ideally I will have multiple objects with RFID tags on them that are placed on top of a Adafruit PN532 RFID Shield connected to a Arduino Uno Wifi Rev 2. The idea is that once a button is pressed the RFID reader will read a Mifare tag then "ignore" it then reads the next tag until all are read. How can I acheive this?

I have read some about Anti-collision protocols and the limitations of RFID but was also wondering if it might be possible to read a tag then hold or ignore that tag until it leaves the range of the RFID shield?

I've also read a user on the Adafruit forums had some luck by altering the library that is used, I'll link it for reference, but I've tried the same method but had no luck myself. Adafruit-PN532 Library

I'm new to Arduino so I apologise if I've messed anything out.

Thanks for any help!

# Answer
> 1 votes
You probably want to use UHF RFID for this. The Adafruit PN532 is only capable of reading max 2 tags at a time in an alternating fashion. This is confirmed by the board's designer in the Adafruit forums.

---
Tags: adafruit, rfid, arduino-uno-wifi
---


# Question
Title: Improving moving mouse loop to optimize speed
Code:

```
#include <Mouse.h>
#include <hiduniversal.h>
#include "hidmouserptparser.h"
#include <USBController.h>

USBController controller;
USB Usb;
HIDUniversal Hid(&Usb);
HIDMouseReportParser Mou(nullptr);
String x;
String y;
boolean isX;
int recv;

void setup() {
    Mouse.begin();
    Usb.Init();
    delay(200);

    if (!Hid.SetReportParser(0, &Mou))
        ErrorMessage<uint8_t > (PSTR("SetReportParser"), 1);
}

void loop() {
    Usb.Task();
    recv = controller.read();
    if ((recv-48)==29){ // recv = M
        // , : -4
        // /n : -38
        x="";
        y="";
        isX = true;
        while (true){
            recv = controller.read();
            if (recv!=0 && recv!=2){ // filter out 0 and 2
                if ((recv-48)==-38){ // -38 is a line break
                    break;
                }
                else if ((recv-48)==-4){ // switch to y value after comma
                    isX = false;
                    continue;
                }

                if (isX){
                    x+=String(recv-48);
                }
                else{
                    y+=String(recv-48);
                }
            }
        }
        Mouse.move(x.toInt(),y.toInt());
    }
}

void onButtonDown(uint16_t buttonId) {
    Mouse.press(buttonId);
}

void onButtonUp(uint16_t buttonId) {
    Mouse.release(buttonId);
}

void onMouseMove(int8_t xMovement, int8_t yMovement, int8_t scrollValue) {
    Mouse.move(xMovement, yMovement, scrollValue);
}

```

I'm using an Arduino leonardo with a usb host shield. My goal is to move my cursor to a specific location based on the data read in. Format of the data read in is "MX,Y" and a line break.

In the main loop,

* I read the data and subtract 48 because that's the real number.
* Then I check if the first character is M because that is where the beginning of my data starts.
* Then I filter out 0 and 2 because those values are useless to me and randomly appear.
* I loop to add the integer values as strings to x then switch to y after the comma appears.
* Then I convert the `string` values to `int` and `mouse.move`.

The problem is the mouse movement is slow and jittery and I think it's because the `toInt` and `String()` methods are slowing it down. How could I improve my algorithm?

# Answer
> 1 votes
This:

> ```
> while (true){
>     recv = controller.read();
>     // ...
> }
>
> ```

is a *blocking* loop. This means that, while executing this part of the code, the Arduino is stuck for an indeterminate amount of time, and can do nothing else. Specifically, it cannot run `Usb.Task()`, which could well be the cause of the jittery behavior you are experiencing.

I would recommend reading the incoming data in a *non blocking* fashion: each time there is a byte to be read, read it and move on. Do not wait for the subsequent bytes. Only when you find an end of line would you handle the data you received. For example:

```
// Parse and execute a command received through USB.
executeCommand(String &command) {
    // Implementation left as an exercise to the reader.
}

// Whether we are presently receiving characters from a command.
bool receivingCommand = false;

// Received command, may be incomplete.
String command;

void loop() {
    Usb.Task();
    if (controller.available()) {
        char c = controller.read();
        if (!receivingCommand && c == 'M') {  // start of command
            receivingCommand = true;
        } else if (receivingCommand && c == '\n') {  // end of command
            executeCommand(command);
            command = "";
            receivingCommand = false;
        } else if (receivingCommand) {  // body of command
            command += c;  // buffer the received character
        }
    }
}

```

A better approach would be to avoid the `String` class, which is not friendly to your Arduino's memory, and use a plain C string, as explained in Reading Serial on the Arduino. This, however, is likely unrelated to your jitter issue.

---
Tags: programming, arduino-leonardo
---


# Question
Title: Where to define web server callback functions so they can access server object? (ESP8266WebServer library)
I want my ESP8266-based device to create an accesspoint that allows the user to input their home ssid and password. There is a device object that holds most of the data defined elsewhere.

I'm trying to use the ESP8266WebServer library. It requires me to define parameterless callback functions. Where should I declare and define these callback functions so that they can access the server object? In all the example code, the server object is global. I'd want to avoid that, and I'd also like to avoid having a server object as a permanent Device class member.

How should I go about this? It is not allowed to define the callback functions inside Device::getWifiCredentials, and if I declare them outside then server isn't in scope.

```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {

    ESP8266WebServer server(80);
    server.begin();

    // define callbacks
    server.on("/", handleRoot); // initial page

    server.on("/ssid", handleCredentials); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

    while( WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(500);
    }

    return ACTION_SUCCESSFUL;

}

// **Where can these functions be defined to allow them to access the server object?**

void handleRoot() {
};

void handleCredentials() {

    String ssid;
    String pw;

    if( server.hasArg() ){
        ssid = server.arg("ssid");
        pw = server.arg("pw");
    }
};

```

# Answer
> 2 votes
put your server declaraition outside the constructor and call a class callback :

```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {
server.begin();

    // define callbacks
    server.on("/", std::bind(&Device::handleRoot, this); // initial page

    server.on("/ssid", std::bind(&Device::handleCredentials, this); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

    while( WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(500);
    }

    return ACTION_SUCCESSFUL;
}

```

---
Tags: esp8266, c++, web-server, espressif
---


# Question
Title: Arduino unable to read 0x41 and 0x42 (reads others just fine (ICT bill acceptor)
Here is my issue:

My code successfully recognizes and accepts $1 (0x40) and $20 bills (0x43), but it fails to recognize, display, process, anything for the $5 bill (0x41), and $10 bills (0x42). Also, when I say "Arduino", I mean TTGO btw...

I have verified that the bill acceptor is indeed sending the correct value (0x41) for the $5, and $10 (0x42) bills using an external monitoring tool like Docklight, and I used an oscilloscope too! All signals from all bill types were near identical and valid. However, the Arduino code does not seem to receive those two values (and ONLY those two values) at all... Meanwhile, it will display every other little thing there is... I have my code setup where it displays all incoming bytes, be it B.A. (bill acceptor) idle signals, rejection signals, everything, but it goes 100% blank, MIA, for 0x41 and 0x42... WHY?!?! So frick'n random...

===================================================

**Just so you all know, this is how the bill acceptor (B.A.) works:**

1. Insert a bill into BA
2. BA sends the corresponding HEX value (ex. 0x40) of the bill to my Arduino (Using RS232 cables and an RS232 to TTL converter (the converters are confirmed to be 100% operational BTW))
3. Once the Arduino "sees" the HEX value for a bill of N value, it will then send 0x02 to the BA to accept the bill.
4. If 0x02 is NOT sent to the BA within 5 seconds, then it will reject the bill and spit it back out the front.
5. Code then adds that value to "total count"

OFC, my code is setup where the only way an accept (0x02) signal is sent is IF 0x4N is received... So, the fact that 0x41 and 0x42 disappear into thin air means 0x02 is never sent so those two values are always rejected... Very, very, simple stuff, so the fact that it consistently is unable to ONLY NOT read 0x41 and 0x42 while clearly displaying all other sent HEX values is causing me unlimited headaches and conniptions... Programming... YAY! -\_-

So, anyone... please, do you know what's going on? The signal is 100% being generated, and my code, below, is setup to display all incoming bytes, but it acts like 0x41 and 0x42 do not exist at all! Nothing. Nada. Zilch. WTF? It literally handles everything I can throw at it... except 0x41 and 0x42!!! FUUUUUUUUUUUU!!! So mad...

**HERE IS THE ICT RS232 PROTOCL FOR MY BILL ACCEPTOR - http://tdmegalit.ru/upload/iblock/401/ict\_protocol.pdf**

**ALSO, I HAVE ALL DIP SWITCHES CORRECTLY SET, POWER SUPPLY IS PERFECT, ALL WIRES ARE TESTED AND PERFECT, RS232 TO TTL CONVERTERS ARE PERFECT. I GUESS IT IS SOFTWARE SERIAL, OR THE TTGO**

So with all that said, **below is my code**. It is a part of a much great whole of a program, so to remove the possibilities of the rest of the code causing the error, I reduced it to what you see below, but the problem persist... bruh

Also, I have included the **Serial Monitor LOG**. The LOG below shows startup, and then a 1, 5, 10, and 20 dollar bill being inserted...

**SERIAL MONITOR LOG:**

```
PLZ NOTE, I ADDED SPACES TO SHOW WHATS GOING ON...
====================================================================

... Received: 0x80       //IDLE SIGNALS (BA POWERED ON BEFORE "SETUP" SENT)
... Received: 0x8F
... Received: 0x80
... Received: 0x8F
... Received: 0x80
... Received: 0x8F

SETUP - ...Sent: STX     //SETUP TO INITALIZE BA
SETUP - ...Sent: DLE
SETUP - ...Sent: ETX
=======================
                         //INSERTED $1 (0x40) SUCCESS!!!
... Received: 0x40
$1 accepted
... Sent: 0x02
... Received: 0x10
                         //INSERTED $5 and 5 seconds later 0x29>>0x29>>0x2F = Rejection
... Received: 0x29
Bill rejected
... Received: 0x29
Bill rejected
... Received: 0x2F
                         //INSERTED $10 and 5 seconds later 0x29>>0x29>>0x2F = Rejection
... Received: 0x29
Bill rejected
... Received: 0x29
Bill rejected
... Received: 0x2F
                         //INSERTED $20 (0x43) SUCCESS!!!
... Received: 0x43
$20 accepted
... Sent: 0x02
... Received: 0x10

```

**BILL ACCEPTOR CODE:**

```
#include <SoftwareSerial.h>

SoftwareSerial BA(32, 33);  // RX, TX

int billCounter = 0;

void setup() {
  Serial.begin(9600);
  BA.begin(9600);
  delay(3000); //WAIT BC TRESH

  BA.write(0x02); // Send the initialization command (STX)
  Serial.println("SETUP - ...Sent: STX");
  BA.write(0x10); // Send the command to enable the bill acceptor
  Serial.println("SETUP - ...Sent: DLE");
  BA.write(0x03); // Send the end of text character (ETX)
  Serial.println("SETUP - ...Sent: ETX");
  Serial.println("=======================");
}

void loop() {
  if (BA.available()) {
    byte receivedByte = BA.read();
    Serial.print("... Received: 0x");
    Serial.println(receivedByte, HEX);

    if (receivedByte == 0x29) {
      delay(200);
      Serial.println("Bill rejected");
      // Handle bill rejection here (e.g., display message or perform necessary actions)

    } else if (receivedByte == 0x40) {
      delay(200);
      Serial.println("$1 accepted");
      BA.write(0x02); // Send the HEX value 0x02 to accept the bill
      Serial.println("... Sent: 0x02");

      // Increment the counter by $1
      billCounter += 1;

    } else if (receivedByte == 0x41) {
      delay(200);
      Serial.println("$5 accepted");
      BA.write(0x02); // Send the HEX value 0x02 to accept the bill
      Serial.println("... Sent: 0x02");

      // Increment the counter by $5
      billCounter += 5;

    } else if (receivedByte == 0x42) {
      delay(200);
      Serial.println("$10 accepted");
      BA.write(0x02); // Send the HEX value 0x02 to accept the bill
      Serial.println("... Sent: 0x02");

      // Increment the counter by $10
      billCounter += 10;

    } else if (receivedByte == 0x43) {
      delay(200);
      Serial.println("$20 accepted");
      BA.write(0x02); // Send the HEX value 0x02 to accept the bill
      Serial.println("... Sent: 0x02");

      // Increment the counter by $20
      billCounter += 20;

    } else if (receivedByte == 0x44) {
      delay(200);
      Serial.println("$50 accepted");
      BA.write(0x02); // Send the HEX value 0x02 to accept the bill
      Serial.println("... Sent: 0x02");

      // Increment the counter by $50
      billCounter += 50;

    } else if (receivedByte == 0x45) {
      delay(200);
      Serial.println("$100 accepted");
      BA.write(0x02); // Send the HEX value 0x02 to accept the bill
      Serial.println("... Sent: 0x02");

      // Increment the counter by $100
      billCounter += 100;
    }
  }
}

```

# Answer
> 3 votes
> The default for Arduino Serial is 8 data bits, no parity, one stop bit. The first page of your linked documents says: Start bit 1, Data bit 8, Parity bit Even, Stop bit 1. The mismatched parity parameter could explain a partial failure of this communication. The documentation for the Serial begin() method describes the various configuration options.
>
> However, see also this thread: https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535 It appears that the various software serial libraries do not support EVEN parity settings. Use a hardware serial port on your TTGO Arduino instead. This may mean using SoftwareSerial for the debug printing (maybe with a USB/UART adapter) and dedicating the hardware serial port to your bank note reader.

Thank you 6v6gt! Using HardwareSerial was the answer and setting the parity bit to EVEN was the answer too :D Here is what I did to fix it if anyone ever needs to see this answer in the future...

**Also note, here is the logic:**

The default for hardware serial is SERIAL\_8N1, but I needed to use SERIAL\_8E1 for the even parity because:

SERIAL\_8N1 means "8" bits, "N"o parity, and "1" stop bit (hence 8N1)

SERIAL\_8E1 means "8" bits, "E"ven parity, and "1" stop bit (hence 8E1)

**Here is the chart I used to get the protocol format I needed:**

```
/* Baud-rates available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200, 256000, 512000, 962100
 *
 *  Protocols available:
 * SERIAL_5N1   5-bit No parity 1 stop bit
 * SERIAL_6N1   6-bit No parity 1 stop bit
 * SERIAL_7N1   7-bit No parity 1 stop bit
 * SERIAL_8N1 (the default) 8-bit No parity 1 stop bit
 * SERIAL_5N2   5-bit No parity 2 stop bits
 * SERIAL_6N2   6-bit No parity 2 stop bits
 * SERIAL_7N2   7-bit No parity 2 stop bits
 * SERIAL_8N2   8-bit No parity 2 stop bits
 * SERIAL_5E1   5-bit Even parity 1 stop bit
 * SERIAL_6E1   6-bit Even parity 1 stop bit
 * SERIAL_7E1   7-bit Even parity 1 stop bit
 * SERIAL_8E1   8-bit Even parity 1 stop bit
 * SERIAL_5E2   5-bit Even parity 2 stop bit
 * SERIAL_6E2   6-bit Even parity 2 stop bit
 * SERIAL_7E2   7-bit Even parity 2 stop bit
 * SERIAL_8E2   8-bit Even parity 2 stop bit
 * SERIAL_5O1   5-bit Odd  parity 1 stop bit
 * SERIAL_6O1   6-bit Odd  parity 1 stop bit
 * SERIAL_7O1   7-bit Odd  parity 1 stop bit
 * SERIAL_8O1   8-bit Odd  parity 1 stop bit
 * SERIAL_5O2   5-bit Odd  parity 2 stop bit
 * SERIAL_6O2   6-bit Odd  parity 2 stop bit
 * SERIAL_7O2   7-bit Odd  parity 2 stop bit
 * SERIAL_

```

**CODE SOLUTION:**

```
#include <HardwareSerial.h>

HardwareSerial BA(1);  // Use Hardware Serial on TTGO

void setup() {
  Serial.begin(9600);
  BA.begin(9600, SERIAL_8E1, 32, 33);  // (Baud rate, Protocol, RX, TX)
  ...  //rest of my code

```

# Answer
> 2 votes
The default for Arduino Serial is `8 data bits, no parity, one stop bit`. The first page of your linked documents says: `Start bit 1, Data bit 8, Parity bit Even, Stop bit 1`. The mismatched parity parameter could explain a partial failure of this communication. The documentation for the Serial begin() method describes the various configuration options.

However, see also this thread: https://forum.arduino.cc/t/altsoftserial-how-to-change-parity-solved/668535 It appears that the various software serial libraries do not support EVEN parity settings. Use a hardware serial port on your TTGO Arduino instead. This may mean using SoftwareSerial for the debug printing (maybe with a USB/UART adapter) and dedicating the hardware serial port to your bank note reader.

---
Tags: serial, softwareserial, rs232
---


# Question
Title: Copy Uno Analog Input Configuration To ESP32
I started a project using the arduino uno and as a challenge I'm attempting to make it work with the esp32 but I've run into a roadblock. I may not describe it in proper terms, but I noticed that the analog input signal on the esp32 functions *differently* from how analog input works on the uno. After some research I found that the esp32 has a default analog width of 12, instead of the default 10 on the uno. This got me wondering what other analog settings (reference voltage, pin attenuation, width, etc.) on the esp32 are different from the uno and how I might go about getting similar results on the esp32. I found this useful page detailing some functions to mess around with the adc channels but, other than `analogSetWidth()`, I haven't been able to figure out what they do. I tried messing around with the functions mentioned in the linked page, but I ultimately made things worse.

tl;dr What analog input settings (analog width, pin attenuation, etc.) on the esp32 are different from the uno?

# Answer
Per the advice of @6v6gt, I was able to find this resource and this resource that told me the following information about the ADC configuration for the Uno's MCU (aka ATmega328P):

* The analog width defaults to 10 bits (\** definitely the most important)
* The reference voltage is determined by the AVCC (power source) by default
* The ADC clock defaults to a divisor of 128 (assuming 13 ADC cycles per conversion)

Wasn't able to find anything useful about pin attenuation, though.
> 1 votes

---
Tags: arduino-uno, esp32, analogread
---


title: Rotary encoder weird values

text:
# Question
Title: Rotary encoder weird values
I am trying to understand this rotary encoder I have, but it makes no sense to me.

I am using this rotary encoder: https://www.amazon.com/gp/product/B07DM2YMT4/

CYT1100 aka CY110 aka EC11

I am using this wiring: https://i.stack.imgur.com/aMyR5.png

P2 is the "push button" and it gives continuity when pressed.

I am using a knock off arduino nano and this is my simple script:

```
#define PIN_CLK 2

void setup()
{
    Serial.begin(9600);
    pinMode(PIN_CLK, INPUT);
}

void loop()
{
    auto val = digitalRead(PIN_CLK);

    Serial.println("CLK:" + String(val));
}

```

Where PIN\_CLK is connected to A (DW) or B (CLK) in the diagram.

My expectation is that A and B should be either a constant HIGH or LOW depending on where the brushes are internally. Not switching to HIGH or LOW for a moment and then returning to what it was before.

When I check them with my multimeter, they are both always 5v (when its not making loose contact on the breadboard).

The serial plotter says its switching between HIGH and LOW repeated:

https://i.stack.imgur.com/6VC3z.png

Same with the Serial monitor:

https://i.stack.imgur.com/wAk0v.png

When I spin the encoder, it gives me gaps of LOW in the output like this:

https://i.stack.imgur.com/lOUmx.png

If I hold my index and thumb against P1 (5v) and A (CLK) while spinning the encoder. I get constant stream of HIGH with a LOW on every notch spin:

https://i.stack.imgur.com/CzUwV.png

Can someone explain this behavior and how this encoder is suppose to work?

Edit: I tried this schematic:

https://i.stack.imgur.com/Mlj1l.png

Whenever I turn the encoder. The LED blinks for a few milliseconds. Then turns off.

Is it suppose to stay solid depending on the 2 bit states?

Edit2: If I turn it extremely slowly. It turns the leds on in the order of left right or right left depending on the direction.

So the led diagram above works, but its weird to me.

# Answer
There are several problems happening here. Since your code only covers one input pin, I'm going to talk about input A. This pin is left floating! When you turn the dial, the brush connects A and/or B to G in your photo, or in other words, pins A/B to ground. But if A/B is not connected to ground, there is no other voltage state - it's just left floating. You need to have a logic LOW 0V and a logic HIGH (either 3.3V or 5V depending on your Arduino board) for the Arduino to be able to distinguish between the LOW and HIGH states. You can solve this by changing your code to:

```
pinMode(PIN_CLK, INPUT_PULLUP);

```

This way when the pin (A) is not connected to GND via (G), it is held at a logic HIGH state.

P1 & P2 are the for the button, so you can't ignore one of the pins. To wire that correctly using an input pullup, P1 needs to connect to GND. P2 needs to connect to an input pin with another `input_pullup`. When the button is unpressed, the state will default to HIGH. When it's pressed, it will be connected to GND and show as LOW.

You are most likely following the images online for wiring the encoders that **are already on a PCB**. That PCB has 3 pullup resistors on it. Regardless if you are using code to do it or hardware, the circuit needs to look like this. `input_pullup` on the Arduino will act just like resistors shown in the circuit.

Here is a great resource: https://lastminuteengineers.com/rotary-encoder-arduino-tutorial/
> 2 votes

# Answer
When encountering weird values from a rotary encoder, there are a few possible reasons and troubleshooting steps you can take:

**Mechanical issues:** Check if there is any physical damage or obstruction affecting the rotary encoder's movement. Ensure that it rotates smoothly without any unusual resistance or skips.

**Loose connections:** Verify the wiring connections between the rotary encoder and the device it is connected to. Ensure that the connections are secure and properly seated.

**Electrical noise:** Electrical noise or interference can sometimes cause erratic readings. Try using shielded cables for the connections and consider adding capacitors or ferrite beads to filter out noise.

**Incorrect configuration:** Review the setup and configuration of the rotary encoder in your code or software. Make sure that you have selected the correct type of encoder (incremental or absolute) and that the signal processing is correctly implemented.

**Debouncing:** If you are using an incremental rotary encoder, it may produce multiple pulses or bouncing signals when rotating. Implementing debouncing techniques in your code can help filter out these erroneous readings.

**Resolution and speed settings:** Check if the resolution and speed settings in your code or software match the specifications of your rotary encoder. Incorrect settings can lead to unexpected values.

**Compatibility issues:** Ensure that the rotary encoder you are using is compatible with the device or system you are connecting it to. Check the specifications and requirements of both the encoder and the device to ensure compatibility.

If you have gone through these troubleshooting steps and are still experiencing weird values from your rotary encoder, it might be worth considering a replacement or consulting the manufacturer's support for further assistance.
> 1 votes

---
Tags: arduino-nano, digital, rotary-encoder, breadboard
---


# Question
Title: Why does a simple LED Blink not work using mbed.h PWM and Arduino Nano BLE?
I have set up a very simple test program to blink an builtin LED using PWM. Following the mbed example and setting the period to 4 seconds (0.25 Hz) and duty cycle to 0.5, the expected behaviour is for the LED to be on for 2 seconds and off for 2 seconds. However, the actual behaviour is that the LED flashes extremely quickly (almost imperceptable to the eye).

```
#include "mbed.h"

mbed::PwmOut ledPin = mbed::PwmOut(P0_13); //builtin led pin

void setup() {
  ledPin.period(4.0f);
  ledPin.write(0.0f);
}

void loop() {
  // put your main code here, to run repeatedly:
  ledPin.write(0.5f);
}

```

I have tried adding `delay()` and `wait_ns()` with different times in the main loop, tried having the main loop empty and setting the duty cycle in the `setup()` function as well as changing the period to larger numbers just in case it was in milliseconds all to no avail. Not quite sure what I'm missing from this extremely simple example.

# Answer
The example you linked has an infinite, but empty, loop - `while(1);` \- following setting up the PWM.

Your loop repeatedly executes `ledpin.out(0.5f);`

I didn't find the .out() member function to know what it does but my first thought would be comment out the contents of your loop() function and let it also run as an empty infinite loop. Then I'd look at the .out member function and find out what its action is. Output to a pin is usually a boolean. If that is the case with .out(), then 0.5f will be converted to an integer 0 which is identical to boolean 'false', and this loop would repeatedly turn off the LED, and at around a megahertz.
> 0 votes

---
Tags: arduino-nano, led, pwm, arduino-nano-ble
---


# Question
Title: Strtok operations on Arduino Zero seem to fail in runtime
I am trying to test functionality of strtok() on a new piece of hardware, as I ran out of memory to develop on my Nano. This is a basic example from the internet involving tokenizing the string and reporting the tokenized entries via SerialUSB. I'm running a Rocketscream V3 (Arduino Zero ATSAMD21G18A).

```
#include <string.h>

void setup() {
  char *token;
  char *mystring = "apples,pears,bananas";

  SerialUSB.begin(9600);
  while (!SerialUSB) { }

  SerialUSB.print("Serial established");

  token = strtok(mystring, ",");

  while (token != NULL) {
    SerialUSB.println(token);
    token=strtok(NULL, ",");
  }
}

```

The code works as expected on my Nano (with Serial instead of SerialUSB), but while it does compile for the Arduino Zero, the Zero never makes it past printing "Serial established". I have confirmed this by including code (serial print, LED flashing) past the tokenization parts, and these are never executed. The loop() function is never reached, it seems to halt at "token = strtok(mystring, ",");".

I cannot think of a simpler possible way to test strtok(), but it's just not working. Any help would be appreciated.

# Answer
> 1 votes
`strtok` works by modifying the source string. Your test string points to a constant string.

```
  char *mystring = "apples,pears,bananas";

```

This particular platform may put that into read-only memory. Try instead as your test string:

```
  char mystring [] = "apples,pears,bananas";

```

I don't have a Zero to test it on, but in any case using `strtok` on a const string is ~~not recommended~~ forbidden.

---

If you turn warnings on for the compiler (File -\> Preferences) you see this:

```
 In function 'void setup()':
 warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   char *mystring = "apples,pears,bananas";

```

If you are doing something "forbidden" then don't expect good results.

---
Tags: arduino-zero
---


# Question
Title: Barebones AVR - Connecting RESET pin to Vcc
I want to build my first barebones AVR circuit.

I plan on NOT having a RESET button. For this reason, is it valid if I connect the ATMEGA's `RESET` pin to `Vcc` directly?

What I mean by this, is that in this scenario, I will not be using a pull-down resistor as well. Just straight to `Vcc`.

EDIT: This is a part of the schematic:

# Answer
According to the datasheet linked to by hcheung in their comment, datasheet, on page 41 it states "Figure 10-2. MCU Start-up, RESET Tied to VCC".

I believe it would be OK to tie the pin directly to Vcc.

I also believe the graphical data presented in "Figure 10-2" could be miss-leading if the reader didn't know what Vcc meant, and also because there is no horizontal axis to specify that they are talking about elapsed time, not voltage change.

**EDIT**

Regarding your comment "Thanks, but now I am not sure if this setup will work with Sparkfun's Pocket AVR Programmer.".

Looking at page 40 of the datasheet, a internal pull-up resistor is built into the MCU.

You could leave the reset pin not connected and see if it still works as expected. Perhaps a high impedance DVOM would show Vcc on that pin. Some people say leave it disconnected if there are no issues from EMI. EEV Blog - Is it ok to leave atmega328p reset pin floating?

The data sheet also mentions the power on reset timeout which may allow you to program the MCU with your programmer once it first starts, (assuming you have tied the reset pin to Vcc and you leave the reset pin disconnected on your programmer).

Another option would be to program the MCU, then connect the reset pin to Vcc through a couple of solder pads you can bridge with a blob of solder.

Once the reset pin is tied to Vcc, using a programmer connected to that pin will likely result in the magic smoke being released from the MCU, your programmer, or both.
> 2 votes

# Answer
> I updated the question with a pic. I am using ATMega328. I intend to program the chip using Sparkfun's AVR Programmer.

Then don't tie /RESET to VCC. The programming won't work. What are you doing? Trying to save one resistor? If you have J2 as a programming interface, then /RESET needs to be able to be pulled low to start the programming sequence. Either remove J2 altogether and program the chip in advance of going on the board, or use the pull-up resistor. Don't tie it to VCC.
> 2 votes

---
Tags: atmega328, pins, avr, reset, pull-up
---


# Question
Title: Display images on Arduino LCD screen from PC
I am new to arduino and I am wondering if it is possible to store image data on my computer and send it to my arduino over the USB cable (which is also used for power) to display on a TFT LCD display I have hooked up. All the tutorials I see involve using an SD card to preload the image data on there beforehand.

Still, my display doesn't have an sd card slot, nor is it practical for my application as the images I want to display will be determined during runtime. I have sent small pieces of data over the COM port to my arduino from my PC but I don't know how I could do it with potentially large image data. The arduino will be plugged into my computer 24/7. If this is possible could I get a little guidance on where to start? Thank you

# Answer
> 3 votes
Since you don't give a clue about the TFT you have in mind, I'll try to describe the process using the following assumptions about the TFT that have to be true for the rest to work:

* one full frame of pixel data for the TFT used would not fit into the Arduinos RAM, but one line of that frame will,
* the pixel data can be sent line by line to the TFT without a need to start the next line inside a certain timeframe (i.e. you could, in theory, just tell the TFT to update line 42 out of order, as an example),
* the TFT has its own way of remembering its display data (i.e. does not need a continuous refresh 60 times per second).

In this scenario, your image processing pipeline looks like this:

* A program running on your PC decompresses (and possibly resizes) the image file in order to get access to the raw pixel data as it would be displayed on the TFT. This means that this program needs to know the resolution and "data feeding order" of your TFT.
* This process then takes one line of the raw pixel data and converts it into a data package to be sent over the serial port. You will need to devise a communication protocol here that your Arduino sketch can work with. The easiest, but not most efficient, way would be to convert it into Base64, because libraries for that exist in practically every language and platform and you are then able to use text-based delimiters like a line break to mark the end of a pixel data line. (Sending binary data is more efficient, but harder and more prone to sychronization errors, because you have no in-band signalling of "end of data line".)
* Your Arduino sketch reads that data package (if Base64-encoded: by using `Serial.read` until you encounter a line break) and converts it back to raw pixel data, in whatever format your TFT (or library for that TFT) needs the data (it might require the color format in e.g. GRB instead of RGB).
* This raw pixel data line is then sent to the TFT.

You will have to determine the baud rate you can send over your serial link (determined by maximum baud rates of both PC and Arduino, and sometimes the cable quality in between). Keep in mind that a serial connection is slow; you probably will be able to watch the image rendering on the TFT line by line.

You may be able to make this more efficient by employing something like RLE (Run-Length Encoding) on the pixel data sent over the serial line, but that would be another iteration of your protocol.

# Answer
> 1 votes
You could "stream" the data from the PC to the LCD, which means you wouldn't need to store it (or maybe store a line or so).

Without knowing which Arduino and which LCD it is hard to give more advice than that.

# Answer
> 0 votes
There are so many different LCDs that with out specifying a specific LCD only very general answers can be provided that may be of limited value.

* Just about all Arduinos can handle an Alpha Numeric LCDs. But these have very limited graphics, if any.

* Most can handle sending geometric shapes and alpha numeric to (smart) Serial Port Color LCDs. Only some Arduinos will be able to handle sending arbitrary images (like a photograph) to (smart) Serial Port Color LCDs.

And few will be able to handle sending data to a common TTL or LVDS Color LCDs.

---
Tags: lcd, communication, display
---


# Question
Title: Reading from DHT22 with Arduino, powered by external source
I have the following situation. When I power my DHT22 with the 3.3V from the Arduino UNO (and Ground it there), then I can read the data perfectly fine using the DHT library from Adafruit.

However, when I connect the DHT22 to my own external power supply (and respective ground), it fails. The reason for using this external power supply is so I can hook it up to a ESP8266 later.

The power supply I build uses a 5V adapter, then an LD33V converter and (just for experimentation) an 100nF capacitor to reduce any noise on the line. I measured this external power supply and it indeed gives off 3.3V after the LD33V. I check the datasheet of the LD33V and it should be able to 'give' 5mA, whereas the DHT22 needs less than 1mA for operation.

I don't know where to look at this moment. Can someone point me in the right direction? Much appreciated :)

Cheers

# Answer
> 1 votes
Have you connected the external power supply ground to the Arduino's ground? If not, one is "floating" with respect to the other. But they need to have the same reference - the ground sides of their power supplies.

---
Tags: arduino-uno, dht22
---


# Question
Title: Arduino Uno R3 assembly code to push a button and turn on a LED
I've been trying this for days without success...

I need to turn on a LED on portb when a button in portd is pushed. Cabling works, I've tested it with Arduino IDE and it works like a charm.

This is what I got so far:

```
.global main
.equ LED, PB5
.equ BUTTON, PD3
main:
   ldi r22,0xff                    ;all bits in portb are output
   out _SFR_IO_ADDR(DDRB),r22
   ldi r21,0x00                    ;all bits in portd are input
   out _SFR_IO_ADDR(DDRD),r21
   ldi r19, 0b00000000             ;unpushed button
   ldi r18, 0b00100000             ;pushed button
   eor r16, r16
loop:
   out BUTTON, r16                 ;read button to r16
   cp r16, r18                     ;compare r16 with r19 (button on)
   cbi _SFR_IO_ADDR(PORTB),LED
   breq loop                       ;go back to loop
   sbi _SFR_IO_ADDR(PORTB),LED     ;if z=1, turn led on turn led on
   rjmp loop                       ;back to loop

```

It is much easier with `sbis`, if I got it right...

```
#include <avr/io.h>
.equ LED, PB5
.global main
ldi r16,0xff
out _SFR_IO_ADDR(DDRB),r16
ldi r16,0x00
out _SFR_IO_ADDR(DDRD),r16

main:
    sbis portd, 3
    rjmp ledoff
    ldi r16,0xff
    sbi _SFR_IO_ADDR(PORTB),LED   ; turn on led
    rjmp main
ledoff:
    ldi r16,0x00
    cbi _SFR_IO_ADDR(PORTB),LED   ; turn off led
    rjmp main

```

But I got this error compiling:

```
.pio\build\uno\src\main.o: In function `main':
(.text+0x8): undefined reference to `portd'
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\uno\firmware.elf] Error 1

```

# Answer
This line:

> ```
>    ldi r18, 0b00100000             ;pushed button
>
> ```

does not match the definition of `BUTTON`. You are setting bit 5 of the register, whereas the button is on bit 3. In order to avoid this kind of error, I would rather write

```
   ldi r18, _BV(BUTTON)            ;pushed button

```

Then, here:

> ```
>    out BUTTON, r16                 ;read button to r16
>
> ```

you are not reading anything: you are writing somewhere. I guess you mean:

```
   in r16, _SFR_IO_ADDR(PIND)      ;read button to r16

```

Note that this reads the whole port at once. If you are only interested in one bit, you should then

```
   andi r16, _BV(BUTTON)           ;keep only the relevant bit

```

before the comparison.

One last thing: you may want to read about the `sbis` and `sbic` instructions: they could simplify the code you have here.

---

**Edit**: answering the updated question.

> undefined reference to \`portd'

This is because there is no such thing as “portd”. You mean `_SFR_IO_ADDR(PORTD)`. Well, no, you should actually use `_SFR_IO_ADDR(PIND)`, as this is the port *input* register, whereas `PORTD` is the *output* register.

A couple of extra notes:

* Do not put code before `main`: it will not be executed, as the C runtime jumps to `main` after its initialization.
* The instructions `ldi r16, …` within the main loop serve no purpose: you are not using this register after the program initialization.
> 5 votes

---
Tags: avr, assembly, platformio
---


# Question
Title: Faster TimerOne with Teensy 4.0 (600MHz)
I have a teensy 4.0 which runs at 600MHz, and is double superscaler (i.e. can execute two instructions per clock cycle, sometimes). I need an interrupt to happen faster than every microsecond. I've calculated that it's possible for the processor to run the my code at that speed with some reasonable overhead. **Can TimerOne (or similar) be set to produce an interrupt more than once per microsecond?**

Thanks in advance.

# Answer
> 2 votes
You can use the TeensyTimerTool for this. It provides a generic interface to the hardware timers (TMR, GPT, PIT) and 20 software timers. Since the coupling of the timer peripherals to the ARM core is rather inefficient, the software timers might be a better fit for sub micro second interrupts. If you prefer the hardware timers I suggest to use a GPT timer (also supported by the lib). You can configure it to use a 150MHz clock instead of the standard 24MHz clock. So something like 2MHz interrupt rate should be feasible.

Documentation can be found here: https://github.com/luni64/TeensyTimerTool/wiki

# Answer
> 0 votes
I had a similar problem with the Teensy 3.5. I found that using the "Periodic Interrupt Timer (PIT)" let me generate interrupt every 300 ns. I imagine that with a Teensy 4.0, it must be possible to generate an interrupt every 100 ns. Here is the code which works for me on my Teensy 3.5, with comments in french and some references in the comments. I test the signal on an oscilloscope.

```
// ex00305_Timer_pit0_isr_rapide.ino
/*

FONCTIONNE TRES BIEN

Le signal n'est pas très stable, mais acceptable.
J'imagine que d'autres routines d'interruption perturbe la précision, comme la routine millis()

L'instruction suivante améliore la stabilité. visiblement.
NVIC_SET_PRIORITY(IRQ_PIT_CH0, 0);

Le but est de tester l'utilisation du Timer1 .c.f
/home/bg/Arduino/Teensy/Teensy_3_5_manual_K64P144M120SF5RM.pdf
Page 1083, Chapter 41 : "Periodic Interrupt Timer (PIT)"

Pour la gestion des timers PIT, c.f.
====================================
https://github.com/loglow/PITimer/blob/master/PITimer.cpp

********************************************************************************** */

#define PINOUT1 34
#define LEDRED  24
#define LEDYELLOW  25
#define LEDGREEN  26

volatile byte bEtat = 0;

void setup() {
    //============
    pinMode(PINOUT1, OUTPUT);
    digitalWriteFast(PINOUT1, HIGH);

    pinMode(33, OUTPUT);
    pinMode(34, OUTPUT);
    pinMode(LEDRED, OUTPUT);  digitalWriteFast(LEDRED, LOW);
    pinMode(LEDYELLOW, OUTPUT);  digitalWriteFast(LEDYELLOW, LOW);
    pinMode(LEDGREEN, OUTPUT);  digitalWriteFast(LEDGREEN, LOW);

    //if (SIM_SCGC6_PIT == 0b100000000000000000000000) digitalWriteFast(LEDYELLOW, HIGH);
    SIM_SCGC6 |= SIM_SCGC6_PIT; // C.f. page 317.  PIT Clock Gate Control   SIM_SCGC6_PIT == 0b100000000000000000000000

    // C.f. : /home/bg/.arduino15/packages/teensy/hardware/avr/1.58.1/cores/teensy3/kinetis.h
    // #define NVIC_ENABLE_IRQ(n) (*((volatile uint32_t *)0xE000E100 + ((n) >> 5)) = (1 << ((n) & 31)))
    // enable IRQ Interrupt
    NVIC_SET_PRIORITY(IRQ_PIT_CH0, 0); // Haute priorité, pour ne pas être perturbé par d'autres interrupt. Amélioration visible !
    NVIC_ENABLE_IRQ(IRQ_PIT_CH0);
    PIT_TCTRL0 = 3; // 0b011;  // enable Timer 0 interrupts ; start Timer 0   IRQ_PIT_CH0 == 48  Dans #elif defined(__MK64FX512__)
    //if (IRQ_PIT_CH0 == 48) digitalWriteFast(LEDGREEN,  HIGH);

    // Efface le flag du timer, pour permettre d'autres interruptions, nécessaire au départ
    PIT_TFLG0 = 1;

    // L'ordre des instruction a de l'importance !
    //""""""""""""""""""""""""""""""""""""""""""""
    PIT_MCR = 0;  // turn on PIT
    //PIT_LDVAL0 = 600-1;  // == 10 micro secondes setup timer 0 for xxx cycles Fréqu = 60 MHz  dt = 16.666 ns
    //PIT_LDVAL0 = 120-1;  // == 2 micros second
    //PIT_LDVAL0 = 60-1;   // == 1 micros second
    //PIT_LDVAL0 = 30-1;   // == 500 ns
    //PIT_LDVAL0 = 24-1;   // == 400 ns
    //PIT_LDVAL0 = 21-1;   // == 350 ns
    //PIT_LDVAL0 = 20-1;   // == 333 ns
    //PIT_LDVAL0 = 18-1;   // == 300 ns
    PIT_LDVAL0 = 120-1;
} // setup

void loop() {
    //===========
} // loop

void pit0_isr() {  // C.f. mk20dx128.c
    //===============
    // J'espère pouvoir gérer un temps

    // Efface le flag du timer, pour permettre d'autres interruptions
    // Doit être mis en début de routine !!!
    PIT_TFLG0 = 1;

    if (bEtat) {
        digitalWriteFast(PINOUT1, HIGH);
        //digitalWriteFast(LEDRED,  HIGH);
        bEtat = 0;
    }
    else {
        bEtat = 1;
        digitalWriteFast(PINOUT1, LOW);
        //digitalWriteFast(LEDRED,  LOW);
    }

} // pit0_isr

```

---
Tags: interrupt, timers, teensy
---


# Question
Title: Need help individually controlling 3 LEDs with 3 toggle switches
I'm trying to individually control 3 LEDs with 3 toggle switches. This is the code I'm using

```
#define LED_PIN1 2
#define BUTTON_PIN1 14

#define LED_PIN2 3
#define BUTTON_PIN2 15

#define LED_PIN3 4
#define BUTTON_PIN3 16

void setup() {
  pinMode(LED_PIN1, OUTPUT);
  pinMode(BUTTON_PIN1, INPUT);

   pinMode(LED_PIN2, OUTPUT);
  pinMode(BUTTON_PIN2, INPUT);

   pinMode(LED_PIN3, OUTPUT);
  pinMode(BUTTON_PIN3, INPUT);

}
void loop() {
  if (digitalRead(BUTTON_PIN1) == HIGH) {
    digitalWrite(LED_PIN1, HIGH);
  }
  if (digitalRead(BUTTON_PIN1) == LOW)   {
    digitalWrite(LED_PIN1, LOW);
  }
  if (digitalRead(BUTTON_PIN2) == HIGH) {
    digitalWrite(LED_PIN2, HIGH);
  }
  if (digitalRead(BUTTON_PIN2) == LOW) {
    digitalWrite(LED_PIN2, LOW);
  }
  if (digitalRead(BUTTON_PIN3) == HIGH) {
    digitalWrite(LED_PIN3, HIGH);
  }
  if (digitalRead(BUTTON_PIN3) == LOW) {
    digitalWrite(LED_PIN3, LOW);
  }
}

```

The problem is that this code is causing all 3 LEDs to turn on or off together when any one of the three toggle switches is pushed. Can someone explain why this is happening? Also, what do I need to change so that each LED can be individually controlled?

Thanks!

# Answer
> 3 votes
How is your wiring done?

This is a working example of how it can be done:

```
#define LED_PIN1 5
#define BUTTON_PIN1 14

#define LED_PIN2 6
#define BUTTON_PIN2 15

#define LED_PIN3 7
#define BUTTON_PIN3 16

void setup() {
  // set up all the LEDs as OUTPUT
  pinMode(LED_PIN1, OUTPUT);
  pinMode(LED_PIN2, OUTPUT);
  pinMode(LED_PIN3, OUTPUT);

  // set up all the buttons as INPUT
  pinMode(BUTTON_PIN1, INPUT);
  pinMode(BUTTON_PIN2, INPUT);
  pinMode(BUTTON_PIN3, INPUT);
}

void loop() {
  // turn the LED on when button is pressed
  digitalWrite(LED_PIN1, digitalRead(BUTTON_PIN1));
  digitalWrite(LED_PIN2, digitalRead(BUTTON_PIN2));
  digitalWrite(LED_PIN3, digitalRead(BUTTON_PIN3));
}

```

When you just want the LED to be on when the button is pressed and off when the button is unpressed you can simplify the code by directly writing the button state to the LED like so: `digitalWrite(LED_PIN, digitalRead(BUTTON_PIN))`. Because read of the button will return either `HIGH` or `LOW` you can directly drive the LED with this.

Also make sure you check the pin's you are using on your device. Pin 3 is the reset pin. I therefore changed the pins to 5, 6, 7 to make sure you're using digital pins.

If you want to see a working example in action, take a look at this tinkercad. Be aware that I'm using an arduino uno here, so make sure that you use correct pins using the previous pin layout when adapting this to your Arduino nano. You can simulate this circuit by clicking on the 'simulate' button and test this working example by clicking on the buttons in the circuit.

---
Tags: arduino-nano
---


# Question
Title: With reference to Arduino Keyboard library, it does not have a keymap for UK keyboard, has anyone created a KeyboardLayout_en_UK.cpp file for this?
With reference to the Arduino Keyboard library, it does not have a keymap for the UK keyboard. I have tried to find a keyboard map that shows the hex value for the UK keyboard but I didn't have any luck.

If you look in the Arduino Keyboard library: `Arduino\libraries\Keyboard\scr\KeyboardLayout_en_US.cpp` it has some other languages but no keyboard layout for a UK keyboard.

It does say somewhere I think on GitHub that a keyboard layout file can be added, but where can I get that file or how can I create that file? Has anyone already created a KeyboardLayout\_en\_UK.cpp file I could use, please?

# Answer
> 1 votes
As an example of what you might do ...

First copy the file KeyboardLayout\_en\_US.cpp and rename it as KeyboardLayout\_en\_UK.cpp.

Most of the entries will be the same. Now looking at the layout in https://github.com/arduino-libraries/Keyboard/blob/1.0.4/src/KeyboardLayout.h we see this:

```
  +---+---+---+---+---+---+---+---+---+---+---+---+---+-------+
  |35 |1e |1f |20 |21 |22 |23 |24 |25 |26 |27 |2d |2e |BackSp |
  +---+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-----+
  | Tab |14 |1a |08 |15 |17 |1c |18 |0c |12 |13 |2f |30 | Ret |
  +-----++--++--++--++--++--++--++--++--++--++--++--++--++    |
  |CapsL |04 |16 |07 |09 |0a |0b |0d |0e |0f |33 |34 |31 |    |
  +----+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+---+----+
  |Shi.|32 |1d |1b |06 |19 |05 |11 |10 |36 |37 |38 |  Shift   |
  +----+---++--+-+-+---+---+---+---+---+--++---+---++----+----+
  |Ctrl|Win |Alt |                        |AlGr|Win |Menu|Ctrl|
  +----+----+----+------------------------+----+----+----+----+

```

The third key along the top row of my (US) keyboard (below the function keys) has `@` on top and `2` on the bottom. It has the code `1f` in the chart.

In the US layout file we see, in part:

```
0x2c,          // ' '        0x20
0x1e|SHIFT,    // !          0x21
0x34|SHIFT,    // "          0x22
0x20|SHIFT,    // #          0x23
0x21|SHIFT,    // $          0x24
0x22|SHIFT,    // %          0x25
0x24|SHIFT,    // &          0x26
0x34,          // '          0x27
0x26|SHIFT,    // (          0x28
0x27|SHIFT,    // )          0x29
0x25|SHIFT,    // *          0x2a
0x2e|SHIFT,    // +          0x2b
0x36,          // ,          0x2c
0x2d,          // -          0x2d
0x37,          // .          0x2e
0x38,          // /          0x2f
0x27,          // 0          0x30
0x1e,          // 1          0x31
0x1f,          // 2          0x32
0x20,          // 3          0x33
0x21,          // 4          0x34
0x22,          // 5          0x35
0x23,          // 6          0x36
0x24,          // 7          0x37
0x25,          // 8          0x38
0x26,          // 9          0x39
0x33|SHIFT,    // :          0x3a
0x33,          // ;          0x3b
0x36|SHIFT,    // <          0x3c
0x2e,          // =          0x3d
0x37|SHIFT,    // >          0x3e
0x38|SHIFT,    // ?          0x3f
0x1f|SHIFT,    // @          0x40

```

I've put the *positions* of each entry on the right (the offset from the start of the array).

So looking at that table, when the scan code `1f` arrives, and SHIFT is pressed, we get `0x40` which is indeed `@` in the ASCII table.

Similarly, `1f` without SHIFT gives us `0x32` which is `2` in the ASCII table.

Now in your case I believe that key gives `"` when SHIFT is pressed, so the *third* line from the top in my example changes from:

```
0x34|SHIFT,    // "          0x22

```

to:

```
0x1f|SHIFT,    // "          0x22

```

And likewise for the other keys. So, the `@` symbol moves to where the quote is in the US keyboard. So change the *last* line in my example from:

```
0x1f|SHIFT,    // @          0x40

```

to:

```
0x34|SHIFT,    // "          0x40

```

Those two changes "swap" the locations of the `"` and the `@` symbols.

---

As noted in the comments, keys marked ¬ and £ do not have a 7-bit ASCII representation so you will not be able to put them in the table (there is no entry for them).

# Answer
> 2 votes
I am not aware of a UK layout file for the Arduino Keyboard library. The library itself does not have such a layout, and a Web search returned nothing. You may consider creating this layout yourself. The documentation of `Keyboard.begin()` states:

> Custom layouts can be created by copying and modifying an existing layout. See the instructions in the Keyboard library’s KeyboardLayout.h file.

The file KeyboardLayout.h does indeed have detailed instructions for this. Are they clear enough? If not, please tell me: I wrote those instructions, and I may try to update them if something in them is confusing.

Do you feel like trying to create this layout yourself? If so, it would be nice if you could submit it to the official library as a pull request. This way other users of the library may benefit from your work. If you don't feel like doing it, I may give it a try (I have already created a few of them). In this case, I would appreciate if you could submit an issue, just to show the maintainers that there is some interest in having the library provide this layout.

---
Tags: library, keyboard
---


# Question
Title: How do you take the simplest continuous reading from a Garmin Lidar Lite V4 using I2C on a Particle Boron v4.1.0?
Hey there Stack community. I'm working with the Particle Boron v4.1.0. I'm connecting a Garmin Lidar Lite V4 on I2C. I'm using the LIDARLite\_v4LED.h header file found in the library given for this device, "LIDAR-Lite" and my goal here is to op-check the sensor, by taking readings in the simplest way according to the .h file.

Wiring: I've soldered 22AWG solid wire to each respective pin on the sensor: GND : black, going directly to ground. VCC : red, 3.3V pin on the Particle Boron. I2C SDA : blue, SDA Pin0 on the Particle Boron with a 4.7K ohm pull-up resistor, connected to ground on one end, and running to Pin0 on the Boron. I2C SCL : green, SCL Pin1 on the Particle Boron with a 4.7K ohm pull-up resistor, connected to ground on one end, and running to Pin1 on the Boron.

I've run an I2C scan which confirmed the address at 0x62.

According to the manual at: https://static.garmin.com/pumac/LIDAR-Lite%20LED%20v4%20Instructions\_EN-US.pdf

To take a reading you must perform the following actions, which are embedded in the library's .h file functions:

"Obtaining Measurements from the I2C Interface You can obtain measurement results from the I2C interface.

1. Write 0x04 to register 0x00.
2. Read register 0x01.
3. Repeat step 2 until bit 0 (LSB) goes low.
4. Read two bytes from 0x10 (low byte 0x10 then high byte 0x11) to obtain the 16-bit measured distance in centimeters."

```
#include <LIDARLite_v4LED.h>

const int I2CADDRESS = 0X62;
uint16_t distance;

LIDARLite_v4LED L1;

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

void loop() {
    L1.takeRange(I2CADDRESS);
    L1.waitForBusy(I2CADDRESS);
    L1.getBusyFlag(I2CADDRESS);
    distance = L1.readDistance(I2CADDRESS);
    Serial.printf("Distance = %u\n", distance);
}

```

When I run the code above the Serial Monitor shows 0 continuously for the reading, which is incorrect.

Do you happen to see what I'm doing wrong?

Here is what's happening in each respective function call above:

```
void LIDARLite_v4LED::takeRange(uint8_t lidarliteAddress)
{
    uint8_t dataByte = 0x04;

    write(0x00, &dataByte, 1, lidarliteAddress);
} /* LIDARLite_v4LED::takeRange */

void LIDARLite_v4LED::waitForBusy(uint8_t lidarliteAddress)
{
    uint8_t  busyFlag;

    do
    {
        busyFlag = getBusyFlag(lidarliteAddress);
    } while (busyFlag);

} /* LIDARLite_v4LED::waitForBusy */

uint8_t LIDARLite_v4LED::getBusyFlag(uint8_t lidarliteAddress)
{
    uint8_t  statusByte = 0;
    uint8_t  busyFlag; // busyFlag monitors when the device is done with a measurement

    // Read status register to check busy flag
    read(0x01, &statusByte, 1, lidarliteAddress);

    // STATUS bit 0 is busyFlag
    busyFlag = statusByte & 0x01;

    return busyFlag;
} /* LIDARLite_v4LED::getBusyFlag */

uint16_t LIDARLite_v4LED::readDistance(uint8_t lidarliteAddress)
{
    uint16_t  distance;
    uint8_t * dataBytes = (uint8_t *) &distance;
    // Read two bytes from registers 0x10 and 0x11
    read(0x10, dataBytes, 2, lidarliteAddress);
    return (distance);
} /* LIDARLite_v4LED::readDistance */

```

Thanks in advance for any assistance!

NOTE: The code doesn't show any errors. It's possible I damaged the chip on the sensor when I soldered, as I'm a newb to all of this! However, I've put two sensors together and tried them each separately with the same code, and got the same results in an attempt to rule this out. I did better soldering the second sensor, and find it highly unlikely I damaged them both.

# Answer
As romkey pointed out, I had the pull-up resistors wired wrong. Pull-up resistors are connected to power, not to ground.

Then I had to include `wire.h` and initiate `Wire.begin();` in setup.
> 3 votes

---
Tags: c++, i2c, library, iot, functions
---


title: NRF24L01 PA+LNA With Arduino

text:
# Question
Title: NRF24L01 PA+LNA With Arduino
I am using the NRF module for remote communucation.I have been many research about nrf but my nrf module is not working This is my tranmistter code:

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

RF24 radio(7, 8,4000000); // CE, CSN

const byte address[6] = "00001";

void setup() {
  Serial.begin(115200);
  radio.begin();
  radio.openWritingPipe(address);
  radio.setRetries(15,15);
  radio.setPALevel(RF24_PA_HIGH);

}

void loop() {
  radio.stopListening();
  const char text[32]="Hello world";
  if(radio.write(&text,sizeof(text))){
    Serial.println("Mesaj gönderildi");
  }
  delay(1000);

```

This is my receiver code:

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

RF24 radio(7, 8,4000000); // CE, CSN

const byte address[6] = "00001";

void setup() {
  Serial.begin(9600);
  radio.begin();
  delay(400);
  radio.openReadingPipe(1, address);
  radio.setPALevel(RF24_PA_MAX);
//  radio.startListening();
   pinMode(10,OUTPUT);

}

void loop() {
 const char text[32]="";
  radio.startListening();
  if(radio.available())
  {
    while(radio.available()){
    radio.read(&text[0],sizeof(text[0]));
    Serial.println(text);
    delay(1000);
    }
  }
  delay(5);

}

```

ı tried the setPAlevel min but there is no change.In the transmitter side the write function returns true, but I can't get anything on the receiver side. Also, if I replace the cable connected to miso with the cable connected to mosi on the transmistter side, the write function still returns true. I also used adaptor ams1117

# Answer
> 1 votes
In the receiver code, you are just reading one byte, as 6v6gt pointed out. Check the library to see how `read()` works.

If you follow the getting started example, this is how you should read bytes in the receiver:

```
char text[32];

if (radio.available())
{
  uint8_t bytes = radio.getPayloadSize();  // get the size of the payload
  radio.read(&text, bytes);                // fetch payload from FIFO
}

```

Don't use `const` for `text` in the receiver. Also, you don't need to use `stopListening` and `startListening` in the `loop()`. They should just go to `setup()`.

---
Tags: arduino-uno, arduino-nano, nrf24l01+, wireless
---


# Question
Title: Are there any signal smoothing libraries for Arduino?
I am working on a mobile robot controlled via a wireless 2.4 GHz link.The receiver is connected to the Arduino Uno which serves onboard as the main controller. The most critical (and main) input channel coming from the receiver produces a very noisy signal, which leads to lots of minor changes in the output of the actuators, even though these are not needed.

```
*Plot of the input of the Arduino in a 30 second interval.*
```

I am looking for libraries that can perform efficient smoothing. Are there any signal smoothing libraries available for the Arduino (Uno)?

# Answer
Microsmooth is a lighweight signal smoothing library currently being developed by me.

It is still being worked on and the aim is to make it lightweight in terms of memory and fast. The library provides multiple filters for smoothing:

* Simple Moving Average
* Exponential Moving Average
* Cumulative Moving Average
* Savitzky Golay Filter
* Ramer Douglas Pecker Algorithm
* Kalmogorov Zurbenko Filter

To use the library, download and add it to the source directory. Also, add the following line to your source file:

```
#include "microsmooth.h"

```
> 13 votes

# Answer
I think I see a lot of single-sample noise spikes in your noisy signal.

The median filter does better at getting rid of single-sample noise spikes than any linear filter. (It is better than any low pass filter, moving average, weighted moving average, etc. in terms of its response time and its ability to ignore such single-sample noise spike outliers).

There are, in fact, many signal-smoothing libraries for the Arduino, many of which include a median filter.

signal-smoothing libraries at arduino.cc:

signal-smoothing libraries at github:

Would something like this work in your robot? (The median-of-3 requires very little CPU power, and hence fast):

```
/*
median_filter.ino
2014-03-25: started by David Cary
*/

int median_of_3( int a, int b, int c ){
    int the_max = max( max( a, b ), c );
    int the_min = min( min( a, b ), c );
    // unnecessarily clever code
    int the_median = the_max ^ the_min ^ a ^ b ^ c;
    return( the_median );
}

int newest = 0;
int recent = 0;
int oldest = 0;

void setup()
{
    Serial.begin(9600);
    // read first value, initialize with it.
    oldest = random(200);
    recent = oldest;
    newest = recent;
    Serial.println("median filter example: ");
}

void loop()
{
    // drop oldest value and shift in latest value
    oldest = recent;
    recent = newest;
    newest = random(200);

    Serial.print("new value: ");
    Serial.print(newest, DEC);

    int median = median_of_3( oldest, recent, newest );

    Serial.print("smoothed value: ");
    Serial.print(median, DEC);
    Serial.println("");

    delay(5000);
}

```
> 7 votes

# Answer
Have you tried a low pass filter? I found an example here an another one here.

Both of these libraries have a list of data being read from the analog sensor of your choice which is averaged. Every new sensor value is added to the list, and the last one is thrown out, like this:

```
List: 3 4 3 3 4 3 5 3 2 3 4 3
new reading added. old one thrown out
      /--                     /--
List: 5 3 4 3 3 4 3 5 3 2 3 4
list averaged

```
> 4 votes

# Answer
You could filter this digitally using a low pass filter:

```
int valueFilt = (1-0.99)*value + 0.99*valueFilt;

```

Change the 0.99 to change the cut off frequency (closer to 1.0 is lower frequency). The actual expression for that value is exp(-2\*pi\*f/fs) where f is the cutoff frequency you want and fs is the frequency the data is sampled at.

Another type of "digital filter" is an event filter. It works well on data that has outliers; e.g. 9,9,8,10,9,25,9 . An event filter returns the most frequent value. Statistically this is the mode.

Statistical averages such as Mean, Mode etc.. can be calculated using the Arduino Average Library.

An example taken from the Arduino Library page referred to :

```
#include <Average.h>
#define CNT 600
int d[CNT];

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

void loop()
{
  int i;

  for(i=0; i<CNT; i++)
  {
    d[i] = random(500);
  }

  Serial.print("Mean: ");
  Serial.print(mean(d,CNT),DEC);
  Serial.print(" Mode: ");
  Serial.print(mode(d,CNT),DEC);
  Serial.print(" Max: ");
  Serial.print(maximum(d,CNT),DEC);
  Serial.print(" Min: ");
  Serial.print(minimum(d,CNT),DEC);
  Serial.print(" Standard deviation: ");
  Serial.print(stddev(d,CNT),4);
  Serial.println("");
  Serial.println("");

  delay(5000);
}

```
> 2 votes

# Answer
Check out the Arduino Smooth library. It uses absolutely no arrays, no looping over past values, it's fast with constant compute time, and the objects take up 8 bytes regardless of the sample window size.
> 0 votes

---
Tags: library, signal-processing
---


# Question
Title: Why does analogRead(A0) deliver different Values when called in a library file vs calling it in the sketch directly
I wanted to write a library representing a sensor to later on have an array of sensors. I generated a file MoistureSensor.h:

```
#ifndef MoistureSensor_h
#define MoistureSensor_h

#include <Arduino.h>

class MoistureSensor {
  private:
    uint8_t sensPin;
    int sensValue;
    int sensId;

  public:
    MoistureSensor(uint8_t pin,int id);
    int getValue();
    int getId();
};

#endif

```

and MoistureSensor.cpp:

```
    // MoistureSensor.cpp
#include "MoistureSensor.h"

MoistureSensor::MoistureSensor(uint8_t pin, int id) {
  sensPin = pin;
  sensId  = id;
}

int MoistureSensor::getValue() {
  sensValue = analogRead(sensPin);
  return sensValue;
}
int MoistureSensor::getId() {
  return sensId;
}

```

this is the main sketch running on a Arduino Mega:

```
#include "MoistureSensor.h"

MoistureSensor sens1("A0", 1);

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

void loop() {
  Serial.println("Value from analogread:");
  Serial.println(analogRead(A1));
  Serial.println("Value from library:");
  Serial.println(sens1.getValue());
  Serial.println("End");
  delay(1000);

}

```

So when I run this the serial monitor shows:

```
Value from analogread:
600
Value from library:
496
End

```

Why doesn't this print the same value? Does the .cpp file interpret the data from `analogRead()` different than the sketch?

Also both values where moving up and down depending on the response of the sensor.

Thanks in advance.

# Answer
> 2 votes
Trying to compile your sketch, I get the following compiler warning:

```
warning: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}'
 MoistureSensor sens1("A0", 1);
                             ^
note:   initializing argument 1 of 'MoistureSensor::MoistureSensor(uint8_t, int)'

```

This means that, whereas the `MoistureSensor()` constructor expected its first argument to be of type `uint8_t`, you provided a `const char*` instead. Indeed, a string literal like `"A0"` decays to a `const char*` pointer when you pass it as a function argument.

The fix is to pass the actual pin number to your constructor:

```
MoistureSensor sens1(A0, 1);

```

But then, there is a second issue. In your test sketch, you have your `MoistureSensor` object read `A0`, whereas the direct `analogRead()` reads pin `A1`. If you want to get the same value, you should read the same pin.

**Side note**: the change from `uint8_t` to `byte` has absolutely nothing to do with your issue. These two types are synonyms.

# Answer
> -1 votes
I found a solution:

changing the parameter of the constructor `MoistureSensor::MoistureSensor(uint8_t pin, int id, int rawMax, int rawMin)`` from` uint8\_t `to`byte`solved this issue for me. I also changed the parameterization to` MoistureSensor sens1(1, 1);\`

---
Tags: arduino-mega, library, analogread
---


# Question
Title: : Failed to open /dev/ttyACM0 (port busy)
I am trying to work with the (new) sparkfun razor IMU 9dof, I wrote a silple sktetch to calibrate the magnetometer:

```
#include <SparkFunMPU9250-DMP.h> // Include SparkFun MPU-9250-DMP library
#include <Wire.h> // Depending on your Arduino version, you may need to include Wire.h
MPU9250_DMP imu; // Create an instance of the MPU9250_DMP clas
void setup() {
  Serial.begin(115200);

  Serial.println(F("Adafruit 10 DOF Board AHRS Calibration Example")); Serial.println("");

  if (imu.begin() != INV_SUCCESS){
    while (1) {
    Serial.println("Failed to initialize MPU-9250, loop forever");
   }

  }

 imu.setGyroFSR(2000); // Set gyro to 2000 dps

 imu.setAccelFSR(2); // Set accel to +/-2g

 imu.setLPF(5); // Set LPF corner frequency to 5Hz

 imu.setSampleRate(100); // Set sample rate to 10Hz

imu.setCompassSampleRate(100); // Set mag rate to 10Hz
}

void loop(void){
  imu.update();

  // Print the sensor data
  Serial.print("Raw:");
  Serial.print(imu.ax);
  Serial.print(',');
  Serial.print(imu.ay);
  Serial.print(',');
  Serial.print(imu.az);
  Serial.print(',');
  Serial.print(imu.gx);
  Serial.print(',');
  Serial.print(imu.gy);
  Serial.print(',');
  Serial.print(imu.gz);
  Serial.print(',');
  Serial.print(imu.mx);
  Serial.print(',');
  Serial.print(imu.my);
  Serial.print(',');
  Serial.print(imu.mz);
  Serial.println();

  delay(50);
}

```

To be sure the Arduino IDE can access to dev/ttcACM0, I did sudo chmod 666 /dev/ttyACM0

I can dowload successfully but when I want to open the terminal I got the following error:

Erreur d'ouverture du port série « /dev/ttyACM0 ». (Port busy) (see attached screenshot)

More over when I entered dmesg on the console, I can see the following messages:

```
[   94.133923] usb 3-2: USB disconnect, device number 2
[   94.133978] cdc_acm 3-2:1.1: urb 12 failed submission with -19
[   94.135862] cdc_acm 3-2:1.1: urb 13 failed submission with -19
[   94.136059] cdc_acm 3-2:1.1: urb 14 failed submission with -19
[   94.136257] cdc_acm 3-2:1.1: urb 15 failed submission with -19
[   94.136457] cdc_acm 3-2:1.1: urb 2 failed submission with -19
[   94.136656] cdc_acm 3-2:1.1: urb 3 failed submission with -19
[   94.136852] cdc_acm 3-2:1.1: urb 5 failed submission with -19
[   94.137048] cdc_acm 3-2:1.1: urb 6 failed submission with -19
[   94.138841] xhci_hcd 0000:03:00.0: WARN Cannot submit Set TR Deq Ptr
[   94.138843] xhci_hcd 0000:03:00.0: A Set TR Deq Ptr command is pending.
[   94.931853] usb 3-2: new full-speed USB device number 3 using xhci_hcd
[   95.316578] usb 3-2: New USB device found, idVendor=1b4f, idProduct=9d0f
[   95.316581] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[   95.316582] usb 3-2: Product: SFE 9DOF-D21
[   95.316584] usb 3-2: Manufacturer: SparkFun
[   95.320306] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
[  858.774849] usb 3-2: USB disconnect, device number 3
[  904.529058] TCP: wlp1s0: Driver has suspect GRO implementation, TCP performance may be compromised.

```

Does anyone outhere experienced such issue?

Thank you for your help

Fabrice

# Answer
> 5 votes
`sudo apt-get purge modemmanager` It helps me for linux user and for many other peoples. Now I am playing with stm32f103 and opening port was painfull. That was problem only for stm32 chip. Arduino nano was working without problems. Before I need reopened few times port to initiate communication. That was painfull. After finding that solution now Arduino ID is working without problems. I am not sure if deleting modemmanager will have impact for my system.

# Answer
> 2 votes
I solved following serial port related problems in ubuntu 18.04 as follows:

**Problem 1 : Cannot open /dev/ttyACM0: Permission denied**
Solution : Grant permissions to read/write to the serial port with this terminal command ---\> `sudo chmod a+rw /dev/ttyACM0` Here replace tty port with your respective ubuntu port.

**Problem 2 : Failed to open /dev/ttyACM0 (port busy)** Solution : This problem appears when serial port is busy or already occupied. So kill the busy serial port with command ---\> `fuser -k /dev/ttyACM0`. Here replace tty port with your respective ubuntu port.

**Problem 3 : Board at /dev/ttyACM0 is not available** Solution : In this case, your serial port in tools menu will be greyed out. I googled a lot for this, but none of solution worked for me. Atlast I tried different arduino board and usb connector and it was working for me. So, if you are having old arduino board (can be solved using required drivers) or defected arduino board then only this problem arises.

# Answer
> 1 votes
When I had this problem I discovered that running `ps x` showed a lot of tasks involving temporary mount files. So I closed Arduino, ran `sudo rm -rf /tmp/.mount_arduin*` and restarted Arduino. The device attached successfully.

# Answer
> 1 votes
You need to be part of the dial out group. Try this: Type 'groups', is 'dialout' there ? sudo usermod -a -G tty yourUserName Example sudo usermod -a -G tty gil

Log off and log on again for the changes to take effect. This has consistently worked for me and is now in some of the Arduino install packages.

---
Tags: arduino-ide
---