# Question
Title: Arduino IDE can't program my Arduino Pro Micro
I have a lot of Arduino Pro Micros that I can't program through the Arduino IDE.

I'm on Windows.

I'm using the SparkFun Pro Micro board information downloaded from SparkFun's website.

I've tried manually reassigning the Pro Micro's COM port in the device manager. It seems to be no different whether I'm at COM1 or COM255.

If I use an Arduino ISP or USBASP to burn the bootloader onto the problematic Pro Micro, it responds for usually one or two more USB programmings but that's about it.

When they get into this problematic state, they are still running their code (I can see the Blink sketch flashing my LED for instance), they just can't be reprogrammed. I can even still open their Serial communications.

Verbose output during the uploading process on first attempt yields the following:

```
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
Uploading using selected port: COM2
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM2 -b57600 -D -Uflash:w:C:\Users\Thompson\AppData\Local\Temp\arduino_build_668056/BareMinimum.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM2
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

```

That last line is where it freezes for an indefinite period. I close and reopen the Arduino IDE and try to reupload, and this is my result:

```
processing.app.debug.RunnerException
        at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
        at cc.arduino.UploaderUtils.upload(UploaderUtils.java:82)
        at processing.app.SketchController.upload(SketchController.java:736)
        at processing.app.SketchController.exportApplet(SketchController.java:703)
        at processing.app.Editor$DefaultExportHandler.run(Editor.java:2039)
        at java.lang.Thread.run(Thread.java:748)
    Caused by: processing.app.SerialException: Error touching serial port 'COM2'.
        at processing.app.Serial.touchForCDCReset(Serial.java:107)
        at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
        ... 5 more
    Caused by: jssc.SerialPortException: Port name - COM2; Method name - openPort(); Exception type - Port not found.
        at jssc.SerialPort.openPort(SerialPort.java:167)
        at processing.app.Serial.touchForCDCReset(Serial.java:101)
        ... 6 more

```

This exact same message (with a different COM number of course) plays out on any Windows machine I try this with.

In the above example I was trying to upload the Bare Minimum example.

Are all of my Pro Micros dead? Is there something wrong with the IDE? Is there an alternative IDE I can get a second opinion from?

EDIT: An update; I've gotten Atom installed with PlatformIO and I was able to write a few sketches to an Arduino Pro Mini. I attempted the same sketches on the Arduino Pro Micro and got the same error and freeze: `programmer is not responding`

# Answer
> 0 votes
After experimenting some more, it looks like this issue is related to a one second watchdog that I have enabled in my sketch. After removing the watchdog, I've had no problems (so far) with uploading code.

---
Tags: arduino-ide, bootloader, arduino-micro, windows
---


