title: ESP8266 as ISP program for ATMega16

text:
# Question
Title: ESP8266 as ISP program for ATMega16
I have used below program for ESP8266 as ISP to upload a program to an ATmega16.

**ISP program uploaded in ESP8266**

```
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ESP8266AVRISP.h>

const uint8_t reset_pin = 5;
const uint16_t port = 328;

ESP8266AVRISP avrprog(port, reset_pin);

void setup() {
    Serial.begin(9600);//115200
    Serial.println("");
    Serial.println("Arduino AVR-ISP over TCP");
    avrprog.setReset(false); // let the AVR run

    // listen for avrdudes
    avrprog.begin();
}

void loop() {
    static AVRISPState_t last_state = AVRISP_STATE_IDLE;
    AVRISPState_t new_state = avrprog.update();
    if (last_state != new_state) {
        switch (new_state) {
            case AVRISP_STATE_IDLE: {
                Serial.printf("[AVRISP] now idle\r\n");
                Serial.println("idle...");
                // Use the SPI bus for other purposes
                break;
            }
            case AVRISP_STATE_PENDING: {
                Serial.printf("[AVRISP] connection pending\r\n");
                Serial.println("pending...");
                // Clean up your other purposes and prepare for programming mode
                break;
            }
            case AVRISP_STATE_ACTIVE: {
                Serial.printf("[AVRISP] programming mode\r\n");
                Serial.println("Active...");
                // Stand by for completion
                break;
            }
        }
        last_state = new_state;
    }else{
      Serial.println("newstate not equal to old");
    }
    // Serve the client
    if (last_state != AVRISP_STATE_IDLE) {
        avrprog.serve();
        Serial.println("serve..");
    }
}

```

Then I have changed the board to ATmega16 and used programmer as `AVR ISP` and fetched/written below simple blink program to upload in ATmega16.

```
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(1, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  Serial.println("light on");
  digitalWrite(1, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
  Serial.println("light off...");
}

```

Tried uploading blink program to ATmega16 using ESP8266 as ISP by **Sketch =\>Upload Using Programmer**. This resulted to compilation followed by uploading status in Arduino IDE for longer period. I didn't get any response after 10 mins of time. Then i have tried opening Serial Monitor which shows `newstate not equal to old`.

I am not sure what went wrong in my coding? How can I debug this issue ?

# Answer
### 1. Uploading the sketch to your ESP8266

* Tools \> Board \> select the appropriate ESP8266 board
* File \> Examples \> ESP8266AVRISP \> Arduino\_Wifi\_AVRISP
* Change lines 7 and 8 to match the SSID and password of your WiFi router
* Sketch \> Upload
* After the upload completes unplug the ESP8266 from your computer.

### 2. Generating the .hex file and the upload command

* Open the sketch you want to upload to your ATmega16
* Tools \> Board \> ATmega16
* File \> Preferences \> Show verbose output during: \> upload (check)
* Sketch \> Upload
* The sketch will compile and then the upload will fail. This is the expected behavior. The goal of this process is to generate the .hex file that will be uploaded and the correct upload command.
* Scroll the black console window at the bottom of the Arduino IDE window up until you see a line that looks something like:

\>

```
E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM54 -b115200 -D -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

```

### 3. Connecting the ESP8266 to the ATmega16

Connect the ESP8266 to your ATmega16 board as follows:

```
+----------+-----------+
| ESP8266  | ATmega16  |
+----------+-----------+
| GPIO12   | MISO      |
| GPIO13   | MOSI      |
| GPIO14   | SCK       |
| GPIO5    | RESET     |
+----------+-----------+

```

You also need to power the ATmega16. It is recommended to use 3.3 V since this is what the ESP8266 is running at. Make sure the ground of the ESP8266 is connected to the ground of the ATmega16.

### 4. Starting the ESP8266AVRISP

* Plug the ESP8266's USB cable back in to your computer
* Tools \> Serial Monitor
* Select 115200 from the baud rate menu in the bottom right corner of Serial Monitor
* You should see something like

> IP address: 192.168.0.100
> Use your avrdude: avrdude -c arduino -p -P net:192.168.0.100:3000 -t # or -U ...

### 5. Uploading via ESP8266AVRISP

* The second line you saw in the Serial Monitor in step 4 is the sketch's attempt to give you the AVRDUDE command you need to run to upload to your ATmega16 via the ESP8266AVRISP. Unfortunately they got a bit vague at the end. Apparently they are trying to steer you towards using AVRDUDE in terminal mode via the `-t` option but also mentioning that `-U` might be preferred. I recommend the latter since the Arduino IDE has helpfully generated the `-U` command for you already.
* Since you need to run a custom AVRDUDE command to upload to your ATmega16 over the network you will not be able to do the upload via the Arduino IDE. Start the command line on your computer.
* Now you need to merge the upload command you generated when you did the intentionally failed upload to the ATmega16 in step 2 with the command that was printed to Serial Monitor in step 4. In my examples, this merged command would be:

\>

```
E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -c arduino -p atmega16 -P net:192.168.0.100:3000 -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

```
* Your command will be similar to mine but the path to avrdude, avrdude.conf, the IP address, port, and path to the .hex file will be different. Enter your merged AVRDUDE command at the command line.
* The upload should now proceed successfully.

### Comments

The above is quite a complex process. Although it will be significantly easier with subsequent uploads, it will likely still not be as easy as an upload via the Arduino IDE. I would not recommend regularly using the ESP8266 as an AVR ISP simply because it's what you have on hand. Instead I would strongly recommend you to just buy a cheap (~$3 USD with free shipping from China) 6 pin USBasp from eBay.

The primary benefit of using the ESP8266 for this application is that it can be done over the WiFi network rather than the traditional USB connection but it's questionable how often that will truly be useful.
> 8 votes

---
Tags: esp8266, isp
---


# Question
Title: Arduino for kids toy with Battery (safe), Can Arduino overheat the Battery with long running code
I am making a learning toy which kids can play with and learn basics of programming. But i am tired of keep replacing the AA batteries as they run out in few days. So i am thinking of using rechargeable battery. But i am very worried to use it considering it is kids toy and people says lipo and li ion battery can explode. There are dangers or over charge and heat etc.

**Is it safe to use them? Which one to use?**

I am using **Arduino pro mini** 3.3v and some times 5v.

I was planning to use: XCSOURCE 5 pcs 1A 5V Micro USB TP4056 Lithium Battery Power Charger Board Module TE420

I think some users have misunderstood the question and have voted this question to be closed. This questions is very much to deal with programming also apologies if i have not made it clear.

* We can get the battery level in the code, but is there any way in code we can some how turn off the charging when the battery has been fully charged.
* I am under impression (might be wrong, you can correct me), normal
battery single AA cell dies after some time on heavy use (using dc motor etc). But
rechargeable batteries are bigger with multiple cells in it they will last longer. So if i am running some code in a loop for long time
will the battery get over heated will it be a problem.

# Answer
> 2 votes
Probably the easiest/cheapest and safest option is to buy a original USB Power Bank and there you have it. Power banks for cellphones/tablets have overvoltage/overcharge/undercharge protection on them and they are also completely sealed, so it should be perfectly safe to handle one of those to your kids (Of couse not some cheap chinese crap).

They can then charge the power bank over USB on any PC or Wall charger and then use it for hours/days.

If I'm allowed to give you a tip, you could eventually pick one of these here, they are pretty good in my opinion.  Of course there are a ton of others around, so you can just pick one which fit your needs.

On your case you just cut a USB cable and plug the ends on the Pro Mini. If a short is detected, Power banks often just shut off and only turn on when they are charged again (You might try this first). If you use a 3.3V Pro Mini, just put a voltage limiter between it. You might also write "3.3V" on the voltage limitor and "3.3V" on the 3.3V version of the Arduino and teach your kids that if the Arduino has "3.3V" written on it, they should put that "3.3V" voltage limitor before it (or just not use 3.3V variants for ease of use).

---
Tags: arduino-nano, arduino-pro-mini, battery, arduino-pro-micro, lipo
---


# Question
Title: Error while uploading code to ESP8266 through Arduino Mega 2560
I am sorry for posting this question for the nth time but I am still not able to find a solution for this error.

I am trying to upload the WiFiScan(Arduino IDE example program)program code to ESP8266 using Arduino Mega 2560. I followed the procedure given here. And I tried uploading it with "Generic ESP8266 Module" and "Adafruit HUZZAH ESP8266" selected as the Board. But I am still getting the following error.

```
trying to connect
  espcomm_send_command: sending command header
  espcomm_send_command: sending command payload
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

```

Edited to add:

**Connections-**

**ESP8266 - Arduino Mega2560**

Tx - Tx1(Pin 18)

Rx - Rx1(Pin 19)

Gnd - Gnd