# Question
Title: DHT 11 temp. And hum. Sensor always 0 values
I am trying to get my DHT 11 from the official arduino store to work (https://store.arduino.cc/grove-temperature-humidity-sensor).

I am following this guide right here: http://wiki.seeedstudio.com/Grove-TemperatureAndHumidity\_Sensor/

But I'm only getting invalid output of 0 humidity and 0 degrees.

I hope the image helps in identifying my problem.

On a side note, my sensor looks like a part is missing which is very strange and makes me doubt the right product was sent to me.

Some more information: \- Black to GND \- Red to 5v \- White is wmpty \- Yellow to d2 \- Using an arduino Uno \- Output does not change whether the sensor is actually connect or not. \- Total noob at this.

Help would be appreciated a lot!

# Answer
You haven't bought a DHT11 module but the *Grove - Temperature&Humidity Sensor (High-Accuracy & Mini) / TH02* module.

Thus you should use the example code here or follow the guide at seedstudio wiki.

Datasheet of the sensor: https://www.silabs.com/documents/public/data-sheets/Si7005.pdf
> 3 votes

---
Tags: arduino-uno, temperature-sensor
---


title: No matching function call for timer?

text:
# Question
Title: No matching function call for timer?
I am using the Timer library here with the Adafruit feather m0: https://github.com/JChristensen/Timer https://playground.arduino.cc/code/timer I cannot figure out why I am getting the error:

no matching function for call to 'Timer::every(int, void (&)())'

Here is that part of the code:

```
void setup(){
      everyAlt = t.every(100, readAltimeter);
      everyLaunch = t.every(500, detectLaunch);
      t.oscillate(blueled, 500, HIGH);
    }

    void readAltimeter(){
      alts[altPlace] = bmp.readAltitude()-zeroAlt;
      altPlace++;
    }

    void detectLaunch(){
      tempSpeed = 0;
      int x = 0;
      while (x < 5){
        tempSpeed += abs((alts[x]-alts[x+1])*10);
      }
      if (tempSpeed/5 > 5){
        t.stop(everyLaunch);
      }
    }

```

I am pretty new to arduino so any help would be much appriciated!

# Answer
Had the wrong version. Correct version downloaded from the current master: github.com/JChristensen/Timer
> 2 votes

---
Tags: library
---


title: Question on a car kit I bought

text:
# Question
Title: Question on a car kit I bought
recently bought an UNIROI Smart Car kit. (UNIROI Smart Robot Car Kit Arduino Robot Kit with 4 Wheel Drive, Arduino UNO R3 Board, Ultrasonic Sensor, Infrared Tracking Module (No Welding Required) https://www.amazon.co.uk/dp/B07CWS344R/ref=cm\_sw\_r\_cp\_tai\_wQExCbHT0YM8K)

I bought some extra things with it to make it more interesting, but the problem is is that I need to connect more pins to the Arduino but they are all taken up by the car. What I have noticed is that there are these extra pins along the side of the Arduino board as you can see here: https://i.stack.imgur.com/7nhBO.jpg

I know you guys don’t have it in hand, but I thought I’d give it a shot to see if any of you know I can use those pins. The description of the car also quotes “Extended Pin Interface. The chassis is designed with extended pin interface for Arduino UNO, only need to solder pins for using, more convenient to develop and build your own robot car kit”

Appreciate any help you guys got.

# Answer
> 2 votes
It seems that you'll have to do some extended modifications to the design. In fact, all Arduino Pins (D0 - D13, A0-A5) are connected to components on the board and thus in use.

Schematics and Code: https://mega.nz/#F!Xbg1FA5L!qGah\_HlLFJ\_NKxv7ILLY2g folder "5 SCH".

This means that the only way that you'll get new components into this project are:

* removing components and re-programming the firmware to not use them
    + e.g., the two tracking-sensors left&right -\> A2 and A3 are free
    + e.g., the speaker pin (D13). Who needs a speaker?
* restructuring components
    + e.g. for the analog sensors: instead of using the Arduino's analog pins, throw a I2C ADC module (e.g. ADS1115) in the build and change the firmware to get the analog values via that new module; making this project use an I2C bus will free all analog pins and cost 2 pins (SCL + SDA). The I2C bus has the additional benefit of being able to connect more than one device to it -- you can e.g. put a I2C GPIO expander (e.g. MCP23017) on it to gain 16 more digital I/O -- more than the Uno had to begin with.

---
Tags: arduino-uno
---


# Question
Title: How to read a 25 kHZ PWM signal from PC fan header?
I would like to control a DC motor's speed using the PWM output from my motherboard header.

Here's the standard pinout for a 4-wire PC fan header:

```
╔═══╦════════╦═════════════════╦════════╗
║ # ║  Name  ║   Description   ║  Wire  ║
╠═══╬════════╬═════════════════╬════════╣
║ 1 ║ GND    ║ Ground          ║ black  ║
║ 2 ║ +12V   ║ Fan Power       ║ yellow ║
║ 3 ║ SIGNAL ║ Fan RPM         ║ green  ║
║ 4 ║ PWM    ║ Digital Control ║ blue   ║
╚═══╩════════╩═════════════════╩════════╝

```

Since my DC motor doesn't have a PWM input, I thought of using an `ATmega328P` in my custom board to read the PWM output of the fan header -- pin 4 -- so that I can use a motor driver to control my motor's speed.

However, I'm not sure how I should read the PWM signal from the motherboard.

1. What is the `HIGH` voltage level of PWM output?
Do I need a voltage divider resistor for it?

A source for the fan control specifies this to be **5.25V** at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.
2. Should I use `pulseIn()` function for the 25kHZ (21~28kHZ range) PWM output?
Can the ATmega328p handle this frequency range?

I prefer to use Arduino's bootloader with the wiring library, but if you have AVR-specific examples that I could follow, I'd appreciate it.

# Answer
> Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output? Can the ATmega328p handle this frequency range?

No, and No; 1/25000 = .000040 or 40 microseconds (μS) and the documentation for pulseIn() says:

> Works on pulses from 10 microseconds to 3 minutes in length

However the PWM frequency is the maximum on time, at 50% you will have a square wave that is HIGH for 20 μS and low for 20 μS. pulseIn will not work if the PWM duty cycle goes below 25%

What you want to do is put an 'accumulator' (an RC filter) between the PWM output and an analog input pin, and read the voltage off of that.

However since you want to

> ... control a DC motor's speed using the PWM output from my motherboard header

and the fanspeed header is already designed to do this, you just use the PWM signal to drive a transistor that drives the motor, the motor itself will act as an accumulator here; no micro controller needed!

> ... so that I can use a motor driver to control my motor's speed.

you will need to generate an extremely similar, almost certainly identical, PWM signal to drive your motor controller/driver

> A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

Trust your documentation or test it if you don't trust the docs!
> 1 votes

---
Tags: pwm
---


# Question
Title: Does Arduino Uno come with Virtual Pin support?
I want to recieve Data with Virtuino from my Arduino Uno 3 (Ethernet Shield) via Ethernet.

Does Arduino Uno 3 support virtual pin? If so - is there a link with the Syntax I need?

Thank you very much

# Answer
Virtual pins are, as the name gives away, *virtual*, thus not related to the hardware you are using. Imagine you have a board with 100 pins, you have 100 physical pins and can add 1 million virtual pins (memory permitting). In other words, the question doesn't seem to make sense to me.

**UPDATE** If you need a bootstrap on *how* virtual pins are defined and used you could give a look at the examples published by the authors, like these

If that's not enough, please provide additional information on what problem you are facing and which solutions you have already attempted.
> 1 votes

---
Tags: arduino-uno
---


title: Error: Does not name a type

text:
# Question
Title: Error: Does not name a type
I have made a class called subjects and I have then made a subject called math. I am trying to set a classroom for math but it is giving me the error 'math' doesn't name a type.

Code for the class

```
class subject {
public:
  char subjectname[];
  char classroom[];

};

```

Code for the classroom and math

```
subject math;
math.classroom = "A1";

```

How can I set the classroom of math to A1?

# Answer
> 3 votes
```
class subject {
public:
  char subjectname[];
  char classroom[];

};

```

This creates a class `subject` which has two `char` arrays of unspecified size as its members. This will attempt to create an array of size 0 (see here). This is not what you want. You can e.g. statically allocate the space with a maximum number of characters beforehand and then `strncpy()` your new string inside the buffer.

This would look like

```
class subject {
public:
  char subjectname[32];  //32 bytes buffer
  char classroom[32];
};

```

And later

```
subject math;
strncpy(math.classroom, "A1", 31); //copy at max 31 bytes to not overwrite the NUL terminator
Serial.print("Classroom is: ");
Serial.println(math.classroom)

```

Or, just use the Arduino `String` class. For example

```
#include <Arduino.h>
class subject {
public:
  String subjectname;
  String classroom;
};

```

Then your first usage code can be used unmodified.

Example

```
#include <Arduino.h>

class subject {
public:
  String subjectname;
  String classroom;
};

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

    subject math;
    math.classroom = "A1";

    Serial.print("Classroom is: ");
    Serial.println(math.classroom);
}

void loop() { }

```

---
Tags: c++, error
---


# Question
Title: Would a 100KΩ resistor connected to ground pull an open analog line down to 0
I have a project that has a photoresistor wired into a voltage divider and connected through a 3.5mm “stereo mini plug”. When nothing is in the mini plug, the analog line is an open circuit, and floats, creating jittery spurious readings.

I’d like to wire a pull-down resistor into the project box to tie it to ground so I get a zero reading when the light sensor is not connected, but want to alter the voltage reading from my photo sensor voltage divider circuit as little as possible.

If I connect a 100KΩ resistor between my analog input and ground, that would give me zero readings on the analog pin when the photo sensor is not plugged in, wouldn’t it? I can’t see how \< 20 CM of 26 gauge wire would pick up enough interference to pull my analog pin up from 0 through a 100kΩ resistor.

What is the effective range of an analog pin on an Arduino? (A Mega 2560, if that matters) What’s the lowest voltage that will register above 0?

(The project box is getting crowded, so experimenting is getting tricky. I’d like to make a single change rather than trying different resistor values.)

# Answer
I would expect a 100K pulldown to quiet the A/D, but I'd have to actually try it. I'd think testing it on the bare board, outside of your project box would still give you useful information. But I would sketch up the schematic of the proposed voltage divider with the parallel pulldown and run the numbers to convince yourself of what effect it will have on your measurement. You may be able to ignore it, or you may want to correct for it.

> What is the effective range of an analog pin on an Arduino?

0 - (1023/1024)\*Vref, whichever reference, 1.1v, 2.56v, or Vcc applied to the Vref pin, you have selected.

> (A Mega 2560, if that matters) What’s the lowest voltage that will register above 0?

Appx (Vref * 2^-11), i.e., 1/2 an LSB of the 10-bit A/D range.

Update:

Is that a jumper selection?

No, it's programmable; the external Vref is reset default. See ch. 25 of the 2560 datasheet for the low-level details; Arduino.cc's function-reference, for the `analogReference()` function for the quick & dirty how-to. Remember to take and discard a measurement whenever you change the reference.
> 1 votes

# Answer
With a 100 kΩ resistor to GND, it is not guaranteed that the value will be zero. If a (servo)motor is connected, it might get some noise.

The pull down resistor can be any value, because it is possible to calculate the value of the photoresistor.

There is an alternative solution. I think that all the analog pins of the Arduino Mega 2560 are digital pins as well. You can do a `pinMode(A0,INPUT_PULLUP);` to pull the input high. When a photoresistor is connected, you can turn the internal pullup resistor off with `pinMode(A0,INPUT);`.
> 1 votes

---
Tags: analogread, resistor, voltage-divider
---


title: Weird behavior with char/uint8 arrays

text:
# Question
Title: Weird behavior with char/uint8 arrays
So I'm trying to read an 8-byte character string from an I2C device and print it to the serial console. This raw 8-char array is *not* terminated when it comes from the device, so I'm pretty sure I need to manually terminate it. Unfortunately, when I go to print the resultant string, the serial monitor just fills up with line breaks. Could someone take a look at this code and tell me where I went wrong?

```
uint8_t* HT_Controller::readMultiple(uint8_t reg, uint8_t num)
{
    Wire.beginTransmission(i2cAddr);
    Wire.write(reg);
    Wire.endTransmission();

    Wire.requestFrom(i2cAddr, num);
    uint8_t* data = new uint8_t[num];

    for(int i = 0; i < num; i++)
    {
        data[i] = Wire.read();
    }

    return data;
}

char* HT_Controller::getManufacturer()
{
    uint8_t* data = readMultiple(REGISTER_MFR, NUM_MFR_BYTES); //Read the bytes from the controller
    char* dataTerminated = new char[NUM_MFR_BYTES + 1]; //Our new array that will have a null char at the end
    memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array
    delete(data); //We're done with the original array, remove it from the heap
    dataTerminated[NUM_MFR_BYTES] = 0; //Add that null char. NB: we don't need to '+1' the index because arrays start at 0, not 1

    return dataTerminated;
}

```

And here's how it's used in the main sketch:

```
void loop()
{
    char* data = mc1->getManufacturer();
    Serial.println(data);
    delete(data);
    delay(500);
}

```

# Answer
Your memcpy is backwards.

```
SYNOPSIS
   #include <string.h>

   void *memcpy(void *dest, const void *src, size_t n);

```

So the line:

```
memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array

```

should be:

```
memcpy(dataTerminated, data, NUM_MFR_BYTES); //Copy the bytes into the new array

```
> 1 votes

---
Tags: c++, i2c, string
---


title: Use 2 DHT22 AND PASS THE DATA TO SD?

text:
# Question
Title: Use 2 DHT22 AND PASS THE DATA TO SD?
I have the code to pass the data from dht22 to sd but for only one and i want to pass the data from 1 dht22 with one file and the data from other sensor to other file and logging in to sd. Anyone can help me?

```
#include
#include
#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
File data_file;

int CS_pin = 10;
long sec=00;
long mint=00;
long hr=00;

void setup() {
Serial.begin(9600);
pinMode(CS_pin, OUTPUT);
dht.begin(); //This command will start to receive the values from dht22
// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is initialized and it is ready to use");
} else
{
Serial.println("SD card is not initialized");
return;
}
}

void loop() {
data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
delay(1000);
}

void getData(){
for(long sec = 00; sec < 60; sec=sec+2){
float temp = dht.readTemperature(); //Reading the temperature as Celsius and storing in temp
data_file.print(hr);
data_file.print(":");
data_file.print(mint);
data_file.print(":");
data_file.print(sec);
data_file.print(", ");
data_file.println(temp);
Serial.print(hr);
Serial.print(":");
Serial.print(mint);
Serial.print(":");
Serial.print(sec);
Serial.print(", ");
Serial.println(temp);
if(sec>=58){
mint= mint + 1;
}
if (mint>59){
hr = hr + 1;
mint = 0;
}
data_file.flush(); //saving the file
delay(2000);
}
data_file.close(); //closing the file
}

```

Thanks

# Answer
First you need to setup the second DHT sensor and a second file. Please replace the `X` by the number of the pin your second sensor is connected to after `#define DHTPIN2`

```
#define DHTPIN 8
#define DHTPIN2 X
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
File data_file, data_file2;

```

In `setup()` you need to also start the second dht sensor:

```
dht.begin(); //This command will start to receive the values from dht22
dht2.begin(); //This command will start to receive the values from dht22

```

In `loop()` you have to open the second data file in addition to the first one:

```
data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
data_file2 = SD.open("data2.txt", FILE_WRITE);
if (data_file2) {
getData2();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data2.txt");
}

```

Although not the most efficient/elegant solution, this requires you to duplicate your `void getData()` function as `void getData2()` to work for the second sensor/file, by replacing `dht` by `dht2` and `data_file` with `data_file2`. This would do the logging on the two sensors in sequence.
If you want the logging in parallel you need to add the measurement and writing of the second sensor/file into the `void getData()` function.
> 1 votes

---
Tags: sensors, sd-card
---


# Question
Title: Arduino Yun can no longer send to Dropbox
A long time ago I had set up an Arduino Yun to send files to Dropbox... I tried now and it ends in "killed" when trying to install the latest Dropbox Python module.

`pip install (six, urllib3, etc etc)` does work individually without running out of memory. Unfortunately when I install all but Dropbox, and then put the Dropbox module code folder in the current directory, it does start to import Dropbox with `import dropbox` but ends up with the KILLED message.

Is there a way I can connect to my current Dropbox without it using all of the 60mb of RAM and quitting... I keep getting the error with version 2.1:

> Error.Cannot connect to Dropbox \[400\] u'v1\_retired'

# Answer
I'd eventually figured out how to do it running the latest Dropbox module installed into the sd card where there was room.
> 0 votes

---
Tags: arduino-yun, python, linux
---


# Question
Title: Digital I/O threshold voltages for ATmega32u4
What are the voltages on a ATmega32u4 (eg Arduino Leonardo) such that a `HIGH` or `LOW` is read?

I want to ensure that I'm reading the chip reference manual correctly, where Table 29-1 says:

---

VIL: Input Low Voltage, Except XTAL1 and Reset pin

* Min: -0.5
* Max: 0.2VCC-0.1V (LVTTL)

VIH: Input High Voltage, Except XTAL1 and RESET pins

* Min: 0.2VCC+0.9V (LVTTL)
* Max: VCC + 0.5V

---

My questions:

1. What is LVTTL?
2. How do I interpret the VIL Max and VIH Min?
3. Is the input undefined between those two values?

# Answer
1. LVTTL is Low Voltage Transistor-Transistor Logic. In general, the term "TTL" is used for a digital signal. The "Low Voltage" part is special, the ATmega32U4 switches from low to high (and vice versa) at low voltages.
2. Just as it is written. For example, when the ATmega32U4 runs at 5V, then:
VILmax = 0.2 * 5 - 0.1 = **0.9 V**.
VIHmin = 0.2 * 5 + 0.9 = **1.9 V**.
3. Between those values the input signal is seen as low or high, but the exact voltage when it switches from low to high may vary.
When the microcontroller is running at 5.0 V and is used within the specifications of the datasheet, then a voltage below 0.9 V is always seen as low and a voltage above 1.9 V is always seen as high (guaranteed).
Those voltages is what a electronics designer must consider.

In the datasheet of the ATmega32U4 at page 403 is paragraph 30.7 "Pin Threshold and Hysteresis" with figure 30-22 and 30-23.
The figures show that at 25°C and 5V, the input switches from low to high typical at 1.55 V and it switched from high to low at maybe a slightly lower voltage.
The hysteresis is almost none and the voltage depends on VCC and the temperature.

(*Thanks to Edgar Bonet for the correction/addition*)
> 5 votes

---
Tags: voltage-level, digital, atmega32u4, voltage, digital-in
---


# Question
Title: I want to get incomming call number and compare it
Hello i want to get and compare incomming call number, it works but not as I want. When im calling from good number it print that I was calling form saved number when the number is stop calling i need to do it on start. And `else` is printing when nobody is calling. How can i do it? Here is my code:

```
String d = "";
void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.println("AT");
  delay(500);
  Serial1.println("AT+CLIP=1");
  delay(1000);
  Serial1.println("AT+CPIN=1439");
}
void loop()
{
 d = Serial1.readString();
 if(d.indexOf("xxxxxxxxx") >=0)
   {
 Serial.println("call is from saved number");
    } else {
       Serial.println("call is not from saved number");
      }
}

```

# Answer
The Arduino Serial class member function `readString()` has a builtin timeout. The function will return on timeout. The default timeout period is 1000 ms. The timeout can be set with `setTimeout()`.

The sketch needs to filter out empty lines (timeout). This can be done by adding a check of the string length. See below for an example of checking:

```
void loop()
{
  String d = Serial1.readString();
  if (d.length() == 0) return;
  Serial.print(d);
  if (d.indexOf("xxxxxxxxx") >= 0) {
    Serial.println(": call is from saved number");
  }
  else {
    Serial.println(": call is not from saved number");
  }
}

```

Cheers!
> 1 votes

---
Tags: arduino-mega, arduino-ide, gsm
---


# Question
Title: nRF24L01 using sender as receiver and vice versa with RF24 library
I have two nRF24L01 modules (I tried 2 with antenna and 2 without antenna) paired with their power base module and connected to two different Arduino Mega 2560 boards. I'm able to send from one module to another up to 32 byte of data and get the acknowledge without any problems. But when I switch them, when I try to send data from receiver and receive it on the sender I have nothing. No data received, no acknowledge sent as response.

As I said before, first part of this code works well, but when it comes to the second part, which is after `delay(1000);` there's silence...

my code is:

**Receiver**

```
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"

// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
const uint64_t pipe02_ = 0xE8E8F0F0A2LL;
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57);
    radio.setPALevel(RF24_PA_LOW);
    radio.enableAckPayload();
    radio.openReadingPipe(1, pipe01_);
    radio.openWritingPipe(pipe02_);
    radio.enableDynamicPayloads();
    radio.startListening();
}

void loop()
{
    if (radio.available())
    {
        char newMessage[33];
        memset(newMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(newMessage, 32);}

        Serial.println("newMessage: " + String((const char*)newMessage));
        delay(1000);
        radio.stopListening();

        char response[32] = "1234567890qwertyuiopasdfghjklzxc";
        radio.write(response, 32);
        unsigned long ack = 0;
        if (radio.isAckPayloadAvailable())
        {
            radio.read(&ack, sizeof(ack));
            Serial.println("ack: " + String(ack));
        }
        radio.startListening();
    }
}

```

**Sender**

```
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"
// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
const uint64_t pipe02_ = 0xA2LL;
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57);
    radio.setPALevel(RF24_PA_LOW);
    radio.enableAckPayload();
    radio.openReadingPipe(2, pipe02_);
    radio.openWritingPipe(pipe01_);
    radio.enableDynamicPayloads();
    radio.stopListening();

    char message[32] = "qwertyuiopasdfghjklzxc1234567890";
    radio.write(message, 32);

    radio.startListening();
}

void loop()
{
    if (radio.available())
    {
        char respMessage[33];
        memset(respMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(respMessage, 32);}

        Serial.println("respMessage: " + String((const char*)respMessage));
    }
}

```

Please help me.

# Answer
> 0 votes
**Update:** It was working yesterday, but today... same thing as with "delay()". What's wrong with these radio-modules??

I have discovered that the `delay()` function was causing this abnormal behavior.

So I have implemented periods instead of `delay()` and now I'm able to switch operating mode between "receiver" and "transmitter". Moreover, I have discovered few additional conditions that must be met (read the comments for the code).

Below is working sample code where transmitter sends some large message. Receiver gets it, waits 2 secs, then responds with another large message and gets the acknowledge for this message:

**Sender**

```
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"
const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //Writing pipe must be full address if acknowledges will be used
const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //At least one of reading pipes must be full adress
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;
RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57); //not necessary. But must be equal at both sides
    radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
    radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
    radio.openReadingPipe(2, pipe02_); //At least one of reading pipes must be full adress
    radio.openWritingPipe(pipe01_); //Writing pipe must be full address if acknowledges will be used
    radio.enableDynamicPayloads(); //If not set, size will be of fixed length. Default fixed length is 32 bytes

    /*Must run this if "startListening()" will be used anywhere in the code below.
    nRF24L01 remembers it's state even if Arduino was restarted*/
    radio.stopListening();
    Serial.println("Sending the message...");
    char message[32] = "qwertyuiopasdfghjklzxc1234567890"; //some test message
    radio.write(message, 32); //Send message over the predefined "writing pipe"

    Serial.println("Waiting for response...");
    radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"

    uint16_t ack = 123;
    radio.writeAckPayload(2, &ack, sizeof(ack)); //Custom ACK payload must be set after "startListening()". Because "startListening()" resets TX buffer
}

void loop()
{
    if (radio.available())
    {
        char respMessage[33];
        memset(respMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(respMessage, 32);}

        Serial.println("respMessage: " + String((const char*)respMessage));
    }
}

```

**Receiver**

```
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"

#define period_  2000

// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //At least one of reading pipes must be full adress
const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //Writing pipe must be full address if acknowledges will be used
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

unsigned long checkPoint = 0;
bool messageReceived = false;
RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57); //not necessary. But must be equal at both sides
    radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
    radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
    radio.openReadingPipe(1, pipe01_); //At least one of reading pipes must be full adress
    radio.openWritingPipe(pipe02_); //Writing pipe must be full address if acknowledges will be used
    radio.enableDynamicPayloads(); //Writing pipe must be full address if acknowledges will be used
    radio.startListening(); //If not set, size will be of fixed length. Default fixed length is 32 bytes
}

void loop()
{
    if (radio.available())
    {
        char newMessage[33];
        memset(newMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(newMessage, 32);}

        Serial.println("newMessage: " + String((const char*)newMessage));
        checkPoint = millis();
        messageReceived = true;
    }

    unsigned long timePassed = millis() - checkPoint;

    //When it receives, controller waits for 2 seconds then sends the response just one time
    if (messageReceived && timePassed > period_)
    {
        messageReceived = false;
        checkPoint = millis();
        Serial.println("sending response...");

        //This must be called before sending anything (except acknowledges)
        radio.stopListening(); //Resets TX buffer and switches radio module's mode to transmitter

        char response[32] = "1234567890qwertyuiopasdfghjklzxc";
        radio.write(response, 32);

        unsigned long ack = 0;
        if (radio.isAckPayloadAvailable())
        {
            radio.read(&ack, sizeof(ack));
            Serial.println("ack received: " + String(ack));
        }

        radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"
    }
}

```

---
Tags: arduino-mega, nrf24l01+
---


title: Arduino library redeclaration error

text:
# Question
Title: Arduino library redeclaration error
This is my first time here and I hope someone can be of help! I'll try to keep it as concise as possible.

So I have two sensors/modules, 1 is an LCD screen from elecrow and another is the DS1307. Both are connected through analog 4 and 5. I tried hooking them up with the help of my breadboard but I've stumbled upon the following issue with the libraries (I don't even know if what I'm trying to achieve is possible but I'm trying nevertheless(and failing horribly while at it))

```
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:31: error: redeclaration of 'OFF'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                   ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:457:5: note: previous declaration 'LCD_SwitchState OFF'
         OFF=0x00,

         ^
    In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:42: error: redeclaration of 'ON'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                              ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:458:5: note: previous declaration 'LCD_SwitchState ON'

         ON=0x01

         ^

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

```

What I make out of this, is that the libraries are conflicting with each other on the following:

* OFF = 0x00
* ON = 0x80
* ON= 0x01

Is there anyway to fix this? I know that I have to edit the .h libraries but I don't know what to change and to what it should be changed, here's the library code on the module itself:

```
// RTC based on the DS1307 chip connected via I2C and the Wire library
enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

class RTC_DS1307 {
public:
   boolean begin(void);
   static void adjust(const DateTime& dt);
   uint8_t isrunning(void);
   static DateTime now();
   static Ds1307SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(Ds1307SqwPinMode mode);
   uint8_t readnvram(uint8_t address);
   void readnvram(uint8_t* buf, uint8_t size, uint8_t address);
   void writenvram(uint8_t address, uint8_t data);
   void writenvram(uint8_t address, uint8_t* buf, uint8_t size);
};

```

Thank you for your help!

C.C

EDIT: I think that I might have come a bit closer. I tried implementing one of the answers and that made me get the following error:

```
    C:\Users\c\Documents\Arduino\libraries\RTClib\RTClib.cpp:284:1: error: 'Ds1307SqwPinMode' does not name a type

 Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() {

 ^

exit status 1
Error compiling for board Arduino/Genuino Uno.

```

That's a whole lot less than before. I will keep this updated!

EDIT 2:

Meanwhile, I tried something entirely else like changing the name of OFF and ON Throughout the RTClib concerning only the DS1307 module. That however gives me an entirely new line of errors such as:

```
error: 'enum Ds1307SqwPinMode' is not a class or a namespace

  RTC_DS1307 Ds1307SqwPinMode::readSqwPinMode() {

                                              ^

```

and:

```
error: could not convert '(Ds1307SqwPinMode)mode' from 'Ds1307SqwPinMode' to 'RTC_DS1307'

   return static_cast<Ds1307SqwPinMode>(mode);

                                            ^

```

These errors in particular only take place in the .cpp library This is where I am stuck now at the moment

# Answer
> 0 votes
**FINAL EDIT WITH SOLUTION:**

I finally stumbled upon the last wall of issues before getting it to work,

1. I redownloaded all the libraries
2. Went to the .h library file of RTClib
3. Changed the variable names from OFF to OFF and on to ONN (it's stupid I know but bear with me)
4. Encounter an entirely new error which seemingly occurs at board version 1.6.23

Error:

> In function 'global constructors keyed to BME280\_LCD\_TIME.o':
>
> lto1.exe: internal compiler error: Segmentation fault
>
> Please submit a full bug report,
>
> with preprocessed source if appropriate.
>
> See http://gcc.gnu.org/bugs.html for instructions.
>
> lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE\_1.8.15.0\_x86\__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status
>
> compilation terminated.
>
> c:/program files/windowsapps/arduinollc.arduinoide\_1.8.15.0\_x86\__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed
>
> collect2.exe: error: ld returned 1 exit status
>
> exit status 1 Error compiling for board Arduino/Genuino Uno.

5. Go to Tools \> Board \> Boards manager
6. I *personally* had to change "**Arduino AVR Boards** by **Arduino** version **1.6.23**" to **version 1.6.21**
7. Compile the code And that should do the trick!

# Answer
> 0 votes
A general rule is to keep definitions such as enum's within the context of the class (library). Below is a possible refactoring:

```
class RTC_DS1307 {
public:
   enum SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

   ...
   static SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(SqwPinMode mode);
   ...
};

```

Cheers!

---
Tags: arduino-uno, sensors, library
---


# Question
Title: I2C communication between Attiny85 as master and arduino UNO as slave
I want to make my Attiny85 and my Arduino UNO communicate together with I2C protocol. Since Attiny do not support Wire library, I use TinyWire by lucullusTheOnly and Wire on the Uno.

The Attiny is sending data as the master to the Uno, the slave.

Here is my code:

**Master**

```
#include <TinyWire.h>

byte slave_address = 10;

void setup() {
    // config TinyWire library for I2C master functionality
    TinyWire.begin();
}

void loop() {
    TinyWire.beginTransmission(slave_address);
    TinyWire.send('c');
    // endTransmission sends the bytes in the buffer to the slave and returns 0 if there was no error
    TinyWire.endTransmission();
    delay(500);
}

```

**Slave**

```
#include <Wire.h>

void setup() {
  Wire.begin(10);                // join i2c bus with address #10
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

```

I connect the pin like this :

```
Arduino --> Attiny
SCL ---- PIN 7
SDA ---- PIN 5

```

I try to pull-up the clock and data line with 2.2k resistors but nothing happened, I receive nothing on the Uno from the Attiny. Any idea ? Thanks !

# Answer
> 1 votes
The pure master functionality of the TinyWire library is currently buggy. As a work around you can initiate the library on the ATTiny also as a slave with an address. When the `endTransmission()` function is called, the library switches temporarily to master mode for sending the bytes. I've tested this with your code in my own setup and it works. (Be sure, that the frequency in the ATTiny is set right. I tested the library only for 8MHz. For my own ATTiny's I had to do an extra step and set the correct fuses with avrdude)

I think the pure master part is blocking itself after the first transmission. I will add an issue in the github project. Maybe I can fix this in some time.

Chrisl aka lucullusTheOnly

EDIT: I had to think about this and looked into the library. The problem was found easily. In `twi.cpp` there is a `NOISE_TESTING` define block in the master send/receive function, which is constantly triggering error #6 (unexpected stop condition). In slave mode this doesn't happen, because directly before sending as a master it calls the master init function, which clears all USI flags, including the stop condition flag, that is polled in the send/receive function.

I have deactivated the `NOISE_TESTING` in the github project. If you don't want to download the current version, you can just open twi.h and comment the definition of `NOISE_TESTING`.

# Answer
> 0 votes
I have the same issue even though I have the latest Github version with the NOISE\_TESTING define block disabled.

I believe it has something to do with the line 359 in TWI.cpp where the stop condition isn't issued if a NACK happens:

```
      if( temp_result.result & (1<<TWI_NACK_BIT) )
  {
    if ( USI_TWI_state.addressMode )
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
    else
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
    return (FALSE);
  }

```

I think it should be :

```
      if( temp_result.result & (1<<TWI_NACK_BIT) )
  {
    if ( USI_TWI_state.addressMode )
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
    else
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
    USI_TWI_Master_Stop();
    return (FALSE);
  }

```

I tried it on ISIS in pure master only and it worked. I don't know if this is a viable solution or if it will cause any conflict with how the rest of the lib works.

---
Tags: arduino-uno, i2c, attiny
---


title: Button for Delay Select

text:
# Question
Title: Button for Delay Select
My target is to make an Arduino system that is able to change modes with different delays by pushing a button. For example, if I pressed the button, it will go into mode 1 with loop 1 that has a 30s delay. If I pressed it one more time, it will go to mode 2 with with loop 2 that has a 1 min delay, etc. The important thing is that mode 1 should be breaked when the push button pressed.

The code below solved part of the problem. However, LEDs are only constant ON, they are not blinking for a certain time then it turned either on-off within the mode when the push button pressed.

```
int b =3;int rl= 5;int gl=6;
int yl=7; int s=0; int o=0;
 int bp =0;

void setup() {
  // put your setup code here, to run once:
pinMode(b,INPUT);
pinMode(rl,OUTPUT);
pinMode(gl,OUTPUT);
pinMode(yl,OUTPUT);

 digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
}

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

bp=digitalRead(b);
if (bp==1){
  delay(50);
  bp=digitalRead(b);
  if (bp==0){
    s=o+1;}}
    else{
      delay(100);}
      switch(s){
        case 1:
        digitalWrite(rl,HIGH);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=s;
break;

case 2 :
digitalWrite(rl,LOW);
digitalWrite(gl,HIGH);
digitalWrite(yl,LOW);
o=s;
break;

case 3:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,HIGH);
o=s;
break;
default:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=0;
break;}}

```

S1 is responsible to activate D12 to be constant ON (when it’s pressed once) which lead UNO2 to be powered then blink the right LED ON (1min) OFF(4Hr), (pressing it twice should turn D12 OFF (optional)). The same thing with S2, when it’s pressed once it should first disable D12 and activate D11 instead, powering UNO3, blinking the left LED ON(30S), OFF (4Hr).

In addition, blinking on() off() repeatedly is needed (unless action break/occur, ex: pressing S1 or S2).

About S1 and S2. The LED on D12 will flash ON for 1 minute then turn off for 4 hours. After the 4 hours, the LED on D12 will flash ON again for 1 min then turn off for 4 hours again & again...as an infinite loop. With S2 The LED on D11 will flash ON for 30 seconds then turn off for 4 hours. After the 4 hours, the LED On D11 will flash ON again for 30 s then turn off for 4 hours again and again as an infinite loop.

# Answer
> 0 votes
In response to your comment on Matej's answer @Ibrahim.M: "I wish I can abbreviate it with only one UNO that able to do the same task by using programming.". You can do this with just one Uno.

I would start by detecting the button presses and debouncing them. This is easy to do using the Bounce2 library. You can use the button presses to start timers which will turn the LEDs On and Off.

**EDIT**

To make an LED flash on and off, and to keep time, you can use the `millis()` function. I started with the BlinkWithoutDelay tutorial, and came up with the following sketch. It only has one timer / LED flasher, but there is enough information in the sketch to figure out how to make the second timer / LED flasher.

```
#include <Bounce2.h>

byte led1State = LOW;
byte timer1Active = 0;
const byte led1Pin = LED_BUILTIN;
const byte buttonPin1 = 6;
const byte buttonPin2 = 7;
unsigned int timer1Counter = 0;
const unsigned long debouncerInterval = 50;
const unsigned long oneSecond = 1000;
unsigned long previousMillis = 0;

Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();

void setup(){
  Serial.begin(9600);
  debouncer.attach(buttonPin1, INPUT_PULLUP);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2, INPUT_PULLUP);
  debouncer2.interval(debouncerInterval);
  pinMode(led1Pin, OUTPUT);
}

void loop(){

  unsigned long currentMillis = millis();

  // 4 hour, 30 second timer.
  if((currentMillis - previousMillis >= oneSecond) && (timer1Active == 1)){
    previousMillis = currentMillis;
    timer1Counter++;
    if(timer1Counter < 31){
      //if(led1State == LOW){
        led1State = HIGH;
      //}
      //else{
        //led1State = LOW;
      //}
      digitalWrite(led1Pin, led1State);
    }
    else if(timer1Counter == 31){
      digitalWrite(led1Pin, LOW);
    }

    // 60 sec X 60 min X 4 hours + 30 seconds.
    if(timer1Counter > 14430){
      timer1Counter = 0;
    }
  }

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      Serial.println("Start 30 second ON, 4 hour OFF timer.");
      timer1Active = 1;
      timer1Counter = 0;
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      Serial.println("Start 1 minute ON, 4 hour OFF timer.");
      timer1Active = 0;
      digitalWrite(led1Pin, LOW);
    }
  }

}

```

Based on this part of your last comment "I’ve a trick! ‘const unsigned long oneSecond = 1000;’ should be edited to ‘const unsigned long oneSecond = 10;’ this make the led be as a constant ON.", it sounds like you want the LED to remain ON constantly for the 30 or 60 seconds. I have "commented out" 5 lines of the above sketch that will make this happen.

# Answer
> 0 votes
Do not use delay but millis(). Example:

```
#define BTN 2
#define MAX_MODE 1   //2 modes

const unsigned int times[] = {1000, 2000};

unsigned int time = times[0];

unsigned long btn_tm = 0;
unsigned long l_time = 0;

byte mode = 0;

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

void loop(){
  if(digitalRead(BTN) == 1 && millis() - btn_tm > 200){
    btn_tm = millis();
    mode ++
    if(mode > MAX_MODE) mode = 0;
    time = times[mode];
 }
  if(millis() - l_time >= time){
    l_time = millis();
    if(mode == 0) Serial.println("mode 0");
    if(mode == 1) Serial.println("mode 1");
 }
}

```

Read it and try it.

---
Tags: timers
---


title: Weird problem with arduino

text:
# Question
Title: Weird problem with arduino
I wrote the code below and the result is not what I expected at all! I'm not sure why it's happening!

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void loop() {
  delay(100);
  Serial.println(sizeof(pat));
  for (int i=0; i<8; i++){
    Serial.print(pat[int(i)],HEX);
  }
  Serial.println("");
  Serial.print(pat[0],HEX);
  Serial.print(pat[1],HEX);
  Serial.print(pat[2],HEX);
  Serial.print(pat[3],HEX);
  Serial.print(pat[4],HEX);
  Serial.print(pat[5],HEX);
  Serial.print(pat[6],HEX);
  Serial.print(pat[7],HEX);
  Serial.println("");
  while(true);
}

```

the output is surprisingly this:

> 8
>
> 008000010
>
> FF0FF0FF0FF66

What is compiler doing in the background but it seems to be messing things up really bad! The loop should be doing the exact same thing as manually writing that code over and over but it's not! How can I fix the loop?

# Answer
If you want to get a value from PROGMEM you must read it with `pgm_read` functions. Read the PROGMEM reference.

```
for (int i = 0; i < 8; i++) {
  Serial.print(pgm_read_byte_near(pat + i),HEX);
}

```

`pat[0]` in `Serial.print(pat[0],HEX);` is an item in a constant array `const uint8_t pat[]`. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without `pgm_read_byte_near`
> 1 votes

---
Tags: debugging, loop, compiler
---


title: Storing hash values from SHA256

text:
# Question
Title: Storing hash values from SHA256
I am using this code and I can not save the output of the hash function to an array of `char`. Can you help me how to do that?

```
#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
  Serial.println();
}