Vcc - 3.3V (Directly from Arduino's 3.3V pin)

CH\_PD - 3.3V (Directly from Arduino's 3.3V pin)

GPIO0 - Push button K2 (refer photo)

RST - Push button K1

While pressing the K2 button(Flash button - GPIO0), I clicked the K1 button(Reset button - RST) and then released K2. According to the document, this should bring the ESP8266 to flash mode. Now when I upload the code, it throws the above error.

# Answer
> 1 votes
After googling for several hours, I was able to figure out the reason. Thanks to this link. Transferring data to ESP8266 with Arduino acting as USB to Serial converter did not work. Using a USB to TTL converter, and following this link you can easily transfer data to ESP8266.

---
Tags: arduino-mega, arduino-ide, esp8266, uploading, wireless
---


# Question
Title: Arduino Micro serial communication is not working after wake from power down
I'm trying to use the power down state for a battery application, but I'm having issues with the serial communication.

I'm using the `lowpower.h` library to put the Arduino Micro into power down mode.

When it wakes I flash an LED, which is working, so I know it's is waking up. And I also re-establish serial communication and send a message. This is not working. I receive nothing on the serial monitor, however the TX LED does flash.

I think the Arduino may be working correctly, but for some reason the serial monitor can't handle it. Perhaps there is a better serial monitor application?

```
#include "LowPower.h"

void setup()
{
    //20sec delay added to make uploading easier (cant upload in power down state)
    Serial.begin(115200);
    Serial.println("20");
    delay(5000);
    Serial.println("15");
    delay(5000);
    Serial.println("10");
    delay(5000);
    Serial.println("5");
    delay(5000);
    Serial.println("START");
    pinMode(LED_BUILTIN, OUTPUT);
    delay(1000);
    Serial.end();
}

void loop()
{
    // Enter power down state for 8 s with ADC and BOD module disabled
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

    Serial.begin(115200);
    delay(100);
    Serial.println("BLINK");
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(5000);                       // wait for a second
    Serial.println("BLINK_stop");
    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
    delay(5000);                       // wait for a second

    Serial.end();

}

```

Serial monitor output:

```
20
15
10
5
START

```

and then nothing...

# Answer
> 1 votes
I found the answer on this related question: Starting usb on pro micro after deep sleep (ATmega32u4)

Which itself was a link to a sparkfun forum

Note: it requires you to close and open the serial monitor at proper timings.

```
// disable the USB prior going to sleep
USBCON |= _BV(FRZCLK);  //freeze USB clock
PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
USBCON &= ~_BV(USBE);   // disable USB

// and wake it up after
//routine to properly wake up
sleep_disable();
delay(100);
USBDevice.attach(); // keep this
delay(100);
Serial.begin(9600);
delay(100);

```

---
Tags: serial, arduino-micro, sleep, atmega32u4
---


title: BMP 280 exact Altimeter readings

text:
# Question
Title: BMP 280 exact Altimeter readings
I was just going through this pressure sensor tutorial.

What I want to know is how can I set the exact altimeter in my readings depending upon my different geographical place ? or may be if I am attaching the sensor to my balloon.

# Answer
> 3 votes
The tutorial sample source code has the line:

```
Serial.print(bmp.readAltitude(1013.25)); // this should be adjusted to your local forcase

```

That `1013.25` value should be the local pressure at sea level in hundreds of Pa. If want to show altitude above ground level, you will need to know that for your location and write your code to calculate the altitude offset.

The sensor can't know location -- it only measures pressure. The AdaFruit library provides the altitude conversion, but being generic, it relies on several assumptions.

---
Tags: arduino-uno
---


title: OLED on Hardware SPI, on DUE

text:
# Question
Title: OLED on Hardware SPI, on DUE
I want to use an OLED with DUE. I plan to connect it via hardware SPI. The Due has a 3X2 pin connector labeled SPI. Is it here where i connect the SCK and MOSI?

If indeed, i connect it here, then which one is SCK and which one is MOSI?

Most importantly, i saw somewhere that in the DUE, hardware digital pin 13 is SCK and pin 11 is MOSI? Is this true? Because if it is, i can simply hook it up to these pins and get rid of the confusing 3X2 pin connector.

# Answer
> 1 votes
It doesn't look like it's true. There is only one `SPI` module and it has fixed pins which are not duplicated anywhere.

However there are three instances of `USART` which can be used in synchronous mode as `SPI`:

* **`USART0`**: `RXD0`(`PA10`) / `TXD0`(`PA11`) / `SCK0`(`PA17`)
* **`USART1`**: `RXD1`(`PA12`) / `TXD1`(`PA13`) / `SCK1`(`PA16`)
* **`USART2`**: `RXD2`(`PB21`) / `TXD2`(`PB20`) / `SCK2`(`PB24`)

Whole table from SAM3X datasheet:

But I'm not sure if the `Arduino IDE` supports this mode, or you'll have to do it from scratch by yourself.

You can even use `RTS` as select slave signal:

---
Tags: arduino-due, spi, display
---


# Question
Title: Rotate Robot head according to Sound level
I'm currently working on a robot using an Arduino and I'd like to control robot's head like this:

Imagine that it is on your desk and it can turn it's head through a range of 150 degrees like a human can do. So if I tap the desk in the the middle position, relative to his head rotation (in front of the robot), it should rotate his head by 75 degrees if he was looking at the left or right.

Likewise, I want to locate the desk tap or another sound source and make his head turn to that direction.

So in order to do that I have a solution, but I'm not confident enough to use it because I don't know whether is will give accurate results. This is what I thought:

I'll place two sound modules on the left and right sides of the robot. When a sound comes, I'll measure which microphone detects the higher sound level, and calculate an approximate angle to rotate the robot's head accordingly.

However, since I'm a newbie to Arduino, I've no real sense of whether that will work as I intend. Do people think this is a good method? If not, how can I improve it?

Also if you can, please suggest some good, Arduino compatible sound modules for this project. Thank you.

# Answer
> 2 votes
A couple of years ago, I completed a MOOC on FUN called Binaural Hearing for Robots (it doesn't seem to have run since, but it may be worth keeping an eye on it to see if they open registration again. At least some of the resources seem to be archived here). Interestingly, localising sound turns out to be easier with three microphones than with two.

You scan the three inputs in sequence, and when the sound is directed to record the time-difference between the three sensors. The technique you're looking at to localise the source is called trilateration.

Once you have a direction relative to the robot head, you can use a simple servo to turn the robot head to that direction.

I did play around with this a little bit, using three KY-038 microphone modules like this that I picked up cheap on eBay:

Connect them to your Arduino something like this:

---

I can't find my code (it was pretty untidy anyway since I was just playing around while I was working on the course), but a lot of Arduino sound-localisation projects have been published online with examples easy to find on Instructables, Hackaday, and many other sites.

---
Tags: arduino-mega, robotics, sound
---


# Question
Title: How do I deal with this Arduino IDE installation error?
I am using Linux Fedora 20 (yes I am going to upgrade it, definitely, soon) and I have installed arduino-1.8.0, but I get this message ...

> Your copy of the IDE is installed in a subfolder of your sketchbook. Please move the IDE to another folder

... when I click on the desktop icon, or run ./arduino. I have tried moving the tar.xz file to its own folder `ArduinIDE` again installed it but get the same message. Please,what should I do to get out of this? Please no answers like "just do what it says":in that case what do I move, and what criteria does the destination need to have?

# Answer
Delete (or edit) your `preferences.txt` file - it most likely has your sketchbook folder set to your home directory.

You may find it in `~/.arduino15` for the "real" Arduino IDE, or in (I think) `~/.arduino` for the arduino.org one.

Unless you have a specific reason for wanting to run 1.8.0, which is actually 1.0.6 re-numbered, you should be using the version from arduino.cc which is currently 1.6.13.
> 4 votes

# Answer
This is still happening. The exception message is not clear. It is objecting to being installed in "the same folder as your sketchbook", not in a "subfolder of the sketchbook". It should ideally read...

> Your copy of the IDE is installed in the **parent** folder of your sketchbook. Please move the IDE to another folder.

You should be able to put side by side versions in /opt or create another branch in your home folder.
> 0 votes

---
Tags: arduino-ide, installation
---


title: Photoresistor and another switch

text:
# Question
Title: Photoresistor and another switch
I am using the circuit diagram below to turn ON/OFF the lights using Photo-resistor.

How can I use the Arduino to bypass the Photoresistor effect? Let say I want to turn ON the lights even though Photoresistor doesn't want to.

**Take note the 12V source** is required by the LED. Knowing that Arduino must work with **max 5V**.

# Answer
You could replace the circuit with these:

* Use one Arduino analog input to measure the light.
* Use a Digital Out (Preferable PWM) to control the LED.

Then you can apply whatever logic you want.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

# Answer
Be careful with the 12V, the Arduino can not handle 12V at its pins.

The input can be the photoresistor with a resistor to 5V (not to 12V). Use a analog input to measure the amount of light.

The output can be with a resistor to the base of the transistor.
This is an example: PighiXXX transistor
Any unused digital output can be used.
Why do you need 12V for the led ? Is it a special led ?
> 0 votes

# Answer
There are several ways to add Arduino control; the question doesn't provide quite enough information to say which is best.

One of the simplest methods is to use a diode to clamp the transistor's base voltage to at most 5 V, as shown in the following diagram. The voltage at the IO pin cannot exceed 5 V plus one diode drop.

With this circuit, setting the IO pin to be an input leaves the LED under photoresistor control. Setting the IO pin as a low output turns off Q1, and setting it as a high output turns on Q1. Note, R3 should limit the current drawn from the IO pin to at most about 25 mA, so 150 to 200 Ω may be suitable.
> 0 votes

---
Tags: switch, photoresistor
---


# Question
Title: Arduino - fuse setting problem on ATmega328P-PU
I am trying to do fuse setting on ATmega328P-PU chips using an avr programmer.

I was successfully able to do fuse setting on 3 ATmega328P-PU chips (which I bought from one of the sites - I forgot). So I bought three more from Amazon.

When I execute `avrdude -c usbasp -p m328p` on the previous 3 chips, I got this response, and was able to do fuse setting.

> avrdude: warning: cannot set sck period. please check for usbasp firmware update. avrdude: AVR device initialized and ready to accept instructions
>
> Reading | ################################################## | 100% 0.00s
>
> avrdude: Device signature = 0x1e950f (probably m328p)
>
> avrdude: safemode: Fuses OK (E:FF, H:D9, L:E2)
>
> avrdude done. Thank you.

But when I execute the same command on the 3 chips I recently bought, I am getting this.

```
avrdude -c usbasp -p m328p

avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

```

I triple-checked the wiring and soldering area. They all look fine.

Is this because the 3 chips I recently bought have a bootloader?

The description for the chip that works is here.

# Answer
> 2 votes
The chips configured with a bootloader would also have the fuses set for an external clock (the factory default is the on-chip oscillator). Without an external clock they won't work.

I have a sketch that uploads files that also can provide an external clock for this eventuality.

As mentioned on that page an 8 MHz clock is provided on pin D8 of the programming board, so you can connect to D8 on the Uno which you are running the sketch on to pin 9 on the actual Atmega328P chip.

Alternatively find a 16 MHz crystal or resonator and connect that between pins 9 and 10 of your Atmega328P which will provide the clock that it is expecting. If you use a crystal you should also run 22 pF capacitors between each leg and ground, like in this image:

---
Tags: arduino-uno, atmega328
---


# Question
Title: How can I wire a 12V LED switch so that it is powered, but my Arduino only receives a 5V signal?
My arduino is powered by 12V. I am getting some cool looking 12V led switches from amazon, but they need 12 volts to light up. My arduino will perform an override function when it detects the switch is closed. the digital pins can only handle 5V. How can I step down the 12V signal that powers the switch to the 5V that the pin can handle.

12V supply -\> 12V led switch -\> reduce 12V to 5V -\> arduino digital pin

# Answer
You need a voltage divider:

The formula is:

V1 = 12V

R2 = 5V max

R1 = The rest (V1-R2)

And then you have to calculate max current. If you use 1/4watt resistors, you have to convert watt to current, P = U x I.

Pmax = 0,25W

R1volt = 7 volt

Imax for R1 = P/U = 0.25/7

Imax for R2= P/U = 0.25/5

Now you have the current and voltage for R1 and R2

And the relation between R1 and R2 is:

R1 = 7/12 x Rtotal

R2 = 5/12 x Rtotal

Rtotal = R1 + R2

simulate this circuit – Schematic created using CircuitLab
> 4 votes

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


# Question
Title: Alternate between 2 relays with one button
I have a very basic programming knowledge, but the thing I want to achieve is to alternate between switching 2 relays with a button or a RPi input pulse.

So something like this:

1. Press the button
2. Switch relay 1 on and off (1 second delay)
3. Press the button
4. Switch relay 2 on and off
5. Press the button
6. Switch relay 1 on and off (1 second delay)
7. Press the button
8. Switch relay 2 on and off
9. Press the button
10. Switch relay 1 on and off (1 second delay)
11. Press the button
12. Switch relay 2 on and off
13. etc.

Here's my code, I thought if I'd just put the second relay after the first `else` everything would work. But I'm missing some basic knowledge to figure this out.

```
const int ledPin = 2;
const int ledPinA = 3;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(ledPinA, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
  if (sensorValue > 500) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
  if (sensorValue > 500) {
    digitalWrite(ledPinA, HIGH);
  } else {
    digitalWrite(ledPinA, LOW);
  }
}

```

I'm thinking I should use `while`.

# Answer
> 0 votes
> So something like this:

easy:

1. increment a counter based on button presses;
2. run a state machine on that counter to decide on relay actions.

the state machine can be a simple switch / case statement.

# Answer
> 1 votes
The way you have it, both `if` blocks will be evaluated each time you call to `loop()`. Instead, you need to create a variable that remains "alive" in between each call to `loop()` to keep track of which relay you want to activate:

```
const int ledPin = 2;
const int ledPinA = 3;
int active_relay = 2;   // State variable for current relay pin

void setup() {
    pinMode(ledPin, OUTPUT);
    pinMode(ledPinA, OUTPUT);
    Serial.begin(9600);
}

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

      Serial.println(sensorValue);

      delay(1);    // This delays for 1ms, not 1s ??

      if (sensorValue > 500) {   // Pulse received
          digitalWrite(active_relay, HIGH);  // Relay on
          delay(1000);                       // Wait 1 second
          digitalWrite(active_relay, LOW);   // Relay off

          // Update variable for next call to loop
          if (active_relay == ledPin) {
              active_relay = ledPinA;      // Swap
          }
          else {
              active_relay = ledPin;       // Swap
          }
      }
      // Remove 2nd if block
}

```

---
Tags: relay
---


# Question
Title: Use Arduino Uno digital pins instead of ESP8266
I would like to know if this is possible.

I am using an ESP8266-ESP01, which only has 2 digital pins. I have a project that needs 3 digital pins so I have planned to use my Arduino, so I can use more digital pins. My plan is instead of plugging the sensor in the GPIO1 of the ESP8266, I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266 and be uploaded to an online cloud.

I can read the sensor data in the Arduino but I don't know how to transfer the data to the ESP8266 so the wifi module would just receive it and send it to the online cloud.

If anyone can help me to get some idea specifically on sending the data from Arduino to the ESP and receiving the data from the Arduino.

Thank you.

# Answer
DDA's answer is perfectly correct. Like he says you need to check the voltage and use a logic level shifter.

However looking at it from another angle there are a whole range of ESP that have an increasing number of digital pins. You could look at using an ESP-5, or an ESP-12E, these have different forms and increasing number of digital pins.

You could also look at the Wemos range, I believe there is an UNO form board and there is the Wemos D1-Mini, which has 10 digital and 1 analog.

Running on two boards is usually more of an issue than running on one board, god help you if you have synchronisation issues!
> 4 votes

# Answer
Use the ESP's two digital pins to talk to the Arduino using SoftwareSerial. Be careful however: your Arduino (possibly, probably) runs on 5V, the ESP on 3.3V. I have an Arduino clone that can be switched between 3.3V and 5V, which makes things easier.

After that all you need is to send the sensor readings to the ESP via SoftwareSerial.
> 2 votes

# Answer
> I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266

Easy:

1. Program the Arduino as a master (I2C, or UART + interrupt) and the ESP as a slave. Connect the sensors to it. Once the data is read on the Arduino, it is sent to the ESP.
2. Put an I2C IO expander IC on the ESP and you don't have to deal with the Arduino at all.
> 0 votes

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


title: Power Measurement

text:
# Question
Title: Power Measurement
I am trying to develop a system that reads the amount of power consumption from my load. Here is how my setup looks like;

The led represents a 5W and 12V light bulb(I was unable to get this in my simulator) and the battery i am using is 9 volts Here is my code;

```
 sens = analogRead(A0);
 vol = sens * (2.0) * ( 5.0 / 1024.0);
 tot_vol = 5 - vol;
 current = vol / 10;
 power = current * tot_vol;
 Serial.print(power);
 Serial.print ("\n");
 delay(1000);
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
state = Serial.read(); // Reads the data from the serial port
}
if (state == '0') {
 digitalWrite(ledPin, LOW); // Turn LED OFF
 state = 0;
}
else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 state = 0;
 }
}

```

I am trying to calculate the voltage drop across my resistor and then get the current and then power from that. This data is sent to an android app via the bluetooth module. However, here is the output i am getting;

What am i doing wrong?

# Answer
A number of things wrong:

1. You have no ground connection to the Arduino. It can't work out what the voltage you are measuring is relative to. (Read this)
2. You should have the shunt resistor as the absolute last item in your chain of components so it is connected directly to ground (V+ -\> LED -\> LED's Resistor -\> Relay -\> Shunt Resistor -\> GND
3. Your shunt resistor should be as low as you can get away with - low enough that it doesn't affect the circuit, yet high enough that you can measure a voltage drop. For that you need to first have a good idea about what level of current you will be measuring.

simulate this circuit – Schematic created using CircuitLab
> 0 votes

# Answer
Normally the shunt resistor (in you schema 220 ohm) is way lower than the load it should measure, 12volt/5Watt = 0.42 Amp and R = U/I, 9V/0,42A = 21ohm. So your 220ohm's shunt is inflicting on the measurement value.

So to change the current measurement circuit you have to use a low ohm resistor and since the voltage drop over a shunt/low ohm resistor is small you need a amplifier.

Here is a page about how to calculate a shunt and use it with Arduino: http://www.vwlowen.co.uk/arduino/current/current.htm

If we use a simplified version, 8v over the lamp and 1volt over the shunt.

U = I x R

Rlamp = 21 ohm

Ilamp = 8 volt/21 ohm

Rshunt = U/I = 1 volt/0.42 Amp
> 1 votes

---
Tags: arduino-uno, c, electronics
---


title: Time Library Adjust Default on Windows

text:
# Question
Title: Time Library Adjust Default on Windows
Looking at this Time Arduino library because I would like to send time stamps with data across my HC05-PC channel.

https://playground.arduino.cc/Code/Time

I wrote this function to get the time at any point

```
String getTime() {
    String timeSecond = String(second());
    String timeMinute = String(minute());
    String timeHour = String(hour());
    String timeDay = String(day());
    String timeMonth = String(month());
    String timeYear = String(year());

    String now = timeHour + ":" + timeMinute + ":" + timeSecond + " " +
        timeMonth + "/" + timeDay + "/" + timeYear;

    return now;
}

```

It seems in the docs he provides info on how to set the default time on a Linux/Unix system so that this library will always be grabbing the correct time by editing some bash files.

When I run the function, having been compiled on Windows, it begins running on 1/1/1970 0:0:0.

He does not provide any documentation for setting the Windows time stamp. How would I go about doing that?

# Answer
> 0 votes
The Adafruit RTClib has a function to use the compiler date and time. You use the TimeLib maintained by Paul Stoffregen. That library does not have such a function, but you can write it yourself. For example with sscanf and setTime. Without external RTC that will only work if you upload a sketch and keep the Arduino always on. I have a clock like that, and since that clock is always on, I never had the need to add a RTC chip. When the Arduino resets, it returns to the date and time when it was compiled.

If you use a Arduino Due or Zero or M0 then they have their own rtc library.

If you want the computer to send the date and time, then you could make a command and send that via the serial port or via Bluetooth.

What kind of date and time do you want ? The local time, including the offset of the Daylight Saving Time ? That is possible, but not easy to make on a Arduino with RTC chip, in that case it is easier to send a command from the computer with the newest date and time.

It that function okay ? The object 'now' disappeares when the function ends, and yet you return that object.

---
Tags: c++, time
---


# Question
Title: Convert string into char array in Arduino?
I am not that great at Arduino and C++ yet, but I'll give this a shot:

I have a char array that looks like this:

```
char PROGMEM bitmap[] = {0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE};

```

However, I receive this char array from a string, which is basically:

```
String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE";

```

How do I turn my `input` variable with a comma separated char array into the actual array? I need it to be fast and not use a lot of memory. I haven't been able to find a use case like this, because it's very unique.

I feel like this should be super simple to do, but I can't wrap my head around it.

Things I've tried and didn't understand that much:

**1:**

```
char delimiter[] = ",";

char* ptr = strtok_r(text, delimiter);

while (ptr != NULL) {
  Serial.println(ptr);
  ptr = strtok_r(NULL, delimiter);
}

```

> cannot convert 'String' to 'char\*' for argument '1' to 'char\* strtok(char\*, const char\*)'

**2:**

```
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
int i = 0;
char bitmap[115];
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = str;
  i++;
}
Serial.println(bitmap);

```

(the total length of my characters are 4799 and the total length of hexadecimals are 114, so I'm just trying something here)

Error: Apparently you can't use `=`?

**3:**

```
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  Serial.println(str);
}

```

This actually prints the strings to the console, but trying to add them to a char array is still a mystery I am trying to solve right as I write this.

**4:**

```
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
char *ptr;
char bitmap[115];
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, &ptr, 16);
  i++;
}

Serial.println(bitmap);

```

I'm getting a lot closer now. `strtol(str, &ptr, 16)` actually gives me the right integers I need, but it seems like my Arduino crashes when I run this code. It simply reboots it. Error:

> assertion "heap != NULL && "free() target pointer is outside heap areas"" failed: file "/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/heap/./heap\_caps.c", line 171, function: heap\_caps\_free abort() was called at PC 0x4011c173 on core 1

# Answer
> 1 votes
So after a lot of help and some tweaking, I finally got it to work!

```
String text = server.arg(0);

char buf[text.length()];
text.toCharArray(buf, text.length());
char *p = buf;
char *str;
char bitmap[960]; //960 is fixed for now, need to count amount of commas + 1
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, NULL, 16);
  i++;
}

```

`bitmap` now contains all the XBM data from the GET request. I ran into some issues, causing the device to restart, because I accidentally forgot that the length of the bitmap array isn't 114 (that's the amount of horizontal pixels of the display). This caused it to overflow by a lot.

Huge thanks to jose can u c for helping me.

# Answer
> 0 votes
You note you can easily use `strtok()` to get individual strings of the text representation of the hex values. So now all you need is to convert the string `"0xD7"` or similar into the **number** `0xD7`.

Have a look at `strtol()` function to perform that task.

# Answer
> 0 votes
When dealing with string containing values separated by comma (or any other *special* character), you use the function `strtok` to *parse* the string. That means, separate each value.

The mechanics is:

* In the first call you indicate the string to parse and the delimiters. That calls return a pointer to the first token found.
* After that, you keep calling the same way, but passing NULL as the string to parse.
* When the call returns a NULL, you are done.

Here is how you do it:

```
void setup()

{
Serial.begin(9600);

String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE,0x0,0x1,0xFF,0x10,0x2";
char *pch;

Serial.print("Splitting string '");
Serial.print(input);
Serial.println("' into tokens:\n");
// --- Start the strtok scan
pch = strtok((char *) input.c_str(),",");

// --- Cycle thru each comma separated hex value.
while(pch != NULL) {
    //  pch poinst to a string representation of an hex value.
    Serial.print(pch);
    Serial.print(" ->");
    //  convert string to value.
    char *p = pch + 2;        // Skip "0x"
    int val = hex2dec(*p++);  // Convert first hex digit.

    if(*p) {  // Convert an optional second hex digit.
        val = val * 16 + hex2dec(*p);
    }

    Serial.println(val, HEX); // Print the value to check.
    //  Next hex value
    pch = strtok(NULL, ",");
}
}

/*
 * Convert a hex digit to decimal.
 */
int hex2dec(char d)
{
    int val = 0;

    if(isDigit(d)) {
        val = (d - '0');
    } else {
        val = 10 + (toupper(d) - 'A');
    }

    return val;
}

```

---
Tags: programming, array
---


title: Programming a servo on an ATtiny85

text:
# Question
Title: Programming a servo on an ATtiny85
Board: "ATtiny25/45/85"

Processor: "ATtiny85"

Clock: "Internal 1 MHz"

Programmer: "Arduino as ISP"

I want to run a servo forwards and backwards on an ATtiny85. The servo library is not compatible with the ATtiny85 so I had to write code from scratch. At this point, the code that makes the servo go forwards (clockwise) is:

```
void setup() {
  pinMode(PB1, OUTPUT);
}

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  // 1 millisecond determines the servo going forwards
  digitalWrite(PB1, LOW);
  delay(19);
}

```

And the code that makes the servo go backwards (anti-clockwise) is simply by changing the amount of microseconds to:

```
delayMicroseconds(2000);

```

I want to have the servo motor go forwards one cycle for a few seconds and then go backwards for a few. I want this to keep looping. At this point my code is:

```
void setup() {
  pinMode(PB1, OUTPUT);
}

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(19);
}

```

This however just makes the servo go back and forward at the same spot forever. I do realise I might need a for loop for this but I am confused as how I will do this.

# Answer
The servo can't move back and forward in 40 milliseconds. It'll be more like tremble between both.

Try something like this:

```
// keep sending 0 position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
}

// keep sending second position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(18);
}

```
> 2 votes

---
Tags: arduino-uno, attiny, attiny85
---


title: Variables displayed incorrectly

text:
# Question
Title: Variables displayed incorrectly
I am making a keypad and when I try to save the buttons that were pushed they reset back to zero.

```
int tmp = 1;
int digit = 1;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int code = 0;

void setup() {
  Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  if (digit > 4) {
    digit = 1;
  }
  for (int i = 2; i <= 7; i++) {
    int tmp = digitalRead(i);
    if (tmp == HIGH) {
      if (digit == 1) {
        int a = i - 1;
      }
      if (digit == 2) {
        int b = i - 1;
      }
      if (digit == 3) {
        int c = i - 1;
      }
      if (digit == 4) {
        int d = i - 1;
        Serial.print(a);
        Serial.print(b);
        Serial.print(c);
        Serial.print(d);
        digitalWrite(8, HIGH);
      }
      digitalWrite(9, HIGH);
      delay(100);
      digitalWrite(9, LOW);
      delay(100);
      Serial.print(i);
      digit++;
    }
  }
}

```

# Answer
Do you know what `int a;` does?

For example you have a global variable `a` and then you have local `a`. Local one hides global one.

In all cases you're changing local variables. Then you're printing global `a`,`b`,`c` and local `d`.
> 3 votes

---
Tags: arduino-uno, button, variables
---


title: Odd Serial behavior with Uno

text:
# Question
Title: Odd Serial behavior with Uno
I'm not understanding what's going on with my Uno. I have a very simple piece of code. no peripherals are connected. Just a bare genuine uno. I program in VisualMicro for Visual Studio.

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

    char stringy[9] = { 0x7E, 0x00, 0x05, 0x08, 0x01, 0x44, 0x33, 0x04, 0x7B };

    for (int i = 0; i < 9; i++) {

        Serial.print(stringy[i]);
        //delay(300);
    }

    Serial.println("");
    Serial.print("done");
}

void loop()
{
    while (1) {  }
}

```

Without a delay of around 250msec or greater in the for loop, I don't get all the characters. In fact, without the delay, the code doesn't even finish executing. I only get the first character '~'. It doesn't seem to matter what my baud rate is.

This code runs fine without a delay on my Nano. What could possibly be the issue?

# Answer
You are printing the unprintable.

Do you think it should print:

```
~0581,34{

```

or

```
0x7E 0x00 0x05 0x08 0x01 0x44 0x33 0x04 0x7B

```

What you will get is

```
tilde
null
enquiry
backspace
start of heading
comma
three
end of transmission
open brace

```

I think you can call

```
Serial.print(stringy[i], HEX);

```

To see the number you put in come out.
> 1 votes

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


title: Where to use "static volatile bool"?

text:
# Question
Title: Where to use "static volatile bool"?
Why in the piece of code below we use "static volatile bool"?

```
static volatile bool wifi_connected = false;

```

taken from here: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino

# Answer
> 5 votes
`static` means that the global will only be accessible inside the current translation unit.

`volatile` means that `while(!wifi_connected){/*...*/}` cannot be optimized to `if(!wifi_connected)while(true){/*...*/}`

These things are orthogonal. So you would use static volatile when you need both properties.

---
Tags: programming
---


# Question
Title: Protothread Library Stalling on One Thread
I am trying to use a protothreading library found here

http://harteware.blogspot.com/2010/11/protothread-powerfull-library.html

to perform protothreading with my Arduino so I can "simultaneously" read from the HC-05 Bluetooth chip input to receive information from the master computer which I am connected to over Bluetooth while also processing and transmitting data from the sensors over Bluetooth.

My code looks like this

```
/*
    This module uses the L293D chip to modulate and power
    two DC motors controlling the wheels of the FryeBot
*/

#include <Time-1.5.0\Time.h>
#include <WiShield\pt.h>

/*L293D INPUT 7*/
const int YELLOW_GEAR_MOTOR_BACK = 8;

/*L293D INPUT 2*/
const int YELLOW_GEAR_MOTOR_FORWARD = 9;

/*L293D INPUT 10*/
const int RED_GEAR_MOTOR_BACK = 10;

/*L293D INPUT 15*/
const int RED_GEAR_MOTOR_FORWARD = 11;

/*
    Establish ratio os the rate of the faster slower gear
    to the faster gear to scale the duty cycle of the
    faster gear
*/
const float RED_GEAR_SPEED_TO_YELLOW = 0.97;

/*Constant for full duty cycle for analogWrite*/
const int FULL_ANALOG_MOTOR_SPEED = 255;

/* HC05 Setup Data */
const int pingPin = 7;
const int HC05PowerPin = 2;

/* Distance data */
long duration, cm;

/* Values for Bluetooth RX/TX */
char buf[25];

char current;
String messageHolder;
String message;

/* Protothreads */
static struct pt pt1, pt2;

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

    /* add setup code here */
    pinMode(YELLOW_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(YELLOW_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(HC05PowerPin, OUTPUT);

    PT_INIT(&pt1);
    PT_INIT(&pt2);

}

static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        collectAndTransmitData();
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
    }

    PT_END(pt);
}

void collectAndTransmitData() {
    digitalWrite(HC05PowerPin, HIGH);

    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);

    cm = microsecondsToCentimeters(duration);

    Serial.print("TX: ");
    Serial.print(cm);
    Serial.println();

    if (message.indexOf("G") > 0) {

        analogWrite(YELLOW_GEAR_MOTOR_FORWARD, (int)(RED_GEAR_SPEED_TO_YELLOW * (float)FULL_ANALOG_MOTOR_SPEED));
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, HIGH);
    }
    else if (message.indexOf("S") > 0) {
        digitalWrite(YELLOW_GEAR_MOTOR_FORWARD, 0);
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, LOW);
    }

    /* Load the distance value into a buffer */
    String sendValue = String(cm);
    sendValue.toCharArray(buf, sizeof(buf));

    /* Write the buffer with a space after for parsing*/
    Serial1.write(buf);
    Serial1.write(' ');
}