void setup()
{ String FinalStr="1234567890";
Sha256.init();
  Sha256.print(FinalStr);
  printHash(Sha256.result());
}
void loop()
{

}

```

# Answer
This is the code that worked for me:

```
#include "sha256.h"
void setup(void)
{char encoded[64];
    Serial.begin(9600);

    // this is actually the RFC4231 4.3 test

    Sha256.init();
    Sha256.print("123");
    uint8_t * result = Sha256.result();

    Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
    Serial.print(  "Got   : ");
    for (int i = 0; i < 32; i++) {
            Serial.print("0123456789abcdef"[result[i] >> 4]);
            Serial.print("0123456789abcdef"[result[i] & 0xf]);

            for(int i = 0; i < 64; i+=2)
                {
                  encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                  encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                }
    }
    Serial.print("\n");
            for(int z = 0; z < 64; z++)
            Serial.print(encoded[z]);
}

void loop(void)
{}

```
> 1 votes

# Answer
Save to a character vector (64 characters + NULL):

```
void copyHash(char* buf, uint8_t* hash) {
  int i, j = 0;
  for (i = 0; i < 32; i++) {
    buf[j++] = "0123456789abcdef"[hash[i]>>4];
    buf[j++] = "0123456789abcdef"[hash[i]&0xf];
  }
  buf[j] = 0;
}