long microsecondsToCentimeters(long microseconds) {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the
    // object we take half of the distance travelled.
    return microseconds / 29 / 2;
}

static int protothreadReadAndParseData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        readAndParseData();
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
    }

    PT_END(pt);
}

void readAndParseData() {
    Serial.println("HERE");
    current = Serial1.read();
    Serial.print("RX: ");
    Serial.print(current);
    Serial.println();

    if (current == ' ') {
        message = messageHolder;
        messageHolder = "";
        Serial.print("message: ");
        Serial.print(message);
        Serial.println();
    }
    else {
        messageHolder += current;
    }
}

void loop() {
    Serial.println("A");
    protothreadReadAndParseData(&pt2, 20); // by calling them infinitely
    Serial.println("B");
    protothreadCollectAndTransmitData(&pt1, 20); // schedule the two protothreads
}

```

The code prints the following in the console when executed.

```
A
HERE
RX: �
B
TX: 522
TX: 524
TX: 524
TX: 524
TX: 524
TX: 524

```

Then continues with TX: ### forever.

I am not sure why the code is not looping back to the first function or at least running it a second time. I am not very clear on exactly how to use this library or who maintains it. The docs on their Github page for their WiShield library which this pt.h is part of are not overly helpful. If you have any experience with other Arduino protothreading libraries let me know so I might try them out. I am not sure where I went wrong with this library in my implementation.

Here is the repo containing the package I am using

https://github.com/nicolaskruchten/arduino/tree/master/libraries/WiShield

# Answer
> 1 votes
In `protothreadCollectAndTransmitData` you have a `timestamp` variable that never gets updated:

```
static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;   // <- This never changes
    ....

```

When the condition is `true` you will need to update `timestamp = millis();`.

```
static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
        // Updated. Move this here, else it ALWAYS gets called!
        collectAndTransmitData();
        timestamp = millis();   // <- Update timestamp for next time
    }

    PT_END(pt);
}

```

But to make sure that is correct, you should look at the macro:

```
#define PT_WAIT_UNTIL(pt, condition) \
do {                                 \
    LC_SET((pt)->lc);                \
    if(!(condition)) {               \
        return PT_WAITING;           \
    }                                \
} while(0)

```

(You can ignore the `do/while` \- that's just there so you can use a semi-colon.) As you can see, when the condition is `false` a `return` is issued. So it looks like it is safe to do it this way.

Disclaimer: I've never used this threading library. I'm working off of the source code I found here: https://github.com/fernandomalmeida/protothreads-arduino/blob/master/pt.h

---
Tags: programming, c++, bluetooth, hc-05, threads
---


# Question
Title: Receive an array of characters using SIM900 module
I tried to receive an array of characters using SIM900, but I couldn't. I can receive just one character like `'G'`, but I want to receive a string `"abcd"`. When I used `char*` to save the SMS, I failed.

Does anyone know how?

My code:

```
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
    pinMode(3,OUTPUT);
    Serial.begin(19200); // for serial monitor
    SIM900.begin(19200); // for GSM shield
    SIM900power(); // turn on shield
    delay(20000); // give time to log on to network. `
    SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
    delay(100);
    SIM900.print("AT+CNMI=2,2,0,0,0\r");
    // blurt out contents of new SMS upon receipt to the GSM shield's serial out
    delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button24
{
    digitalWrite(9, HIGH);
    delay(1000);
    digitalWrite(9, LOW);
    delay(7000);
}