void setup()
{
  String FinalStr="1234567890";
  Sha256.init();
  Sha256.print(FinalStr);
  char buf[65];
  copyHash(buf, Sha256.result());
}

```

Cheers!
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Recommendations for 24V to 5V AC/DC converter
I'm working on an ESP8266 thermostat that should be powered by the 24V AC from the furnace. I'm looking for a converter to 5V DC that would be small enough to fit in a smaller enclosure and not dissipate too much heat. Not fully sure about the current, but I'm planning for up to 500 mA for short periods of time. I found on ebay this, but it accepts input from 85V upwards. What would happen if I would feed 24V AC to it? Would it still work. Or alternatively doesn anyone have a link for something similar that would work with 24V?

# Answer
Transformers for furnaces are typically Class 2 transformers, energy limited. Unloaded, or lightly loaded, they produce a significantly higher output voltage than the rated output voltage, 24 volts in this case. 28 volts is typical, and it may be higher during high line situation. The 24 volt rating is a loaded voltage, with a resistive load.

28rms x 1.4 = 39.2 volts

You should be using a regulator with a voltage rating of at least 40 volts, and that is really marginal.

https://www.aliexpress.com/item/1pcs-2018-new-dc-dc-converter-12V-24V-36V-48V-60V-72V-to-5V-0-5A/32922897633.html

The AC-DC converter you linked to would not work. It has a low voltage cutout. It also would not be able to provide the power if it was able to work at the lower voltage. The input current would be much higher than the normal input current at a normal line voltage.
> 1 votes

# Answer
24VAC rectified with a full diode bridge rectifier (4 diodes) becomes 36VDC when smoothed with a cap, the datasheet indicates this part would be okay with that. You'd probably be okay as you're planning \<500mA output most of the time.

https://www.digikey.com/product-detail/en/murata-power-solutions-inc/OKI-78SR-5-1.5-W36-C/811-2196-5-ND/2259781
> -1 votes

---
Tags: esp8266, power
---


title: Arduino Code 'Bug'

text:
# Question
Title: Arduino Code 'Bug'
I'm sharing my code.. The problem I am facing is that the code performs all the functions that are to be called except showing the MAX30100 (for heart rate) readings. I have tried this code using statement switches,cases, if-else but couldn't figure out. Can anyone help me out regarding this?

```
    unsigned long runGSR() {

total = total - readings[index];         // subtract the last reading:

 readings[index] = analogRead(inputPin);  // read from the sensor:

  delay(100);

  total = total + readings[index];       // add the reading to the total:

  index = index + 1;                     // advance to the next position in the

array:

  if (index >= numReadings)               //when the end of the array is reached

    index = 0;                           // wrapped around to the beginning:

  average = total / numReadings;           // calculate the average:

  return average;       // send it to the computer as ASCII digits

    }
    void ambtemp()

    {

       reading = analogRead(A2);       //takes the reading from analogue pin 2

  tempVolts = reading * 5.0 / 1024.0;   //converts the readings to volts

  ambitemp = tempVolts / 0.01;        //output voltage /10 millivolts = 1 degree
C

  Serial.print(",Ambient Temp:");      //prints ambient temperature in serial monitor

  Serial.println(ambitemp);

  delay(10);

    }

    void hbt()    //Function for heart rate (MAX30100) in which I am having problem
    {
        do
        {
            pox.update(); // Make sure to call update as fast as possible
            if (millis() - tsLastReport > REPORTING_PERIOD_MS) {   //the loop repeats every second
            lcd.clear();
            Serial.print("HR:");
            Serial.println(pox.getHeartRate()); //prints Heart rate on LCD
            delay(100);
            ambtemp();    //calls the ambient temperature function
            gsr = runGSR();   //calls the GSR sensor function
            delay(100);
            tsLastReport = millis();
        }

```

# Answer
> 1 votes
I assume you use this as source for your code:

This means that:

```
#include "MAX30100_PulseOximeter.h"
PulseOximeter pox;

```

Your issue is that the line:

```
Serial.println(pox.getHeartRate()); //prints Heart rate on LCD

```

Does not actually print anything on the LCD. It only shows the value on the serial.

Try using `lcd.print()`

---
Tags: arduino-uno, code-review
---


title: Connecting NodeMCU through internet

text:
# Question
Title: Connecting NodeMCU through internet
I have a NodeMCU and a website (free website domain provided by http://www.hpage.com) and I have to send and receive some data (suppose a 8bit number) from the website to the NodeMCU via internet. The NodeMCU is connected to internet through WiFi hotspot of an Android phone.

* Can anyone provide an example code? How can I address the NodeMCU from the website?
* Does the NodeMCU need to be a server or just a client?

Thanks in advance for kind help.

# Answer
> 0 votes
> How can I address the NodeMCU from the website?

You can't. The NodeMcu is behind the phone, behind a router, behind a gateway of the operator etc. It can access the Internet over the infrastructure routing it out, but is not visible from the Internet.

> Does the NodeMCU need to be a server or just a client?

The device should be a client and open the communication to the server by sending a request and renewing the connection if it times out. You can use WebSockets or MQTT or similar framework.

---
Tags: esp8266, nodemcu, http, networking
---


# Question
Title: Is this a good way to filter noise due to vibration in limit switch?
I have a circuit connected as follows

my limit switches which are attached to my structure sometimes gets falsely triggered, so I wrote this code to address it. My motor is supposed to go down skip the up limit switch at first hit the down one then go back to the up one. is this a good way to implement it? https://pastebin.com/qVU1Gp0q

```
//Switch pressed ->  reading HIGH
//Switch not pressed -> reading LOW
//Motor direction 0 is down, 1 is up

const int uplimit = 32;
const int downlimit = 34;
const int motorspeed = 9;
const int motordirection = 28;
//const int pumpspeed=5;
//const int pumpdirection=6;
const int motorenable = 26;
//const int pumpenable=;
int Finishedcleaning = 0;
int Reachedup = 0;
int Motorinitialsetup = 0;
int Motorsecondsetup = 0;
int downfiltered = 0;
int upfiltered = 0;
void setup() {
  // put your setup code here, to run once:

  pinMode(motorspeed, OUTPUT);
  pinMode(motordirection, OUTPUT);
  pinMode(motorenable, OUTPUT);
  //pinMode(pumpspeed, OUTPUT);
  //pinMode(pumpenable, OUTPUT);
  pinMode(uplimit, INPUT);
  pinMode(downlimit, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int average1 = 0;
  int average2 = 0;
  if (Motorinitialsetup == 0 ) // to be run before hitting initial switch
  { digitalWrite(motorenable, HIGH);
    analogWrite(motorspeed, 190);
    digitalWrite(motordirection, 0); // Bring motor down
    //   digitalWrite(pumpenable,HIGH);
    //  digitalWrite(pumpdirection,1);
    // analogWrite(pumpspeed,240);
    Motorinitialsetup = 1; //so this if statement does not run again

  }

  for (int i = 1; i < 100; i++)
  { downfiltered = digitalRead(downlimit);
    average1 = average1 + downfiltered;
  }
  average1 = average1 / 100;

  if ((average1 > 0.9) && Finishedcleaning == 0 ) // Function after hitting down switch
  {
    delay(1000); // wait until motor cross switch
    analogWrite(motorspeed, 0); // stop motor
    Finishedcleaning = 1; //indicate cleaning is over for next loop
    delay(500); // wait until motor cross switch
  }

  if ( (Finishedcleaning == 1) &&   (Reachedup == 0)  && (Motorsecondsetup == 0))
  {
    digitalWrite(motordirection, 1); // reverse motor direction
    analogWrite(motorspeed, 190); // start motor again
    Motorsecondsetup = 1;
  }

  if ( Motorsecondsetup == 1) // only checks switch up switch after motors comes back
  {

    for (int i = 1; i < 300; i++)
    { upfiltered = digitalRead(downlimit);
      average2 = average2 + downfiltered;

    }
    average2 = average2 / 300;
    if ((average2 > 0.9) && (Finishedcleaning == 1)) // Stop Motor after returning
    { analogWrite(motorspeed, 0);
      delay(1000);
      Reachedup = 1; // indicate finished returning after cleaning cycle
    }
  }
}

```

# Answer
> 1 votes
**Hardware:**

You have the switch at 5V with a pull down resistor.
When using longer wires or when everything is put into a box, it might be safer to have a GND wire to the switch (with a pull up resistor) instead of a 5V wire. When a switch or button is connected with a shielded cable, it can also be better to connect one pin of the switch to GND.

If you change the switch and connect one pin to GND with pullup resistor, then you have to change the sketch as well, because the pin will become LOW when the switch is pressed.

You may add a capacitor of 1 nF to 100 nF between the digital input and GND. That will help against spikes and noise.

The pull down resistors of 4k7 is a high value for a noisy environment. I suggest to use 470 Ω or 1k resistors.

The **ground path** is very important. You have the GND of the motor driver connected to the breadboard and that is also where the switches are connected. That means the input (switches) and the output (motor driver) share a piece of ground wire. Always avoid such situations.
Breadboards have often bad contacts. If the GND to the breadboard is not very solid, then you are injecting the input pins with noise from the output pins of the Arduino board.
Use two seperate breadboards for input and output. Or connect the GND of the motor driver directly to the Arduino board.

**Software:**

An integer can not be 0.9, therefor your filter does not work.

The function `digitalRead()` returns HIGH or LOW. You add those values, but I prefer to stick with HIGH or LOW.

Taking multiple samples and have a threshold is a good idea. Do you really need 100 or 300 samples? A button may bounce for 10 ms, so I suggest to use about 20 samples during 20 ms.

```
int digitalReadFiltered(int pin) {
  int result;
  const int n = 20;                // maximum 30
  int count = 0;                   // an integer can hold 30 analog samples

  for (int i = 0; i < n; i++) {
    if (digitalRead(pin) == HIGH) {
      count++;
    }
    delay(1);        // 1 ms for sampling during 20 ms with 20 samples
  }

  if (count > (n / 2)) {
    result = HIGH;   // counted enough HIGH values
  } else {
    result = LOW;
  }

  return(result);
}

```

---

In short, **a pull down (or pull up) resistor** with a low value makes the circuit low impedance, and the electrical noise will have less influence.

When a button is pressed, that connects the digital input pin of the Arduino board directly to 5V (or GND). Then it is almost impossible that electrical noise can get to that pin.

When a button is not pressed, then the resistor keeps the input pin low (or high). Then electrical noise can cause spikes.

A circuit with low impedance is less influenced by the electrical noise. The lower the value of the resistor, the less troubles with noise.

It is not something that can be calculated, see it as electrical/capacitive/electromagnetic/radio-noise combined with bad ground currents from a wrong ground path. What is the best way to receive that? With a high impedance circuit of course.

A pull down (or pull up) resistor with a value of 10k can be used when there are no wires connected to it that are going outside the circuit board. When there is a button with wires, then I would suggest a lower value, for example 2k2 or 4k7. Since you have troubles with noise, I suggest a value of 470 Ω or 1k.

---
Tags: arduino-mega, switch
---


# Question
Title: Does baud rate for HC-05 Bluetooth module need to match the Serial Monitor?
I have this sketch that I got as a sample. I have the two HC-05s connected. What I type in one serial monitor shows up on the other, but as question marks. The most common reason for this I find is baud rate doesn't match. I didn't change the baud rate on the HC-05s when I got them, so I assume they are set to default. I can put them in command mode and ensure the baud rate is set.

Does the baud rate of the HC-05s have to match the baud rate of the Serial monitor? I would assume not. I am also wondering if this is a problem with formatting a char\[\] when writing to the serial display.

```
#include <SoftwareSerial.h>
SoftwareSerial BTserial(7, 8); // RX | TX
// Connect the HC-05 TX to Arduino pin 7 RX.
// Connect the HC-05 RX to Arduino pin  8 TX through a voltage divider.
//

char c = ' ';

void setup()
{
Serial.begin(9600);
Serial.println("Arduino is ready");
Serial.println("Remember to select Both NL & CR in the serial monitor");

// HC-05 default serial speed for AT mode is 38400
BTserial.begin(38400);
}

void loop()
{

// Keep reading from HC-05 and send to Arduino Serial Monitor
if (BTserial.available())
{
    c = BTserial.read();
    Serial.println(c);
}

// Keep reading from Arduino Serial Monitor and send to HC-05
if (Serial.available())
{
    c =  Serial.read();
    BTserial.write(c);
}
}

```

# Answer
No, they do not need to match.

You are talking about two separate serial port connections.

The baud rate between the HC-05 and the Arduino (BTserial) has to match.

The baud rate between the Arduino and your PC (Serial) has to match.

BTserial and Serial can use different baud rates.

An overflow problem can arise if a lot of data arrives from the HC-05 and there is not enough memory to store it until it can be forwarded to Serial.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: bluetooth, hc-05
---


# Question
Title: Creating an array of structures which store bitmaps to work with u8glib
I've tried reading the documentations and I'm getting desperate because I can't find anything.

I need to create an array of structures, which contains a bitmap stored in `PROGMEM` space (because of issues with memory usage).

The bitmaps are created as follows:

```
const uint8_t pat[] PROGMEM = {
...
};

```

Then I need to create a structure like this:

```
typedef struct{
    uint8_t bitmap[8];
} chars;

chars allChars[1];

```

but the compiler doesn't like that for some reason and spit out a bunch on invalid conversion from const to char so it was clear I couldn't use that! My next attempt was to create a pointer to the pattern like so:

```
typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

```

This time it again gave warnings about invalid conversion but at least compiled! I then tried to write the entire code and run it:

```
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void draw(void) {
  u8g.drawBitmapP( 37, 28, 1, 8, pat);
  u8g.drawBitmapP( 74, 28, 1, 8, (char*) allChars[0].bitmap);
}

void setup(void) {
  allChars[0]= (chars) {*pat};
}

void loop(void) {
  draw();
  while(true);
}

```

the first line where I have used the pattern directly in the draw function, works perfectly fine, but the second line which retrieves the value from the pointer draws some weird noise shape (I'm guessing memory dump of an address or something)!

Is it even possible to create a struct with one of the variables being just a pointer to the constants that I have defined earlier? I'm pretty sure I'm doing something very wrong as I'm not familiar with using pointers and addresses and whatnot, so it would be great if someone could help with these issues!

# Answer
> 1 votes
That still wouldn't solve the issue with struct! I think I have found a glitch in GCC compiler where if you define your struct in dynamic memory rather than PROGMEM, even if you use a buffer and fetch the data using memcpy\_P, it will return the correct value while printing, but when you copy it again to allChars\[0\].bitmap , the wrong value is copied! the thing that solved the issue was adding PROGMEM to the struct like below:

```
typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

```

I have not yet encountered any compilers that are this specific and don't even allow transfer between memory spaces correctly. (Not to mention other issues with GCC linker that are brought up by david from eevblog like stack overflow without warning, etc). They really need to solve issues like this as this compiler is one of the most frequently used on different platforms.

anyways, here is the final code if anyone finds it useful (I will probably end up making a youtube video about it later):

```
#include "U8glib.h"
//U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

chars allChars[1];

const unsigned char pat[] PROGMEM = {
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x0f, 0xff, 0x00,  //....%%%%%%%%%%%%.....
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x0f, 0xff, 0x80,  //....%%%%%%%%%%%%%....
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
};

void charToBitmap(int x, int y, char chr){
  for(unsigned int i=0; i<sizeof(allChars);i++){
    if (allChars[i].ascii=chr){
      u8g.drawBitmapP( x, y, allChars[i].size[0], allChars[i].size[1], allChars[i].bitmap);
      break;
    }
  }
}

void draw(void) {
  charToBitmap(0,0,'0');
}

void setup(void) {
  allChars[0] = (chars) {48,{3,54},pat};
}

void loop(void) {
    u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}

```

# Answer
> 0 votes
You're making it far too hard on yourself.

All you need is a single 2-dimensional array of data in PROGMEM:

```
const uint8_t bitmaps[10][8] PROGMEM = {
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
};

```

Each row is a bitmap, and there are 10 rows, so 10 bitmaps (I have them all the same at the moment).

Then you just reference the slice number you are interested in:

```
u8g.drawBitmapP( 100, 30, 1, 8, bitmaps[3]);

```

Note: I haven't tested this.

---
Tags: programming, array, pointer, struct
---


# Question
Title: How to convert a delimited string of hex numbers to an int array
I am sending a string to the Arduino via serial, I made the program that sends the data, so I can change it to anything, but for now it sends a string of hex numbers delimited by ':', so for example 00:AA:FF and I need to get that into an int array onto the Arduino, the main problem is I don't always know how big the array will be, sometimes just 2 indexes, other times 16 indexes.

As I said, I made the program sending the data so I can make the data anything, I just need to get an int array to the Arduino and get it back as an int array via serial

# Answer
You could store the hex numbers in a `int array` using strtok() and strtol().

```
char str[] = "00:AA:FF:7FFF";
int intArray[16]; // Maximum number of hex numbers.

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char * pch = strtok(str, ":");

  while(pch != NULL){
    intArray[counter] = strtol(pch, NULL, 16);
    pch = strtok(NULL, ":");
    counter++;
  }
  Serial.print("Item Count = ");
  Serial.println(counter);

  for(int i = 0; i < counter; i++){
    Serial.println(intArray[i]);
  }

}

void loop(){}

```
> 1 votes

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


title: Emit region-neutral keyboard signals

text:
# Question
Title: Emit region-neutral keyboard signals
The `Keyboard` API allows the Arduino boards such as the Micro or Leonardo to emit USB signals mimicking a physical keyboard. However, the signal seems to transmit key strokes and not characters which means that machines with different region settings interpret the USB signal differently. For example, a `y` will be interpreted as `z` in a German OS since the keyboard layout has these keys swapped.

Is there any way to output a signal that will result in the correct character being transmitted regardless of the OS settings *without any modifications to the machine the Arduino is attached to*?

# Answer
No. There is no such facility.

If you take a German keyboard and plug it into a US configured computer the key layout will be wrong. You have to tell the computer that you're using a German keyboard.

Keyboards don't know what is printed on the keycaps. All they understand is where the buttons are physically located.

The same with the Arduino. It's sending the keypresses that correspond to the keyboard layout of a US keyboard, and you have to tell the computer that you're using a US keyboard - because that is effectively what you are using.

If you want to change the keyboard map the Arduino uses you will have to manually modify the Keyboard library (file `Keyboard.cpp`, array `_asciimap[128]`).
> 3 votes

# Answer
Download `Device Class Definition for Human Interface Devices (HID)`

https://www.usb.org/sites/default/files/documents/hid1\_11.pdf

See section 6.2.1 HID Descriptor

`bCountryCode 0x09` German

also see section E.4 (page 67)

```
E.4 HID Descriptor (Keyboard)
Part            Offset/Size  Description                                         Sample
                (Bytes)                                                          Value
----------------------------------------------------------------------------------------
bLength           0/1        Size of this descriptor in bytes.                    0x09
bDescriptorType   1/1        HID descriptor type (assigned by USB).               0x21
bcdHID            2/2        HID Class Specification release number
                             in binarycoded decimal—for example, 2.10 is 0x210).  0x101
bCountryCode      4/1        Hardware target country.                             0x00
bNumDescriptors   5/1        Number of HID class descriptors to follow.           0x01
bDescriptorType   6/1        Report descriptor type.                              0x22
wDescriptorLength 7/2        Total length of Report descriptor.                   0x3F

```
> 3 votes

---
Tags: usb, arduino-micro, keyboard
---