void loop()
{
    // Now we simply display any text that the GSM shield sends out on the serial monitor
    if(SIM900.available() >0)
    {
        char *in = SIM900.read();
        if (in =="abcd") digitalWrite(3,HIGH);
        if (in == "00") digitalWrite(3,LOW);
    }
}

```

# Answer
> 0 votes
It solved . I used another library that manipulated . And just support sim900 U can get it in this below link and include to your arduino IDE This library written by digispark group

# Answer
> 0 votes
```
#use this code and then inform me"
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
    pinMode(3,OUTPUT);
    Serial.begin(19200); // for serial monitor
    SIM900.begin(19200); // for GSM shield
    SIM900power(); // turn on shield
    delay(20000); // give time to log on to network. `
    SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
    SIM900.write(0x22);
    SIM900.write(0x0D);
    SIM900.write(0x0A);
    delay(100);
    SIM900.print("AT+CNMI=2,2,0,0,0\r");
    // blurt out contents of new SMS upon receipt to the GSM shield's serial out
    delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button24
{
    digitalWrite(9, HIGH);
    delay(1000);
    digitalWrite(9, LOW);
    delay(7000);
}

void loop()
{
    // Now we simply display any text that the GSM shield sends out on the serial monitor
    if(SIM900.available() >0)
    {
        char *in = SIM900.read();
        if (in =="abcd") digitalWrite(3,HIGH);
        if (in == "00") digitalWrite(3,LOW);
    }
}

```

---
Tags: arduino-uno, arduino-ide, c++, gsm, pointer
---


# Question
Title: WS2812 (?) RGB LED matrix turns on white
I have an RGB LED 8x8 matrix which is claimed to consist of WS2812. When turning it on, it automatically lights up all LEDs white with full brightness. The LEDs even light up without DIN being connected. I remember reading something about this behaviour and I think it was related to the LEDs being SK6812 or similar rather than WS2812, but I can't find this page anymore, nor anything else describing this behaviour.

My question is, how can I disable the LEDs lighting up when turning power on? Of course I could add some kind of relay to switch them on right before the signal is sent by the Arduino, but is there something simpler?

# Answer
Use a MOSFET to control the matrix power line and activate the MOSFET only a few milliseconds before turning off your LEDs: this way the few millis intercurring between power on and off control signal will not be noticeable and will reduce the current bootstrap consumption.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: led
---


# Question
Title: DS18B20 setting resolution without addressing
As i understand the dallas library, there are two ways of referencing the sensor, one is to refer to the address, and the other is just to grab it as it is indexed.(gettempbyindex)

I want to know how to set the resolution of the sensor when i'm using the gettempbyindex method, all the examples i can find seem to only set resolution when specifying the address explicitly..

Is it even possible?

# Answer
> 1 votes
You can use getAddress: `bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index)`

If you want to set the resolution for all devices, you can just use `void DallasTemperature::setResolution(uint8_t newResolution)`. (It will call getAddress for all indices.)

---
Tags: esp8266, ds18b20
---


# Question
Title: How can i build mouseless technology with arduino?
I want to build mouseless technology with arduino as shown in this link

Can anyone tell me how to approach this with arduino? Or what can be the logic behind it?

# Answer
Your question is far far far too broad. No one is going to come here, post all the electrical schematics you need, all the code you need, and walk you through step by step. That's not how this works. The stack exchange requires that the poster make some effort to make progress in thier project before posting specific problems they are having.

That being said I will say that what you want to achieve is not possible on only an arduino. The method you posted in the video requires a lot of image processing to track the blobs. This is not something a microcontroller such as the arduino can achieve. A more powerful Intel based device may have some potential for your project but I doubt it.

I once did image processing with the raspberry pi. The pi itself is still not powerful enough to perform real time image processing to a good level, however it's a possibility that it could work (my image processing was more complicated than processing a binary image and tracking dots).

The ideal solution for you would be to do exactly what this guy has done. Build an application on a laptop or desktop computer which has enough power for the image processing. I suggest taking this route first even if downscaling to a raspberry pi is possible in the future, it will introduce you to image processing, and at least you know that it CAN work, as there is a working example.

Look up OpenCV if you havnt already, download, build it, follow tutorials and start from there! Then I think you should aim to build an application that tracks white objects in the frame. And that would be your first step to completion.
> 1 votes

---
Tags: arduino-uno, arduino-mega, robotics
---


# Question
Title: Vin and Ground pins shorting only under specific conditions
So I have an Arduino Nano that I think might have gone bad. The Vin and ground pins are shorting (I'm checking continuity with a multimeter). But it only shorts when:

* The Arduino has power
* The red lead of the multimeter is on ground and the black is on Vin (not the other way around)

I've tried checking with the leads both ways (red to ground as well as red to vin) while both on and off, and with two different multimeters, one of which is brand new. Completely at a loss for words because this isn't really how physics is supposed to work (continuity shouldn't depend on lead orientation from the multimeter or whether the circuit is powered, right?). Any insight would be appreciated. Do I have a bad board?

# Answer
> But it only shorts when: The Arduino has power

You **must not** use a continuity checker or ohm meter on a powered circuit.

Not only will it not work, you risk damaging the meter.

It's also not necessarily safe to use such a meter on an unpowered active electronic circuit like an IC or eval board, as the meter must apply a small amount of power to the circuit to make a measurement - how much power varies between meters and settings, and how much a circuit can tolerate in an unintended way depends on things like polarity and the state of other parts of the circuit. However, it is common practice to do so - especially for example when there's a fear that the device might already be damaged.
> 1 votes

# Answer
It is not clear from your question what you are measuring with the multimeter (volts, ohms, amps etc.) but if you are using the ohms scale when your Nano device is not connected to the power, your multimeter charging capacitors on the board and reversing the leads will then cause a discharge through the multimeter, maybe giving a reading which leads you to believe there is a short circuit.
> 0 votes

# Answer
Also if you have this setup and set it to measure Amp, then it will effectively shortcut the leads with as small resistace as mutltimeter can.

Also check, if those connectors (usually crocodiles) cannot touch something they should not (each other mainly)
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: Is it possible for Arduino firmware to recognise only one computer?
Is it possible to adjust the Arduino firmware to recognise only one PC computer? On other computers it would show driver not recognised or driver not found.

E.g.: My computer should see the Arduino normally, and it should not work if I connect the same arduino to other computers.

# Answer
No.

However, it is possible to place unusual and/or secret requirements on the computer's drivers or application software - however those software components could be present on multiple computers unless you also take measures to node lock them.

* You could customize the USB VID/PID and descriptors, causing the device not to be recognized by a usual driver
* You could alter the behavior of the USB interface (or bootloader and sketch) to require unusual operations - either obscure, or even secret to the level of unique-per-unit cryptography
* Or most simply, you could just use a board without a USB interface and bring your own. Especially if you lock the flash, there's not a whole lot others can do except entirely erase your work and be left with an unusually expensive ATmega evaluation board.

Do note also that most operating systems make it possible to easily intercept the raw USB traffic going to/from devices, so someone who can see it in operation can learn a lot about how it is working.

If you want to play games with odd USB implementations, you'll probably do better with a direct USB board like a Leonardo - and you will certainly want to have an ISP setup to recover it, as your efforts will no doubt break it many times before you get something on there which works as intended.
> 2 votes

---
Tags: arduino-uno, firmware
---


title: Arduino with nRF24L01

text:
# Question
Title: Arduino with nRF24L01
I am using nRF24L01 with Arduino Nano and Mini. I feel they are very useful when we want to connect multiple Arduinos together.

In market we can buy Arduino with WiFi and Bluetooth, why don't they make Arduino model with nRF24L01? Is there any specific valid reason?

Or am I wrong in using nRF24L01 and there is a better cost and power efficient way to connect multiple Arduinos together wirelessly?

# Answer
NordicRF (the company behind nRF24L01) has released two series of SoC devices that are compatible with nRF24: NRF51 and NRF52. Thanks to the effort by Sandeep Mistry and other contributors, they can be programmed using the Arduino IDE and libraries. Instructions are available here: https://github.com/sandeepmistry/arduino-nRF5

I have tested NRF51822, which is the cheapest variant (costing slightly more than Arduino Pro Mini + NRF24L01+ but in a single small and power-efficient package) and it works great.

The BBC Micro:bit is based on NRF51. More information is available at https://forum.mysensors.org/topic/9722/bbc-micro-bit-and-mysensors-a-great-match

Compared to the Atmega328-based Arduino Pro Mini, NRF51822 has 8x larger flash and 8x larger RAM. It also has Bluetooth 5 and BLE support and a 32-bit ARM Cortex M0 CPU.

There is also this alternative: https://www.ebid.net/eu/for-sale/arduino-ide-compatible-controller-with-the-nordic-nrf24l01-radio-transceiver-156695123.htm

Specifications:

* Dimensions 59mm x 18mm
* The Nordic nRF24L01+ 2.4 GHz Radio transceiver on board
* Supply voltage up to 6.5 Volts
* The Digital and Analog pins are 5 volts
* ATMega328P frequency is 8 Mhz
* 4 battery connector pins
* FTDI header for programming

Full disclosure: I am member of the MySensors core team. A MySensors user (not affiliated with the core team) created and is selling this board.
> 2 votes

# Answer
nRF24L01 is a proprietary system, unlike WiFi and Bluetooth. There is only one (official) maker of nRF devices (Nordic Semiconductor).

Yes, they are very nice modules, but why would you spend the time and money developing a generic microcontroller board that has such limited scope as to only be able to communicate with the same board or one with one specific module attached? You wouldn't - it doesn't make financial sense - especially when it's easy for an end user to add the module to any other board instead.

Bluetooth and WiFi make more financial sense because there is a huge range of devices that they can communicate with which means they can be used for a far greater range of projects thus increasing demand for them.
> 0 votes

---
Tags: nrf24l01+, wireless
---


# Question
Title: Why is there already text in the serial monitor before the Arduino initializes?
I have encountered this several times before and I would like it if someone was able to give an explanation. In almost any sketch that I've ever created with Serial communication involved, I notice that I will get text that seemingly appears before the void setup() function has run. For example, I have the simplest sketch below where this occurs.

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

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

```

If I upload this to one of my Arduino Megas, I will often get the output in the serial monitor:

```
WelcWelcome

```

When I open the serial monitor to view the output, the "Welc" is already written and then the rest of the "Welcome" come in a few moments later. If I close and re-open the serial monitor or reselect the baudrate setting within the serial monitor, the serial monitor clears, restarting the Arduino, and printing only "Welcome" to the screen without the "Welc", as I would expect.

However, if I upload the sketch, then disconnect-reconnect the Arduino-USB cable from the computer, and open the serial monitor, there is no leftover bytes printed to the screen like before.

The exact bytes leftover that appear before the void setup() function is called varies from upload to upload. Can anyone give me an explanation and is there a way to avoid the leftover bytes ? Thank you.

# Answer
It's because the Arduino has started running the sketch and placed data into the USB chip's buffer. You then open the serial monitor which then opens the serial port thus resetting the Arduino. So the sketch runs again.

It only resets the Arduino, not the USB interface chip, so you get what was in there from the first execution plus the new text from the second (post-opening) execution.

You cannot "avoid" the extra bytes, that's just the way things are. The Arduino resets. There are buffers in various places. You have no control over those buffers.

As a side note: the serial monitor is completely disgusting. If you want to do things properly use a proper terminal emulator, then you can use ANSI control codes to do things like clear the screen, move the cursor around, apply colour, etc.
> 5 votes

# Answer
Because as soon as you start the serial monitor, it picks whats on the serial buffers and then resets the arduino connected and also it would reset again when you try to upload code but luckily serial monitor is cleared in this instance;
> 0 votes

---
Tags: serial, arduino-mega, usb
---


# Question
Title: Reading FAN tachometer/RPM on 4 wire fan using arduino
I am following the wiring and code at https://playground.arduino.cc/Main/ReadingRPM but using pin 9 to read the speed instead of pin 2 and I have added a 10K pull up resistor between pin 9 and +5V as well; I dont see any interrupts firing even though the fan is running;

The fan is a standard intel cpu fan with 4 wires(black, yellow, green, blue) and the green wire is the sense/tach wire and I have connected it to pin 9 as well;

Need some help or expert advise; I am not sure if the approach works fine or not;

# Answer
There are no interrupts on pin 9 (unless you are using Pin Change interrupts...?). You have to use pin 2 (interrupt 0), or pin 3 (interrupt 1) (also, on the Mega: 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2)).
> 4 votes

---
Tags: interrupt
---


# Question
Title: Is possible to set a pin faster than digitalWrite?
I am currently using arduino library to logically set my digital pins high or low, but I just realized how slowly it actually sets those pins, which is especially problem as i am doing this in a ISR routine. Can't this be done faster by actually acessing the direct port, and setting the current pin?

How do I convert something like this

```
  digitalWrite(11, !digitalRead(11));

```

To something faster?

I am using a Arduino UNO..

# Answer
**Yes, it is possible**

The atmel chip at the core of the arduinos can set or clear individual pin output levels in a single operation. There are special instructions to do so `SBI` and `CBI`\- you just need to figure out what C compiles down to those instructions.

Each pin is represented by one bit of a port byte, for pin 11 it's bit 3 on port B. So you can toggle it with

```
PORTB ^= _BV(PB3);

```

or set it with

```
PORTB |= _BV(PB3);

```

or clear it with

```
PORTB &= ~_BV(PB3);

```

Probably the last two will compile to a single `SBI`/`CBI` instruction while the toggle one may or may not, depending on the code and how the compiler optimises it.
> 5 votes

# Answer
Yes there is!
You can directly manipulate the port. The Arduino website has a pretty good explanation for it here.

Togelling a pin as asked by you can be simply done by something like this:

```
  PORTB ^= _BV(PINNUMBER)

```

A simplified way is the digitalWriteFast library.

> This library consists of a complex header file that translates digitalWriteFast, pinModeFast, digitalReadFast into the corresponding PORT commands. It provides syntax that is as novice-friendly as the arduino's pin manipulation commands but an order of magnitude faster.
> 4 votes

# Answer
Since pin 11 on the ATmega328P is PB3:

```
PINB |= _BV(PB3);

```
> 4 votes

# Answer
The fastest way may be to use assembly from your C++ code:

```
asm volatile("SBI %[IOREG], %[BIT] \n\t"::[IOREG] "I" (&PINB), [BIT] "I" (PB3));

```

This forces a `1` to the bit for pin 11 (bit 3 on port B of the ATmega328), which, as per the Atmel datasheet, will simply toggle output (1 to 0 or 0 to 1) on that pin (provided it was initially setup as output).

As far as I remember the assemby instruction `SBI` used above cannot be generated by g++ (the C++ compiler used by Arduino IDE), hence you have to code it yourself.

You won't be able to achive a better performance as this single assembly instruction takes exactly 2 clock cycles to execute (ie **125 ns** on an Arduino UNO).
> 2 votes

# Answer
Yes that can be done by manipulating the ports directly. Here is the link to Arduino https://www.arduino.cc/en/Reference/PortManipulation
> 0 votes

# Answer
The Arduino GPIO library has been developed to allow high performance digital pin access. Most access functions are compiled to a single instruction and execute in 1-2 clock cycles. The library functions are more than 10 times faster than the Arduino digital pin functions. In some cases as much as 100 times faster.

Additional support classes are available for Shift Register Input/Output, and Software Serial. These also demonstrate how the GPIO template class may be used to construct additional libraries.

This library supports boards based on SAM3X8E, ATmega168, ATmega328P, ATmega32U4, ATmega1280, ATmega2560, ATtinyX4 and ATtinyX5.

The classical blink sketch looks like this:

```
GPIO<BOARD::D13> led;

void setup()
{
  led.output();
}

void loop()
{
  led = HIGH;
  delay(1000);
  led = LOW;
  delay(1000);
}

```

Please see github for benchmarks and further documentation and examples.
> 0 votes

---
Tags: pins, isr
---


title: just a silly doubt about glowing an LED

text:
# Question
Title: just a silly doubt about glowing an LED
what will happen if i insert the anode of a LED to pin 12 and cathode of the LED to pin 11 and set pin 12 to high and pin 11 to low,will the led glow??

# Answer
What will happen is you will damage your LED and/or your Arduino since you haven't mentioned a current-limiting resistor (220 ohms could well be suitable).

However the general concept is perfectly sound. You could, for example, have two LEDs, wired in opposite directions. By bringing one pin LOW and the other HIGH, one LED would light up, and by reversing the output to the pins the other LED would light up. If both pins were either HIGH or LOW then neither LED would light up, as there would be no voltage difference between the leads.

There is a calculator for LED resistors.
> 4 votes

# Answer
Yes it will, try it. This is one of the way to use a LED as a light sensor and light source by connecting it to two different Digital pins.

Ref.: https://playground.arduino.cc/Learning/LEDSensor
> 3 votes

---
Tags: arduino-uno, programming, led, input
---


# Question
Title: Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan
This question is not same as the other one and this is more about employing the pwm signal to drive a CPU fan;

I am trying to follow the answer by Edgar Bonet on the question Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4 and use this pwm signal to control the speed of a 4-wire cpu fan(with black, yellow, green and blue wires);

Following is my updated code for generating the pwm signal on timer 4

```
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4C1)  // non-inverted PWM on ch. C
          | _BV(WGM41);  // mode 10: phase correct PWM, TOP = ICR4
    TCCR4B = _BV(WGM43)
         | _BV(CS40);   // prescaler = 1
    ICR4   = 320;      // TOP = 320

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

```

I have connected pin 8 on the mega to the pwm input on the fan(blue wire) but I dont see any variation in fan speed and fan seems to run at full speed;

I dont really have any means or tools to verify if its really generating a 25khz pwm signal but fan speed is not changing or if its not generating a 25khz pwm signal because of which there is no change in the speed of fan;

I am stuck at this point and any help on this would he highly appreciated;

# Answer
I've just tested your setting with older "Alpine 64 GT" CPU Fan and it works as expected. I've just added parsing integers sent from serial monitor, so I don't have to change code anymore.

```
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
      analogWrite25k(w);
      Serial.println(w);
    }
}

```
> 1 votes

---
Tags: pwm, speed
---


# Question
Title: Use ESP-01 with Arduino Uno/Nano, with the ESP8266WiFi library
There is this library - https://github.com/esp8266/Arduino That provides a more user-friendly API for WiFi capabilities with the ESP8266.

However, all tutorials that I found so far for this library show how to program the ESP8266 (usually 12) directly. That is not what I'm looking for.

My current setup is having an Arduino Uno/Nano where the ESP8266 is connected to, say, GPIO8 and GPIO9 (RX, TX) and I use SoftwareSerial to communicate with it with AT commands. So I want to keep all the logic in my Arduino, but use ESP-01 only to provide WiFi capabilities to my Arduino.

However in that library I don't see the option to set the serial port pins (RX and TX) so I'm not sure if that's even possible.

In short - I want to use this library, but not program the ESP directly. Also, I'm using an ESP-01 and not 12.

Thanks.

# Answer
You cannot use that "library". Simply because that isn't a library, that is a *core*. It's the entirety of the Arduino API designed to run on an ESP8266.

You can use it to program the ESP8266 directly and nothing else. No part of that has anything at all to do with Arduino boards like the Uno.
> 6 votes

# Answer
You can infact connect ESP as a serial device to the arduino and use AT commands supported by the ESP to interact with it and achieve what you want;

For ESP-01 read the detail on http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/

Please read the following instructable which has detailed explanation on how to connect ESP12 also if interested; http://www.instructables.com/id/ESP-12E-ESP8266-With-Arduino-Uno-Getting-Connected/
> 4 votes

---
Tags: arduino-uno, esp8266, arduino-nano, wifi
---


# Question
Title: Which library to use for 23LC1024 SRAM 1 Mbit
I noticed there are quite some libraries for the 23LC1024 SRAM 1 Mbit memory:

1. SpiRam Extended library
2. SpiRam library
3. Direct SPI ?

I tried 1 and 3 so far. What I noticed was that to read 1 byte took around 18 us for the 3th solution and around 25 us for the first library. However, the first has possibilities to read multiple bytes and that considerably speeds up the time.

Also there are other libraries like MQTT and possibly I missed some.

However, in all cases I would expect speeds around just a few us. Since I maybe need to read 100 of different small groups of bytes preferably within 10 us (and process them), it might get problematic in worst case scenarios.

Does anybody know where the speed differences come from or if there are ways to increase the speed or which library is fast?

# Answer
> 4 votes
SPI RAM has two modes of operation: single byte and "page mode".

In single-byte mode you first send the read or write command followed by the (typically 3-byte) address and then read a byte. That's 5 bytes per transaction, or 40 SPI clock cycles. At the maximum of 8MHz (SPI\_CLOCK\_DIV2 on a 16MHz MCU) that would be at absolute best (1/8000000\*40) 5µS per byte read or written. That's not including the time taken to toggle the CS pin and perform the other software-level parts of controlling the SPI peripheral.

In page mode it is possible to send one *start* address and then read or write sequential data *from* that address upwards. Ideal if you need to read a larger number of bytes that are sequentially in memory. For instance, to read 100 bytes sequentially it would take 104 SPI bytes - one for the read/write command, three for the start address, and 100 for the data. That is 832 SPI clocks, or at 8MHz, 104µS.

As you can see, reading 100 bytes within 10µS is not possible on an Arduino with SPI SRAM. There just isn't enough speed. Even 100 sequential bytes. 100 "small groups of bytes" just ain't gonna happen.

There are other technologies that are faster which may be more suited to your use, but they require different peripherals in the chip (namely SQI), and the chips with that in tend to be more powerful and have more RAM anyway, so your 1Mb of external SRAM would be redundant.

# Answer
> 3 votes
This was an excellent challenge for an SPI bus manager and device driver support library I have been working on. Below are some performance results for the SRAM (23LC1024) device driver (Arduino Uno @ 16 MHz, SPI @ 8 MHz) read/write us per byte, kbytes/s, in benchmark.

```
write: 9.875 + N*1.4275 us, max. 700 kbyte/s
read: 9.875 + N*1.5 us, max. 670 kbyte/s
where N is the number of bytes transfered

```

The protocol overhead (9.875 us) is 1) slave select pin handling, and 2) command byte and 24-bit address (four bytes header in total).

Cheers!

Update \[2017-09-25\]

@MichelKeijzers I recently had time to work on an abstraction of external storage and refactor a number of device drivers to support the new interface. The abstraction includes memory block allocation, caching, handling of large vectors, and streams on external storage. Please see https://github.com/mikaelpatel/Arduino-Storage for more details; benchmarks, example sketches, etc.

---
Tags: arduino-uno, spi, sram
---


# Question
Title: Adafruit Feather 32u4 Bluefruit LE and HC-05 Bluetooth module
Is it possible to connect an Adafruit Feather 32u4 Bluefruit LE with an HC-05 Bluetooth module?

I am making a heart rate monitor using an Adafruit Feather, but it is unable to send the data to LABView for processing as it uses BLE. I do not have the means to buy a Bluetooth dongle to work around the issue.

However, I do have an HC-05 Bluetooth module that can be read by VISA on LABView.

Therefore I would like to ask if it is possible to connect my Adafruit Feather to my HC-05 module and send the data through the HC-05 instead of the built-in BLE.

Thank you!

# Answer
HC-05 does not support BLE as far as I know but you can use a HM-10 if you can get your hands on one; Its almost about the same cost as a HC-05, maybe a little more;
> 1 votes

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


# Question
Title: Arduino protecting analog input with internal voltage reference
Usually a common way to protect an analog input consists on reducing voltage and current in the following way:

Current limiting components, as Resistors or inductors and voltage limiting components as diodes, zener, tvs.

In this case for components availability I have used two resistors and a zener diode.

The circuits aims to accept a 0-10V input and read it with the internal reference voltage 1,1V.

The question is the following: Assuming I want to use a 2,2V zener diode as overvoltage protection and 1,1V internal voltage reference, can I consider it safe or the 2,2V of zener will be too much for the 1,1V reference?

simulate this circuit – Schematic created using CircuitLab

NOTES: I am using 2,2V zener diode because is the smallest size I can found. I could use two normal diodes to reach 1,4V but maybe it will be too much for 1,1V reference and the result could be the same. I could also add an external reference, but I would like to know if I can have problems with this configuration.

# Answer
> 2 votes
Yes, it is safe. The reference voltage is only used as a comparison. The ADC is still powered by, and limited by, the chip's supply voltage (5V).

The AREF voltage has no bearing on what limits there are on voltages you can apply to a pin. All that will happen is that voltages above 1.1V will register as 1023. You can go right up to 5V safely.

# Answer
> 1 votes
As far as I know, no one uses a zener diode in a analog circuit that is used to measure a voltage. Well, at least no one who is serious and knows what he/she is doing.

The zener diode will start leaking at a lower voltage and it might introduce noise. I never use a zener diode in a analog input circuit that is used to measure something.

What is the maximum positive and negative voltage that you want to protect the Arduino against ?

Suppose using a 5V ATmega chip, with R1 = 100k, R2 = 10k, C1 = 10nF, with 1.1V as reference (and no extra ESD or clamping diodes and no zener diode). Then you are protected up to **160 V**.
That is a constant voltage of 160 V that is allowed, as long as R1 can dissapate the heat.
That means without the zener and better choosen values of the resistors, it becomes more accurate and safer and more sturdy.

Calculation: A0 can be up to 5.5V. Then the internal diodes start to conduct, and it is allowed to push 1mA into the pin.
Current R2 = 5.5 / 10k.
Current into pin = 1mA.
Voltage over R1 = 100k * ((5.5/10k) + 1mA).
External signal = 5.5 + voltage over R1.

Suppose a leakage current for a 2.2V at 1V is 0.02mA. That seems a reasonable number from what I can find. That will influence your measurement by maybe 2 percent (I'm not sure, I didn't do the calculation). That would mean that of the 10-bit resolution you dropped to 6-bit resolution (I'm also not sure about this one).
To protect the analog input, instead of a 2.2V zener, a 5V zener would be more appropriate (that is: when going down the wrong path to use a zener). The 1N4733A has a leakage current of 10 µA at 1V, and that will still influence the analog signal and still cause a less accurate voltage measurement.

---
Tags: adc, analogreference
---


title: Arduino Zero timer setup

text:
# Question
Title: Arduino Zero timer setup
Where would I find information on how to configure the Arduino Zero's timers?

Because this...

```
  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 150;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV256 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

```

Is completely indecipherable and highly error prone.

# Answer
# BOTTOM UP

The arduino Zero uses an Atmel samd21 µController. This video explains how to program the samd chips in a bottom up fashion, or at least how to gather all required information to do so. In case the video doesn't work anymore, i'll briefly rephrase it here. The main steps are:

The bottom up process can be very time consuming, because you are searching a needle out of an haystack like, the datasheet and the ASF. So you need to tackle all the tiny bits before building the whole thing.

# TOP DOWN

For some situations it is better to look for a working example program and try to figure out how its done. For this i recommend the arduino github repository. It is a very good resource for figuring out how arduino uses the ASF and helps me tune certain functions.

The top down process therefore allows to decompose a large working function into its smaller parts and dig into the interesting parts. However, it requires something to work with at the start which is not always available.

# INDECIPHERABLE

Some code examples aren't understandable from the start. Once you know what the code is doing, i recommend splitting up the large pieces like this register and bit modification section into smaller ones. Extract these sections into functions with self explanatory names, and if done correctly you can get rid of the comments.

Hope this helps ;)
> 4 votes

# Answer
> Where would I find information on how to configure the Arduino Zero's timers?

Try the datasheet.

What you showed there is fairly typical, may be on the primitive side for chips of its kind.

More power comes with more complexity.
> 1 votes

---
Tags: arduino-zero
---


title: Dust sensor code with a few errors

text:
# Question
Title: Dust sensor code with a few errors
I'm fairly new to this and I'm having trouble with a code for a dust sensor. Getting a couple of errors. I downloaded this code from GitHub. Anyone have any idea how to fix any of these errors? Any help is appreciated. Sorry if this formatted wrong, this is also my first post. Thanks for your time

```
// SDS011 dust sensor example
// -----------------------------
//
// By R. Zschiegner (rz@madavi.de).
// April 2016

#include "SDS011.h"
#include<SoftwareSerial.h>
SoftwareSerial myserial(0, 1);
SDS011(byte pin_rx, byte pin_tx)
float p10,p25;
int error;

SDS011 my_sds;

void setup() {
  my_sds.begin(0, 1);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
}

void loop() {
  error = my_sds.read(&p25,&p10);
  if (! error) {
    Serial.println("P2.5: "+String(p25));
    Serial.println("P10:  "+String(p10));
  }
delay(100);
}

```

here are the errors I'm getting

```
code:10: error: expected ')' before 'pin_rx'

 SDS011(byte pin_rx, byte pin_tx)

             ^

C:\Users\Nick\Desktop\code\code.ino: In function 'void loop()':

code:26: error: 'p25' was not declared in this scope

   error = my_sds.read(&p25,&p10);

                        ^

code:26: error: 'p10' was not declared in this scope

   error = my_sds.read(&p25,&p10);

                             ^

exit status 1
expected ')' before 'pin_rx'

```

# Answer
You have to use the begin command. Instead of:

```
SDS011(byte pin_rx, byte pin_tx)

...

SDS011 my_sds;

```

Use

```
SDS011 my_sds;

```

(Thus remove the first line: SDS011(byte pin\_rx, byte pin\_tx)).

And in setup add:

```
my_sds.begin(0, 1);

```

This follows the library function of SDS011:

```
void begin(uint8_t pin_rx, uint8_t pin_tx);

```

Other errors: because you forgot the ; in

```
SDS011(byte pin_rx, byte pin_tx)

```

the next line:

```
float p10,p25;

```

is misinterpreted, and p10 and p25 are not known. Therefore errors are shown while trying to use p10 and p25.

These errors will go when changing the begin code as described earlier.
> 2 votes

# Answer
Your code should be like below; there are multiple syntax and semantic errors in the code you have posted;

Below is the edited and working code;

```
#include <SDS011.h>

float p10,p25;
int error;

SDS011 my_sds;

void setup() {
  my_sds.begin(0, 1);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
}

void loop() {
  error = my_sds.read(&p25,&p10);
  if (! error) {
    Serial.println("P2.5: "+String(p25));
    Serial.println("P10:  "+String(p10));
  }
  delay(100);
}

```
> 0 votes

---
Tags: sensors, c++
---


# Question
Title: redefining delay and delaymicros as personal function
Is it possible to redefine delay and delaymicros function with #define ? I want to use timer2 interrupt instead of these.

Something like this:

```
#define delay(unisgned long ms) countMicros(uint16_t top, uint16_t storageVar)

setup(){}

loop(){
 delay();// function countMicros is called instead.
 }
void countMicros(uint16_t top, uint16_t storageVar){
//...}

```

# Answer
Not exactly like that. You will have to manage the different sets of parameters, i.e. convert the incoming `ms` into the `top` and `storageVar` that would be appropriate for calling `countMicros()`. Maybe something like this:

```
#define delay(ms) mydelay(ms)

void mydelay(unisgned long ms) {
    uint16_t top = some expression;
    uint16_t storageVar = another expression;
    countMicros(top, storageVar);
}

```

where both expressions are a function of `ms`.

If the expressions are really simple, you could even put the whole thing inside a single macro, as in

```
#define delay(ms) countMicros(some expression, another expression)

```
> 1 votes

---
Tags: atmega328
---


# Question
Title: Run Stepper with A4988 driver in highest resolution
I have a Bipolar Stepper Motor (12V, 350mA, 28oz-in NEMA-17) and would like to run it in the highest resolution (Sixteenth Step) with the A4988 Driver. According to multiple sources I read I need to "put 5V" to the MS 1,2,3 pins. What does this mean/How can I achieve this ?

Do I need to hook up the MS 1,2,3 to the digital pins of the Arduino and write Digital High. Or do I need to hook all of them to 5V together ? And should the code look like this ? Is this safe/good pratice ?

```
int MS1Pin = 8;                 // Set MS Pins
int MS2Pin = 9;
int MS3Pin = 10;

void setup()
{
  pinMode(MS1Pin, OUTPUT);      // sets the digital pin as output
  pinMode(MS2Pin, OUTPUT);      // sets the digital pin as output
  pinMode(MS3Pin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(MS3Pin, HIGH);
  digitalWrite(MS2Pin, HIGH);
  digitalWrite(MS1Pin, HIGH);
<<MY CODE here>>

}

```

Sorry for these beginner questions, I just don't want to fry the Chip and this to work.

Thank you.

# Answer
> 0 votes
You can drive the MS pins from the Arduino if you want, but there is no need. You can just hook them all up to 5V.

Have you seen this page, there seems to be load of details that you might find relevant. https://www.pololu.com/product/1182

---
Tags: a4988
---


title: AttachInterrupt in a library

text:
# Question
Title: AttachInterrupt in a library
I'm having trouble adding attachInterrupt in a library that I am creating. I researched a lot, and I noticed that this is a common mistake, but do not quite understand the answers I found.

The error in question is this:

```
sketch_nov04a.ino: In function 'void setup()':
sketch_nov04a:10: error: argument of type 'void (Teste::)()' does not match 'void (*)()'

```

My library is as follows:

**Teste.h**

```
#ifndef TESTE_H
#define TESTE_H
#include <Arduino.h>

class Teste
{
public:
    volatile long lastWindIRQ;
    volatile byte windClicks;

  void wspeedIRQ();
};
#endif

```

**Teste.cpp**

```
#include "Teste.h"

void Teste::wspeedIRQ()
{
  if (millis() - this.lastWindIRQ > 10)
  {
    this.lastWindIRQ = millis();
    this.windClicks++;
  }
}

```

**my implementation**

```
#include <Teste.h>

Teste teste;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH);
  attachInterrupt(0, teste.wspeedIRQ, FALLING);
}

void loop()
{
  Serial.println(teste.windClicks);
  delay(3000);
}

```

**EDIT**: Updated the error and corrected the problem cited by Ignacio

# Answer
The problem is that `wspeedIRQ()` is a member function (i.e. it's part of the `Teste` class), but `attachInterrupt()` expects a non-member function (i.e. a function which is static and/or not part of a class at all).

This is a very important distinction in C++ because it affects how the compiler calls the function behind-the-scenes. There is unfortunately no way to use a member function directly with `attachInterrupt()`.

Various workarounds are possible though. The simplest is to write a wrapper function which calls the member function. For example:

```
Teste teste;

// This is a non-member function...
void isr()
{
    // ...which calls the member function:
    teste.wspeedIRQ();
}

void setup()
{
    //...

    // Setup interrupt to use a non-member function
    attachInterrupt(0, isr, FALLING);
}

```

As a side note, your implementation of `wspeedIRQ()` won't compile at the moment anyway. The reason is that `this.` is invalid. It's a pointer so the correct syntax is `this->`.

(In practice, you usually don't need to use `this` to access member data. C++ figures it out automatically, unless there's a naming conflict.)
> 4 votes

# Answer
Normally you should use digitalPinToInterrupt(pin) to translate the actual digital pin to the specific interrupt number not the pin switch comparison attachInturrupt( , , )that is limited to pin 2,3 on an arduino uno ...or if you spend more money well... here's a list.

```
Board                              Digital Pins Usable For Interrupts
Uno,    Nano, Mini, other 328-based 2, 3
Mega,   Mega2560, MegaADK           2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based   0, 1, 2, 3, 7
Zero                                all digital pins, except 4
MKR1000 Rev.1                       0, 1, 4, 5, 6, 7, 8, 9, A1, A2
Due                                 all digital pins
                                    all digital pins (Only pins 2, 5, 7, 8,
                                    10,  11, 12, 13 work with CHANGE

```

delay() won't work b/c values won't return from millis() (don't ask why) https://www.arduino.cc/en/Reference/AttachInterrupt explains how to use inturrupts like let me recite the beggining

Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input.... blah blah

what pete didn't mention is what Interrupt Service Routines were... and how these special functions have unique limitations other functions like in c++ do not.... from c-strings to structs to overloading to f-structs to t-templates. ISR's are as short as possible and should not return anything! if your cheap and don't want to spend more than $5 for a arduino you can use sketch to use multiple isr's you can set them up as priority

but your non member functions should be volatile and global... and millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms. delayMicroseconds() does not use any counter, so it will work as normal. and .... global variables are used to pass data between an ISR and the main program. To make sure variables shared between an ISR and the main program are updated correctly, declare them as volatile.
> 0 votes

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