# Question
Title: What happens if I don't use a relay for 5V pump
I am trying to build an automatic watering system by following some examples. However, I don't have all the components for the entire system, therefore I have built it in Fritzing using only the components that I have (see scheme below):

I didn't build the physical version yet, because I am not sure that such a system would work without burning anything. In many examples, people connect the pump to a Relay Module, but since I don't have it yet, I would like to build it like this until I set up the watering system.

Can anyone help me understand why a relay would make it better or worse?

P.S. I have a JPC-3F relay, but I can see that the Relay Module contains multiple components. Is it possible to add the JPC relay to the pump without having the entire Relay Module? Would I need extra components for that?

Thank you!

EDIT: Thanks to the answer from ratchet freak, I have added resistances and a transistor. It works fine, but the same question stands. Do I still need a relay in this case?

# Answer
You should put a resistor in series with the led to limit the current.

The IO pins cannot source enough current to run the pump without damaging themselves. That's why you need a buffer of some kind.

The extra components in the relay module are a transistor to do the actual switching and a reverse-biased flyback schottky diode in parallel with the relay coil. The flyback diode is required to absorb the voltage spike generated by the coil getting switched off and acting like an inductor.

You can use a transistor to switch the motor directly assuming you can find one that can handle the current draw. If you do then you absolutely will need a flyback diode on the motor to avoid damage to the transistor.
> 9 votes

# Answer
this is not an answer to the question you asked, but you need to understand this:

generic DC relay advice. Use commutating diodes. this is not a special kind of diode, it is a particular use of a generic diode. you want 2:

one across the coil, reversed biased - cathode to +VDC. The coil throws a huge spike of negative DC when power to the coil is cut and the magnetic field collapses. this diode eats that spike

second one from the load to ground, reverse biased. this eats any spike from the load to ground - the fat blue arc you see when you disconnect a load by yanking the wire

https://www.allaboutcircuits.com/textbo ... -circuits/ https://www.allaboutcircuits.com/textbo ... ing-diode/ https://en.wikipedia.org/wiki/Flyback\_diode G
> 4 votes

# Answer
The relay have a coil resistance of 70 ohm for the 5 Volt version.

Ohms law, U = I x R

I = U/R = 0.071 Ampere, and now you have to find out, can an Arduino I/O pin drive a load of 71 mA? If not you have to add a driver aka most commonly a transistor.

And now you should ask yourself, can I drive the motor directly with a transistor driver and skip the relay? So do you have any data on the pump?

And if you look at the datasheet for IRF520, fig 3 and fig 4 have the data for planning if it will work or not.

Ref.: https://www.infineon.com/dgdl/irf520npbf.pdf?fileId=5546d462533600a4015355e340711985
> 2 votes

---
Tags: motor, relay
---


# Question
Title: Arduino port grayed out for Fake Board with CH340
I have downloaded and used Arduino IDE v1.8.4 from official site (needs no install) for windows10, and connected my random board with a ch340, but it's LED is only blinking and I can't select the port (ie. it's grayed).

I did test all USB ports and restarted my laptop but that didn't work!

I tried to install 1.6.9 IDE that I had before, but again the port option is unselectable!

This is my board: http://uupload.ir/files/xgv\_uno.jpg

# Answer
Simplest possible thing would be that you do not have CH340g driver installed and you should try installing it first; These boards use CH340 for usb to serial and they need the driver to be installed; Please give it a try by getting the driver from the following link http://www.wch.cn/download/CH341SER\_EXE.html or any other reliable source if there is any problem with the link;

If the board is not recognized even after that, it could be a bad USB port or a bad USB cable or even a board with the CH340 chip dead;
> 2 votes

---
Tags: ch340
---


# Question
Title: How to connect a simple wall switch to arduino GPIO
I am trying to create a smart doorbell, but my problem is that doorbell makes ring any time when nobody touch the button.

I think that the problem is caused for the incorrect way to connect the analog wall button to arduino GPIO.

Basically my wiring diagram is:

Analog Input (A0) to 1 pin of the button. Ground of the Arduino (GND) to the other pin of the button.

When the button is pressed, the circuit is closed, and doorbell makes ring!

But surely this is not the way to connect a button on the wall because the doorbell sounds on its own.

I leave a picture of the button

# Answer
jose can u c is absolutely right, you need a pullup. No need to change your wiring however: the Arduino has built-in pullups on all the inputs. You just have to activate them:

```
const uint8_t buttonPin = A0;  // or any other pin for that matter

void setup()
{
    pinMode(buttonPin, INPUT_PULLUP);
}

```
> 2 votes

# Answer
You need to have a pull-up resistor, see circuit below.

You do not need to connect it to an Analog pin, but a digital pin. Without a pull-up or pull-down resistor, the voltage on the input pin "floats" anywhere, and can give false triggers. This circuit *forces* the pin to either be 5V or 0V.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Error uploading Arduino Micro Sketch using Kubuntu
I have an arduino micro which I want to program from my Kubuntu 15.10 system. I installed the arduino software using apt-get, but when I try to upload the program (for test purpose I use the Basics\BareMinimum sketch) I get the following error:

```
Found programmer: Id = "0.00 V1"; type =
    Software Version = 0..; Hardware Version = 0.0
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

```

The proper device "Arduino Micro" is selected and also the proper port "/tty/ACM0". I found people on the internet which have the same error and could solve it by using another USB port or cable. But I tried it with two different cables and different ports and didn't manage to get it working. I even tried it on my Laptop running an older version of Kubuntu which produced the same error.

Therefore I tried the newest version of the Arduino software from the arduino homepage. With this I get a different error:

```
avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
avrdude: ser_send(): write error: Bad file descriptor

```

My user is added to the dialout group, so I should have access to the port. It is also the right port as the port disappears from the arduino menu when I unplug the board.

The arduino itself shouldn't be the problem, as I can upload the sketch from another windows laptop without problems.

EDIT: when I plug in the arduino, the following is added to the `dmesg` output:

```
[ 8390.293960] usb 1-2: new full-speed USB device number 6 using xhci_hcd
[ 8390.424861] usb 1-2: New USB device found, idVendor=2341, idProduct=8037
[ 8390.424863] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 8390.424864] usb 1-2: Product: Arduino Micro
[ 8390.424865] usb 1-2: Manufacturer: Arduino LLC
[ 8390.425283] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[ 8390.426815] input: Arduino LLC Arduino Micro as /devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2:1.2/0003:2341:8037.0007/input/input21
[ 8390.482163] hid-generic 0003:2341:8037.0007: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC Arduino Micro] on usb-0000:00:14.0-2/input2

```

# Answer
> 2 votes
> Therefore I tried the newest version of the Arduino software from the arduino homepage.
>
> The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

That is not the newest version.

I think the more recent versions of the IDE are more robust - after all they have fixed reported bugs. Try 1.6.5 or 1.6.7. The version 1.0.5 is pretty old.

---

I too have had "upload completed" on my Leonardo (virtually the same as the Micro) when it did no such thing.

I am using Ubuntu 14.04 and don't have any problems programming my Micro with IDE 1.6.7.

---

When programming you should see the Tx/Rx and yellow LEDs flicker. If not, press Reset when it starts to upload and try again.

---

Have you followed the instructions here? Arduino Troubleshooting.

---

> I installed the arduino software using apt-get ...

Personally I download the IDE from this page: https://www.arduino.cc/en/Main/Software

---

## Update

I just compiled and uploaded "Blink" with IDE 1.6.7 to my Micro on Ubuntu 14.04. This is what I saw:

```
Forcing reset using 1200bps open/close on port /dev/ttyACM1
PORTS {/dev/ttyACM0, /dev/ttyACM1, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, /dev/ttyACM1, } => {/dev/ttyACM1, }
Found upload port: /dev/ttyACM1
/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avrdude -C/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM1 -b57600 -D -Uflash:w:/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/nick/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

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

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

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex"
avrdude: writing flash (4456 bytes):

Writing | ################################################## | 100% 0.33s

avrdude: 4456 bytes of flash written
avrdude: verifying flash memory against /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: load data flash data from input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex contains 4456 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.03s

avrdude: verifying ...
avrdude: 4456 bytes of flash verified

avrdude done.  Thank you.

```

Can you please compare to what you get? Or post exactly what you see?

---

What do you see in your Port menu? This is what I see:

---

# Installing Arduino on a fresh Ubuntu system

I did the following steps to get Arduino up on Ubuntu 14.04, on a PC where it was not previously installed.

## Download and install

## Compile "blink"

* Selected Uno device type
* Loaded "Blink" from examples
* Uploaded (checked Uno showed in menu as shown above)
* Got error:

```
Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

```

## Check permissions, join dialout and tty groups

See owner of `/dev/ttyACM*`

```
$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Feb  1 07:32 /dev/ttyACM0

```

Am I in that group? (No)

```
getent group dialout
dialout:x:20:

```

Add to group `dialout`:

```
$ sudo usermod -a -G dialout nick

```

Am I in that group? (Yes)

```
$ getent group dialout
dialout:x:20:nick

```

Try again:

```
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

Add to group `tty`:

```
$ sudo usermod -a -G tty nick

```

Check groups I am in:

```
$ groups nick
nick : nick adm tty dialout cdrom sudo dip plugdev lpadmin sambashare

```

Try again (same error).

## Log out and log back in

After logging out and back in, it uploaded OK! Changed to Micro board (very similar to Leonardo) - still uploaded OK (after changing board type in IDE).

## Check USB for Micro

After reset:

```
$ lsusb | grep Arduino
Bus 002 Device 014: ID 2341:0036 Arduino SA

```

After about 3 seconds:

```
$ lsusb | grep Arduino
Bus 002 Device 015: ID 2341:8037 Arduino SA

```

# Answer
> 1 votes
I have been meaning to try the Arduino IDE on Ubuntu. (I'm on Ubuntu 14.10 LTS and using an original Arduino UNO).

From the top, I installed using:

```
sudo apt-get update && sudo apt-get install arduino arduino-core

```

(from: http://playground.arduino.cc/Linux/Ubuntu)

It's the older version 1.0.5 and loaded up the basic sketch. It worked straight off the bat.

Just some quick thoughts:

# Keyboard and mouse emulation

I noticed the `hid-generic` and was reminded of the caution on:
https://www.arduino.cc/ re codig practices for keyboard and mouse emulation

regarding coding practices for keyboard and mouse emulation. Does your old sketch utilise the keyboard/mouse libraries at all? It might come down to REALLY timing the reset perfectly.

# The `reset` problem

Given that you're getting a communication error based on the virtual USB device in the Leonardo/Micro (single chip as opposed to the previous versions), and you're seeing it in the IDE but not via the `avrdude` software, have you followed the `reset` instructions from the above link? So back to timing the reset (emphasis mine):

> In general, you upload code to the Leonardo or Micro as you would with the Uno or other Arduino boards. Click the upload button in the Arduino IDE and your sketch will be automatically uploaded onto the board and then started. This works more or less the same way as with the Uno: the Arduino software initiates a reset of the board, launching the bootloader - which is responsible for receiving, storing, and starting the new sketch.
>
> However, because the serial port is virtual, it disappears when the board resets, the Arduino software uses a different strategy for timing the upload than with the Uno and other boards. In particular, after initiating the auto-reset of the Leonardo or Micro (using the serial port selected in the Tools \> Serial Port menu), the Arduino software waits for a new virtual (CDC) serial / COM port to appear - one that it assumes represents the bootloader. It then performs the upload on this newly-appeared port.
>
> These differences affect the way you use the physical reset button to perform an upload if the auto-reset isn't working. **Press and hold the reset button on the Leonardo or Micro, then hit the upload button in the Arduino software. Only release the reset button *AFTER* you see the message "Uploading..." appear in the software's status bar.** When you do so, the bootloader will start, creating a new virtual (CDC) serial port on the computer. The software will see that port appear and perform the upload using it. Again, this is only necessary if the normal upload process (i.e. just pressing the uploading button) doesn't work. (Note that the auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it; this won't work if something interferes with the board's USB communication - e.g. disabling interrupts.)

# `avrdude` command line

Next, share your `avrdude` command line and we can see if something is odd there. As an example with my UNO I see this:

```
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build1362089533882735765.tmp/Blink.cpp.hex:i

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/madivad/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: Send: 0 [30]   [20]
.... and so on ....

```

# USB 3 vs USB 2

I probably could have put this closer to the top, but are you using a USB 2 or USB 3 port? If USB 3 are the correct drivers loaded? Have you tried a USB 2 port (if available)

# Good luck

# Answer
> 1 votes
You may find that there is a process on Ubuntu that is grabbing the newly created CDC/ACM port as soon as it enters programming mode.

With the Leonardo and Micro you have a CDC/ACM port while it's running, and when the board resets to enter programming mode that CDC/ACM port is destroyed and an entirely new one (hopefully under the same name) is created. The process `modem-manager` can grab that newly created CDC/ACM device thinking it's a modem and try to configure it as such, thus locking you out of the port. A similar process in Debian is `brltty` which tries to configure the CDC/ACM port as a braille TTY interface.

You can check to see what process has the CDC/ACM device node open if any with the `lsof` command:

```
sudo lsof /dev/ttyACM0

```

If you find that you do have `modem-manager` running on your system (I'm not sure if it's still default or not, it's been a while since I used Ubuntu, preferring the purity of Debian) it's best to completely remove it:

```
sudo apt-get remove modemmanager

```

# Answer
> 0 votes
This is all the symptoms of not having the correct board selected in the IDE. The fact that the LEDs are flashing during uploading means it's probably not a comms issue.

I understand you wrote that you have selected the correct board already, but please double/triple-check.

I work with both UNOs and Nanos, this is a classic mistake I make all the time.

# Answer
> -1 votes
```
sudo chmod 666 /dev/ttyACM{for your arduino board}
```

mine happens to be "/dev/ttyACM1" so i did

```
sudo chmod 666 /dev/ttyACM1
```

---
Tags: uploading, arduino-micro, ubuntu
---


# Question
Title: Water flow sensor unable to get readings
I connected my "arduino(nano)" to "water flow sensor" and wrote a code which simply prints the readings like 0-1023 and tested it. First i got the readings but now i'm not getting it.
My code looks something like this.

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

void loop(){
 int vla=analogRead(2);
 Serial.println(vla);
 delay(1500);
}

```

and my connection.

> Sensor to Supply module
> Vcc --\> 5v
> Gnd --\> Gnd
>
> Sensor to Arduino(Nano)
> Sig --\> D2

# Answer
> Sensor to Arduino(Nano) Sig --\> D2

Your connections are wrong.

```
int vla=analogRead(2);

```

is reading from analog channel 2, which is pin A2 on your Nano, not D2

D2 is not an analog pin and thus you can't use it with `analogRead()`.
> 1 votes

---
Tags: sensors, arduino-nano, electronics
---


# Question
Title: Can I use my Arduino nano to upload sketch in Uno's ATmega328p chip?
I can not upload sketch to my UNO directly. My ATmega16U2 doesn't work.But the Atmega328P processor still work. I have an arduino nano lying around. Can I use it to upload sketches to Atmega328P directly. Thanks in advance

# Answer
Yes. You can. Either as a USB to UART adaptor and use the Uno's bootloader as you would with any bootloader-enabled breadboard Arduino, or as an Arduino ISP to program the chip directly through the ICSP pins as you would when putting the bootloader onto a blank chip.
> 0 votes

---
Tags: arduino-uno, arduino-nano, arduinoisp
---


# Question
Title: SIM900a Mini Modem, IMEI 0, help with TX RX pins
I have Simcom **SIM900a** GSM *(SIM900a Mini DEV Board v3.9.2)* and I am interfacing it with **Arduino UNO**. I have no idea how to connect SIM900a to Arduino UNO.

What I did now is:

I connect the following Pin from above image to:

**5** to: `GND (Digital GND near Pin 13)`

**6** to: `5V of Arduino`

**2** to: `GND of Arduino near 5V`

**3** to: `Digital Pin 0 of Arduino (RX)`

**4** to: `Digital Pin 1 of Arduino (TX)`

**1** to: (No idea)

From Picture option **7**, **8**, **9** are not connected to anything.

Can you please guide me am I doing right?

I am getting hard time to find out what is `TX` and `RX` in my SIM900a module as it is not written there.

My SIM900a looks like **this**, **this***(Schematics given)* and this.

When I upload the sketch:

**File \> Examples \> GSM \> TestModem:**

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

**PS:**

I saw this schematic here which is way different than what I am doing.

**PSS:**

Hints, am I supposed to provide external power supply of `5 V` `2 A` OR do I need some kind of converters `(TTL to RS232 converter)` ?

# Answer
Finally I found solution to this problem:

My Pins connections were wrong, it should not be: `0` and `1` it should be `2` & `3`:

```
2 - RX Arduino
3 - TX Arduino

```

also `SoftwareSerial.h` is not working with `SIM900A`

**Pins:**

All connections should be like this:

```
SIM900A - Arduino
=================
VCC     - VDC (+5V)
GND     - GND
5VR     - Connect to Arduino TX (Pin 3)
5VT     - Connect to Arduino RX (Pin 2)

```

As discussed here.

**Very important:**

Any program with header/library: `#include <SoftwareSerial.h>` is not working but `#include <GSM.h>` is working fine. As `SoftwareSerial.h` only work with `GSM Shield` and `SIM900A` isn't a shield.

**Program/Sketch to Upload:**

```
/*
SMS sender

created 25 Feb 2012
Originally written by Tom Igoe
But this is modified version
*/

// Include the GSM library
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

void setup(){
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial){
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;

// Start SIM900A GSM

while (notConnected){
    Serial.println("Status 1: Please wait a while, If it taking lot of time, \nmeans you have wrong pin connections.");
    // If your SIM has PIN, pass it as a parameter of begin() in quotes
    if (gsmAccess.begin(PINNUMBER) == GSM_READY){
    Serial.println("Status 2: GSM is ready.");
    notConnected = false;
}else{
    Serial.println("Status 3: Not connected");
    delay(1000);
  }
}
    Serial.println("Status 4: GSM initialized. " );

    // calling function to send message
    sendMessage();
}

void loop(){
    // empty loop
}

// method to send message to specific number just once.
void sendMessage(){
    Serial.print("Message is sending...: ");
    // send the message
    sms.beginSMS("03XXXXXXX "); // Replace XXXXXXX with your mobile number.
    sms.print("This is just some message"); // Message content, replace with your's.
    sms.endSMS();
    Serial.println("COMPLETE!\n");
    Serial.println("Message Sent...!\n");
}

```

**Bam**, It is working, and it successfully can send message.

**Things to remember:**

1. As everywhere being said you need to supply external power supply to SIM900A it requires `5 Volts` and `2 Amphs`.
2. Connect `GND` of SIM900A to Arduino `GND`.
3. Connect `VCC+` *(above photo connection 2)* to `5V` pin of Arduino.

**One Problem:** When I upload sketch of:

> Example \> GSM \> TestModem:

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

I cannot get IMEI from SIM900A but I can send message.
> 1 votes

# Answer
Your wiring is correct:

```
6 - VDC (+5V)
5 - GND
4 - RX (connect to Arduino TX - pin 1 for UNO)
3 - TX (connect to Arduino RX - pin 0 for UNO)

```

5VDC/2A power supply is must, otherwise module will be resetting when wireless radio is turned on. When using separate power supply, don't forget to connect Arduino GND and module GND.

The RX/TX on the module are depicted as 5VR/5VT (and 3VR/3VT for 3.3V pins).

The better way to get started / debug would be to use USB-to-serial converter: set the baudrate as 115200, connect and type AT and enter. Shall respond with AT (echo) and OK.

PS: The red wire (6) shall be on the left and black (5) on the right side, according to the board connector.
> 0 votes

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


# Question
Title: SIM900A showing Starting modem test...ERROR, no modem answer. Checking IMEI...Modem's IMEI: 0
---

**Edit:**

Solution can be found **HERE**

---

I am trying to interface Simcom **SIM900A** GSM *(SIM900a Mini DEV Board v3.9.2)* and I tryed interfacing it with **Arduino UNO**. I have connected as:

**Pins:**

```
SIM900A - Arduino
=================
VCC     - VDC (+5V)
GND     - GND
5VR     - Connect to Arduino TX (Pin 1)
5VT     - Connect to Arduino RX (Pin 0)

```

**Power Supply (External):**

```
5V 2A

```

**Problem** When I upload sketch of:

```
Example > GSM > TestModem:

```

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

**Other info:**

* By supplying `5V, 2A` the `SIM900A` `Power LED` `ON` continuesly and `Signal LED` `blink with certain period of time` which mean I am okay with signal.
* I connected SIM900A and Arduino with `Male to Male` \+ `Female to Female` as I don't have `Male to Female` wires. I tested the wires with Multimeter and it's prefectly working.
* I tested uploading other sketches of sending sms but not successful. Note that, I have load + free sms on SIM.
* Power supply is actually Adapter *(no transformer but circuit)* with output of `5.1 Volts`

My previous post can be checked **HERE**

**PS:**

Yesterday just for a minute I noted: Both LEDs *(Power + Signal)* of SIM900A were `blinking at same time`. But then by restarting it gets Okay again.

Please help. I am likely to die becuase of tension.

# Answer
---

**Note:**

Detailed Solution can be found **Here**

---

**Excerpt:**

My Pins connections were wrong, it should not be: `0` and `1` it should be `2` & `3`

Also `SoftwareSerial.h` is not working with `SIM900A`

**Pins:**

All connections should be like this:

```
SIM900A - Arduino
=================
VCC     - VDC (+5V)
GND     - GND
5VR     - Connect to Arduino TX (Pin 3)
5VT     - Connect to Arduino RX (Pin 2)

```

Details **Here**
> 0 votes

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


# Question
Title: Communicating to arduino as fast as real-time
I'm trying to control some pneumatic cylinders with arduino. I want to do the calculations on pc and then send the command to arduino to control the air flow to pneumatic cylinders. It's very important that arduino receive these commands super fast (in real time if it's possible) so that I can control air flow in millisecond precision.

What is the fastest way to communicate to arduino (Read and write). I tested serial communication and it's very slow in compare to real-time. Is there any specific settings for serial communications that i need to do to increase it's speed? Should I use LAN connection? Or maybe I should use for example Arduino YUN with an OS?

# Answer
Going over USB will add about a millisecond of jitter to your data in both the sensing and command directions. Using a part with direct USB rather than then needing to go through a serial link from USB chip to processor could help limit what is added on top of that, but it will still be there. If you could get a USB high speed solution that would reduce this as the polling interval is shorter, but there are few such solutions for simple microcontrollers. Ultimately, USB is meant to move a lot of data in a reasonable amount of time - it is *not* designed to move small messages promptly.

True realtime systems put the processing and the actuation in tightly connected local circuitry. With the increasing isolation of PC processors from external I/O by multiple layers of intermediate architecture on the chip and motherboard, you see very little realtime use of PCs today. An embedded board with a decent processor and good direct I/O (Beaglebone, maybe the Linux side of a Yun or comparable) would be better, but be aware that multi-tasking operating systems like Linux or Windows are fundamentally in conflict with real-time performance - it takes very complex hacks to make that work, for example running a realtime scheduler directly on the hardware and having it run an ordinary operating system as a low priority task.

The architecturally cleanest solutions would be to find a way to fit your calculations on a fast single processor - in the realm of Arduino-style solutions perhaps one of the latest in the Teensy series. Beyond that you are really out of the realm where this could be considered an Arduino question - trying for example to run a realtime scheduler on the Linux half of a Yun is really not related to "Arduino" at all.

One thing that is not clear however is if your system needs to *react* in real time, or merely to *sequence* with precise timing. Mere sequencing is a far easier problem, as you can send the data a bit in advance of need and hold it in a buffer, so that communication latency doesn't delay operations. A 3d printer could be an example of this - the really complex calculations are done on a PC, then commands are drip-fed a bit in advance of need to a simpler executive traditionally running on a repackaged Arduino Mega, and that moves the motors with sub-millisecond pulse precision. Given that there are no realtime inputs to the calculations, their results can also be stored on an SD card for use months later with no PC connection at all. If your need does reduce to such pure non-reactive sequencing then things are a lot simpler; if it doesn't, then the rest of the explanation here applies.
> 4 votes

---
Tags: serial, communication
---


title: MFRC522 Only working sometimes

text:
# Question
Title: MFRC522 Only working sometimes
```
   /*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10       // Configurable, see typical pin layout above

MFRC522 MFRC522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    MFRC522.PCD_Init();     // Init MFRC522
    MFRC522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
  Serial.print("...");
}

void loop() {
    // Look for new cards
    if ( ! MFRC522.PICC_IsNewCardPresent()) {
    Serial.print("IsNewCardPresent");
        return;
    }

    // Select one of the cards
    if ( ! MFRC522.PICC_ReadCardSerial()) {
    Serial.print("ReadCardSerial");
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    MFRC522.PICC_DumpToSerial(&(MFRC522.uid));
}

```

I have recently purchased a RC522 RFID Module for my Arduino UNO. I connected everything, and started the IDE, downloaded the correct library, and ran the DumpInfo example program. The first time that I ran it, all went well, and when I swiped a card in fro, I recieved the correct data dump.

However, I started it up today, and reset everything, ran a new program to clear the Arduino, restarted my PC, and it still did not work. In the serial monitor it says that all is well, no error messages or anything. But, when I put a card in front of it, absolutely nothing happens.

Any help would be great!

# Answer
Check your power supply. I've seen so many weird results from inconsistent/under powered circuits. It's worth a look.

What does your circuit look like? Are you powering the RFID reader from the Arduino or it's own source? Are the grounds coupled?
> 1 votes

# Answer
If I am right then you have soldered the pins of the module yourself and I recommend you to desolder the pins and soldered them again.

I also used RC522 RFID Module with an Arduino and I faced same type of problem with the module. This way worked for me.
> 1 votes

# Answer
The first thing you could try is to increase the baud rate to 115200. I'm using a different library, and in the `auth_read_write.ino` sketch the `Serial.begin()` comments says "Read a fast as possible. There is a limit for how long we are allowed to read from the tags".

If changing the baud rate doesn't work, then have a look at this answer: RFID-RC522 not working, red led is on. It has a link to a different library which worked for me.
> 1 votes

---
Tags: rfid
---


# Question
Title: Arduino Uno with PWM driven motor and 433 MHz wireless receiver don't work
I am fairly new to the Arduino topic and I'm trying to get a few things to work together.

At the moment I'm using an Arduino Uno board, but planning to use an Arduino Nano for this.

First I tried setting up a DC motor that can be controlled via PWM, which works perfectly when used standalone. I can start/stop the motor and change speed depending on the value I send to the PWM pin.

Next, I tried to use an RF-5V wireless receiver to work with a remote control from remote switched power outlets. For this one I followed the instructions on how to build a 433 MHz sniffer. This all by itself works as well. I can receive different codes depending on which keys on the remote I am pressing.

Now the fun part started: I wanted to integrate both projects into one, so I could use the remote to start/stop the motor. So I came up with the following circuit:

(The sketch is updated so it shows the right pins matching the code)

And the following code (which is partly from the instructions mentioned above):

```
#include <RCSwitch.h>

// init 433MHz lib
RCSwitch mySwitch = RCSwitch();
unsigned long lOldValue=0;  // to check for consecutive reads on 433MHz
int motorPin = 5; // PWM-Pin to use for motor

void setup() {
  pinMode(motorPin, OUTPUT);
  Serial.begin(9600);
  // set-up rf receiver
  mySwitch.enableReceive(0);
  // 433MHz Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    int value = mySwitch.getReceivedValue();
    // only react, if at least two times same value received
    if (value == lOldValue) {
      if (value == 0) {
        Serial.print("Unknown encoding");
      } else {
        Serial.print("Received ");
        Serial.print( mySwitch.getReceivedValue() );
        Serial.print(" / ");
        Serial.print( mySwitch.getReceivedBitlength() );
        Serial.print("bit ");
        Serial.print("Protocol: ");
        Serial.println( mySwitch.getReceivedProtocol() );
        // One of the keys on the remote
        if (value == 274393) {
          Serial.println("got start code, starting motor");
          analogWrite(motorPin, 100); // start the motor
        }
        // another key on the remote
        if (value == 270384) {
          Serial.println("got stop code, stopping motor");
          analogWrite(motorPin, 0); // stop the motor
        }
      }
    }
    lOldValue = value;
    mySwitch.resetAvailable();
  }
}

```

When I run the code and click on the remote, I get different values shown depending on the key I press. So the wireless receiver works as expected.

When I receive the right value for starting the motor, the motor really begins to turn, so this works as well.

And here the fun part starts:

As soon as I use the `analogWrite` function to send data to the PWM port the motor is connected to, the wireless receiver stops working (or at least I do not get any more values when pressing a key on the remote).

I found a few similar posts/problem descriptions on the net which said to try the following:

* Use another pin for PWM (due to possible interrupt conflicts). I tried that as well, same behaviour.
* Use external power supply instead of USB-Cable, which helped somebody resolve this issue. Not here. Does not work either.

**So the question is:**

Does anybody know how to combine those two things together so I can use the wireless receiver to get commands and switch on/off the motor with it on an Arduino Uno?

And would this solution probably work with an Arduino Nano as well?

**Update:**

I changed the motor against a LED, same behaviour. So its not related to the motor itself.

I found out that when i use some timers to set the motor pwm to 0 with the analogWrite function, that the wireless receiver starts working again. So it really looks like there is no way to use PWM and the wireless receiver together.

I also changed the pin for the receiver from 2 to 3 (and of course changed the code to use the right pin) and used other PWM pins for using with the motor. But still to no success.

Does anyone have an idea on how to bring both the wireless receiver and PWM driven things to work together? Might this be an hardware issue (due to interrupts) or a library issue for the rcswitch?

# Answer
You are asking too much from the Arduino if you expect it to drive a motor with only the on-board 5V regulator AND the radio. Eliminate at least the motor connection to the 5V and use a MOSFET to drive the motor with a stand-alone power source like an alkaline battery pack of at least 6V - You need current to drive a motor and the UNO is limited to 500mA. Once you PWM the MOSFET, it should handle the motor with ease. A IR510 is good for this use. You will need a 10K pull-down resistor to the Gate Pin to keep it LOW when no signal is present. This should get you going in the right direction. 0.01 ceramic filter capacitors to the - and + leads to ground around the motor is also helpful. Look up on-line how others do this.
> 1 votes

---
Tags: arduino-uno, pwm, wireless
---


# Question
Title: Powering a Nano with a 5v mini USB adaptor
I have made a simple temp sensing circuit that lights an LED when it reaches a certain point. It works perfectly when powered by a USB plugged in to the laptop but when I connect it to a 5V supply with a mini-USB connection nothing happens.

Is this correct and do I need to send power directly to the board on the 5V pin?

Many thanks, Jack

# Answer
Thanks all. I found a different power source with a mini-usb connector and it works fine. I think when plugging it in to the PC the Nano makes some faint clicking noises but when direct to 5v plug it does not? I'm not sure so I'll re-test. It was the lack of clicking that lead me to believe it wasn't working as I can't see the on board LEDs using my enclosure.

I don't know about the accuracy but it seems to work for my situation - it is to be placed in a fridge that recently turned itself in to a freezer but has since fixed itself. This project is an early warning system in case it decides to do it again.

Thanks again. Jack
> 1 votes

---
Tags: arduino-nano
---


title: String to Int Array

text:
# Question
Title: String to Int Array
I have a string:

```
String cod=server.arg("codice");

```

where codice (an IR sequence) is retrieved from a webserver. For example:

codice=1, 2, 3, 4

In which the syntax can be modified.

So, cod is a string that contains numbers separated with ", "

To send the IR code i use:

```
irsend.sendRaw(rawData, 67, 38);

```

I don't know how to convert the String to Int (rawData) as requested by rsend.sendRaw.

# Answer
Use `strtok` to split the char array into the different parts, then use `atoi` on each of the parts to convert it to an int. (`atoi` ignores whitespace)

```
char* str = "4532, 4488,  548, 1694,  574";

const size_t bufferSize = 5;
int arr[bufferSize];

char *p = strtok(str, ",");
size_t index = 0;

while (p != nullptr && index < bufferSize) {
  arr[index++] = atoi(p);
  p = strtok(NULL, ",");
}

for (size_t i = 0; i < index; i++)
  Serial.println(arr[i]);

```

**Edit:** You just edited your post, and it seems like you really need to use Strings (capital S). There are two ways to go about it: you have to keep in mind that `String::c_str()` returns the actual pointer to the internal null terminated char array inside the String object, and that `strtok` is destructive (it replaces the delimiters with null characters).
If you need the String for other things after converting it to an array of ints, you'll have to make a copy first:

```
String cod = "4532, 4488,  548, 1694,  574";
char *str = new char[cod.length() + 1];
strcpy(str, cod.c_str());

```

Don't forget to free the memory afterwards:

```
delete[] str;

```

If you don't care about destroying the String, you can just use:

```
String cod = "4532, 4488,  548, 1694,  574";
char *str = cod.c_str();

```

**Edit 2:** The ESP8266 compiler doesn't allow implicit conversion from `const char*` (read only) to `char*` (as `strtok` argument). To get around it, the clean solution is to copy it, as explained in my first edit.
If you really don't need the String afterwards, and you don't want to waste memory on the copy, you can just use an explicit type cast:

```
String cod = "4532, 4488,  548, 1694,  574";
char *str = (char*)cod.c_str();

```

The AVR compiler doesn't have any problems converting `String::c_str()` to `char*`
> 2 votes

---
Tags: array
---


# Question
Title: How do I properly convert a pointer (uint8_t* or void*) to a "normal" integer?
I'm writing a program for arduino that needs dynamic memory allocation frequently, but as I don't want the memory to get fragmented, I'm also writing a "memory handler" for it. This memory handler would need to do calculations involving both pointers and `size_t` variables, like this (example code is not part of program, but the structure of the calculations is the same):

```
size_t freeMemSize = nextPointer - currentPointer - currentSize;

```

Which would calculate the size of free memory between two reserved spaces.

Of course, arduino doesn't want to swallow this code, as it compares incompatible types. My questions are:

* Is a cast to the correct integer type enough to solve the problem?
* If it is, what is the "normal integer" counterpart of a pointer?

I guess this varies from processor to processor, so I should look for something like size\_t, but for memory indices instead of sizes.

Board: Uno, Nano
IDE version: 1.8.2

# Answer
> 0 votes
Assume the following declarations:

```
uint8_t* nextPointer;
uint8_t* currentPointer;
size_t currentSize;

```

Then the expression is valid:

```
size_t freeMemSize = nextPointer - currentPointer - currentSize;

```

If any of the pointers are `void*` the compiler cannot calculate the expression (pointer or size).

Cheers!

---
Tags: arduino-uno, arduino-nano, variables, pointer
---


# Question
Title: ESP8266 sketch worked a few times but now doesn't seem to run
When I flash my code:

```
/* Create a WiFi access point and provide a web server on it.

 Author: Lucio A. Rocha
 Last Update: 21 Aug 2016

*/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

/* Set these to your desired credentials. */
const char *ssid = "MaisonBlanche";
const char *password = "7932gLBw";

ESP8266WebServer server(80);

const int led = 2;  //GPIO2

/* Just a little test message.  Go to http://192.168.4.1 in a web browser
 * connected to this access point to see it.
 */
void handleRoot() {

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"<html>\
  <head>\
    <title>MicroCloud</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h3>You are connected on MicroCloud #2!</h3>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p>Status: Light ON</h1></p>\
    <p><a href=\"http://192.168.4.1/on\"><h1>Turn ON</h1></a></p>\
    <p></p>\
    <p><a href=\"http://192.168.4.1/off\"><h1>Turn OFF</h1></a></p>\
  </body>\
</html>",

    hr, min % 60, sec % 60
  );
  server.send ( 200, "text/html", temp );

}

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");

  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  pinMode(led, OUTPUT);
  digitalWrite ( led, HIGH );

  //URLs available to query
  server.on("/", handleRoot);
  server.on ( "/on", turnON );
  server.on ( "/off", turnOFF );
  server.begin();
  Serial.println("HTTP server started");

}

void turnON(){

  digitalWrite ( led, HIGH );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"<html>\
  <head>\
    <title>MicroCloud</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h3>Request: Light ON</h3>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p></p>\
    <p>Status: Light ON</h1></p>\
    <p><a href=\"http://192.168.4.1/on\"><h1>Turn ON</h1></a></p>\
    <p></p>\
    <p><a href=\"http://192.168.4.1/off\"><h1>Turn OFF</h1></a></p>\
  </body>\
</html>",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void turnOFF(){

  digitalWrite ( led, LOW );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"<html>\
  <head>\
    <title>MicroCloud</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h3>Request: Light OFF</h3>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p>Status: Light OFF</p>\
    <p><a href=\"http://192.168.4.1/on\"><h1>Turn ON</h1></a></p>\
    <p></p>\
    <p><a href=\"http://192.168.4.1/off\"><h1>Turn OFF</h1></a></p>\
  </body>\
</html>",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void loop() {
  server.handleClient();
}

```

onto the ESP8266 with this setup:

For my serial output I get:

```
en 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

```

I got it to work semi successfully before now. I was basically following along with https://create.arduino.cc/projecthub/luciorocha/esp8266-control-led-with-smartphone-8a59f3. I got to the point where the code was being run successfully - but then something unexpected happened, when I thought the LED would go on, when I selected the `turn on` button, nothing happened. When I selected `turn off`, the blue LED on the board turned on and stayed steady. Then, when I selected `turn on` again, the LED on board went off. I thought the sketch was supposed to manipulate pin 2, but it seemed to be manipulating the onboard LED instead, and in the reverse way that it should.

Now, I can upload it, but the only thing it does after that is spit out the above serial output. I have tried running it with:

```
GND -> GND
VCC -> 3.3v
CH_PD -> 3.3v

```

Other sketches seem to work, so maybe something I did triggered an ESP8266 setting which now conflicts with something in the code?

**UPDATE**

I double checked that other sketches are running - also running is a sketch that connects the ESP8266 to my network - it connects and gets assigned an IP. I made this simplified sketch of the one above, involving the connection process:

```
/* Create a WiFi access point and provide a web server on it.

 Author: Lucio A. Rocha
 Last Update: 21 Aug 2016

*/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");

  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP("MaisonBlanche", "7932gLBw");

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
}

void loop() {

}

```

The only thing it outputs (no connection) to serial is:

```
0, len 1384, room 16
tail 8
chksum 0x2d
csumcL⸮
~ld

```

So it seems as if the problem is with my code, or it is able to connect to a network as a client but not as a `softAP`?

**UPDATE**

I ran this code:

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

ESP8266WebServer server(80);

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

  Serial.print("Setting soft-AP ... ");
  boolean result = WiFi.softAP("MaisonBlanche", "7932gLBw");
  if(result == true)
  {
    Serial.println("Ready");
  }
  else
  {
    Serial.println("Failed!");
  }
}

void loop()
{
  Serial.printf("Stations connected = %d\n", WiFi.softAPgetStationNum());
  delay(3000);
}

```

The same garbled serial output appears, and then it started outputting:

`Stations connected = 0`

Then the output changed to:

`Stations connected = 1`

Does this just mean it is successfully connecting using `softAP`?

**UPDATE**

I think I have narrowed it down what is not working to the `ESP8266WebServer`. I used this code:

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

ESP8266WebServer server(80);

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

  Serial.print("Setting soft-AP ... ");
  boolean result = WiFi.softAP("MaisonBlanche", "7932gLBw");
  if(result == true)
  {
    Serial.println("Ready");
  }
  else
  {
    Serial.println("Failed!");
  }

  server.on("/", handleRoot);
  server.begin();
}

void handleRoot() {

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

    "<html>\
      <head>\
        <title>BEASTMODE</title>\
        <style>\
          body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
        </style>\
      </head>\
      <body>\
        <h3>You are connected on BEASTMODE!</h3>\
      </body>\
    </html>",

    hr, min % 60, sec % 60
  );
  server.send ( 200, "text/html", temp );
}

void loop()
{
  Serial.printf("Stations connected = %d\n", WiFi.softAPgetStationNum());
  //delay(3000);
  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());
  server.handleClient();
}

```

When the loop starts it begins to output:

```
Soft-AP IP address = 192.168.4.1
Stations connected = 0

```

It seems to go between 0 stations connected and 1 station connected. I go to 192.168.1.4 in my browser, and it never loads the page, it just times out. So if it has a `softAP` IP address - but it is not accessible, then maybe the server isn't working for some reason. Also I read how you can put the chip into different modes (STA/AP/etc

# Answer
> 0 votes
This works fine, doesn't use ESP8266WebServer which seems to be the culprit. It is the web server from `ESP8266WiFi`. At the bottom there is a link to a blinking LED example which works for me. You just type in `<ip>/gpio/0` in browser for off, and change it to `/gpio/1` for on.

---
Tags: arduino-uno, esp8266, wifi, sketch, web-server
---


title: mcufriend SPI connection

text:
# Question
Title: mcufriend SPI connection
Bought a cheap LCD form china (mcufriend, pictured below) and I cant understand which pin is which to use it with the SPI interface (starting to get worried that I can't use it), I've figured out this much:

* LCD\_RST; reset pin
* LCD\_CS; chip select
* LCD\_RS;
* LCD\_WR;
* LCD\_RD;

Which of those is MOSI, SCK, DC? Trying to use it with a ESP8266 (ESP-12).

# Answer
You can't use that TFT screen with SPI. The SPI interface (`SD_DI`, `SD_DO`, `SC_SCK` and `SD_SS`) is for the SD card slot only.

All the pins starting `LCD_` are the 8-bit parallel ("8080" style) interface for controlling the TFT screen.
> 2 votes

---
Tags: esp8266, spi, display
---


# Question
Title: How can I read a piezo sensor and have it output a fixed voltage?
I'm trying to creature an instrument out of a few boards I have. The plan is to have piezo sensors wait for a hit, then be read by a digital pin, then execute code based on what piezo sensor was hit.

I know how to make a note play, but I don't know how to read a signal from a piezo that's between 3V and 5V. I'm not worried about velocity measurements, I just want there to be a hit, register the hit through arduino, then relay the pin number to a track number.

I read that pin change interrupts can read a signal instantly.

Below is some example code for my audio output board that plays audio files. This specific bit of code is for "notes" on an instrument.

```
          wTrig.masterGain(-8);                 // Lower main volume
          wTrig.trackPlayPoly(6);               // Play first note
          delay(1000);
          wTrig.trackPlayPoly(7);               // Play second note
          delay(1000);
          wTrig.trackPlayPoly(8);               // Play third note
          delay(1000);
          wTrig.trackFade(6, -50, 5000, 1);     // Fade Track 6 to -50dB and stop
          wTrig.trackFade(7, -50, 5000, 1);     // Fade Track 7 to -50dB and stop
          wTrig.trackFade(8, -50, 5000, 1);     // Fade Track 8 to -50dB and stop

```

I don't have experience with code, but this is how I think activating a note would work:

```
wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

```

As far as limiting voltage, don't I just need to put some resistors in circuit with the piezo sensors?

In psuedo-code, this is what I want to make happen:

```
Listen for signal from any pin
Store that pin number as a variable
wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

```

# Answer
> 1 votes
A piezo will output a decaying sinusoid when you feed it an impulse (a hit on the attached surface). Problem with a high frequency sinusoid is that one: half the time it's negative, and two: it forces a near-real-time monitoring of the analog voltage there, ie no or small delays in your code.

I've made a pattern recognition 'drum' with piezos, and the general approach was to first start with plotting the analog voltage of the piezo. This is done by putting the positive of the piezo to an analog pin and the negative to ground, *and* a 1M resistor between the leads (this value worked for me, play with different values to see what works best). Then do a serial plot (ctrl shift L in the IDE) and observe:

* how high the peak is for different distances and strengths of 'knocks'
* how many times a significant peak occurs before decaying.

Your end goal is to have the Arduino recognize a peak by seeing when the analog reading is above a threshold value , then have a dead period where it ignores subsequent peaks (so it doesn't read multiple events on a single sinusoid), and then play your note. Longer dead period means less false-positives, shorter means more responsive.

I apologize for the long-windedness of my somewhat ambiguous response, I'll try to remember to paste my code when I'm at my computer tomorrow.

# Answer
> 1 votes
If the piezo is mounted to a surface, and you're hitting the surface to create vibrations, it is complicated as mentioned in the other answer, and it would be a good idea to connect piezo brass to a stable 2.5V and use rail clamping diodes on the pin. For this purpose, you may be okay with just a couple 100 ohm resistors as a divider and a capacitor between ground and the 2.5V. The proper audio way is more involved.

But if you're tapping the piezo directly with your finger, or tapping a thin plate and foam on top of the piezo, it's a lot simpler. I've done this with a 100k ohm resistor in parallel (better response and consistency than 1 M ohm) and 5V zener diode in parallel for a 5V processor. An analog pin with AnalogRead function can determine the voltage. Brass wired to ground, center area wired to pin. I've found that placing thin foam underneath everything gets rid of the crosstalk, especially if you don't need velocity sensitivity.

I would avoid using the delay function because it will prevent other piezos from working during that time. Millis() calculations allow other actions to be performed.

---
Tags: programming, piezo
---


title: Ultrasonic HC-SR04 echo and trig pins

text:
# Question
Title: Ultrasonic HC-SR04 echo and trig pins
I am doing a watch with GPS tracker project. I am using an Ultrasonic HC-SR04 sensor. I don't know where to connect the **Echo** and **trig** pins with my Arduino. Please let me know how to connect it.

# Answer
To any 2 free IO pins.

To quote sparkfuns datasheet:

> (1) Using IO trigger for at least 10us high level s ignal,
> (2) The Module automatically sends eight 40 kHz and detect whether there is a pulse signal back.
> (3) IF the signal back, through high level , time of high output IO duration is the time from sending ultrasonic to returning.
> Test distance = (high level time×velocity of sound (340M/S) / 2,

In other words you send a short pulse to trigger pin and then wait for the echo pulse and measure how long it was high. Divide the number of microseconds it was high by 58 and you have the distance in centimetres ( use 148 for inches)
> 3 votes

# Answer
You can connect them to two GPIO pins. It does not matter much which ones (probably between 2 and 12 since these are not used by other functions like the builtin led or RX/TX).

In the following example pins 9 and 10 are used:

Example

Fragment related to the pins:

> The HC-SR04 Ultrasonic Module has 4 pins, Ground, VCC, Trig and Echo. The Ground and the VCC pins of the module needs to be connected to the Ground and the 5 volts pins on the Arduino Board respectively and the trig and echo pins to any Digital I/O pin on the Arduino Board.
> 1 votes

---
Tags: hc-sr04
---


title: for loop iterated only once

text:
# Question
Title: for loop iterated only once
I have written a little project, it works so far as it should but the for loop is only iterated once, then the result is displayed on the LCD.

```
#include <LiquidCrystal.h>
#include <stdlib.h>
const int Contrast=20;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int led = A5;
const int button = A3;

void setup() {
  Serial.begin(9600);
analogWrite(6,Contrast);
lcd.begin(16, 2);

pinMode(led, OUTPUT);
digitalWrite(led,LOW);
pinMode(button, INPUT_PULLUP);
}

void loop() {

unsigned long mittelwert = 0;

for(int i=0; i<10; i++){
  unsigned long r = random(1,5000);
  unsigned long now = millis();

  digitalWrite(led,HIGH);

  while (digitalRead(button) == HIGH){
    lcd.setCursor(0,0);
    lcd.print("druecken");
  }
  mittelwert = mittelwert + millis() - now;
  digitalWrite(led, LOW);  //LED aus

}

lcd.clear();
lcd.setCursor(0,0); //setze Cursor auf 1.Stelle in der 1. Zeile
lcd.print(mittelwert/1000);
lcd.setCursor(0,1);
lcd.print("Sekunden");

delay(5000);
lcd.clear();

}

```

# Answer
> 1 votes
It does iterate 10 times, it's just really fast. You probably want to wait some time to debounce the button, and then wait for the button to be released again.

I don't know why you have to keep printing to the LCD during the loop. Wouldn't printing it once before the loop be enough?

There's something wrong with your math as well. To get an average value, you add up all values, and divide by the number of values. Your variable name `mittelwert` is confusing, `totalTime` would be more appropriate.
`averageTime/1000` is an integer division, so it floors the result. For example, if the average time is 999 ms, ⌊999 / 1000⌋ == 0. Use a floating point division if you want a decimal number.

In your setup, you don't have to use `digitalWrite(led, LOW);` because it is already initialized to `LOW` when you start the program.

```
const int led = LED_BUILTIN;
const int button = A3;

const int numberOfTests = 10; // repeat 10 times

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

  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);
}

void loop() {
  unsigned long totalTime = 0;
  for (int i = 0; i < numberOfTests; i++) { // repeat 10 times
    int r = random(1, 5000);
    delay(r); // wait a random number of milliseconds (between 0.001 s and 5 s)

    digitalWrite(led, HIGH); // turn LED on
    unsigned long startTime = millis();

    Serial.println("Press button");
    while (digitalRead(button) == HIGH); // wait for the button to be pressed

    totalTime += millis() - startTime;
    digitalWrite(led, LOW); // turn LED off

    delay(25); // button debounce
    while (digitalRead(button) == LOW); // wait for the button to be released
  }

  unsigned long averageTime = totalTime / numberOfTests;
  Serial.print(averageTime);
  Serial.println(" milliseconds");
  Serial.print((float)averageTime / 1000.0, 3); // print the result of the floating point division with 3 digits after the decimal point
  Serial.println(" seconds");

  delay(10000); // Wait 10 seconds before repeating
}

```

# Answer
> 1 votes
Your button is configured as an input with a pullup. Therefore, except when the button is depressed to ground that input, this nested loop

```
while (digitalRead(button) == HIGH){
   lcd.setCursor(0,0);
   lcd.print("druecken");
}

```

will endlessly repeat, preventing execution from advancing.

Given that your question fails to state what you are hoping to *accomplish* it's not possible to make any corrective recommendations. If you do want to make use of the button, you should probably first search and read the existing questions here having to do with debouncing.

---
Tags: arduino-uno, lcd, button, display
---


# Question
Title: How to connect capacitive touch sensor to Arduino?
The capacitive touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my Arduino Micro, correct?

Also, I need to power 2 of these capacitive touch sensors along with an IMU. How do you power multiple sensors on the Arduino Micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

# Answer
> The capacitative touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my arduino micro, correct?

Probably, yes. Without more details about what the sensor is we can't really comment.

> Also, I need to power 2 of these capacitative touch sensors along with an IMU. How do you power multiple sensors on the arduino micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

You can plug as many (within reason) items into the +5V and GND pins as you like. You can twist wires together, use screw terminal blocks, breadboard, solder, whatever you like, to connect the wires together to a single wire that goes to the pin.
> 1 votes

---
Tags: sensors, arduino-micro
---


# Question
Title: Send String to a function inside a class
I made a little class for handling menus. When creating a new instance, I pass a reference to the `oled` object made in `main.cpp`. Yet when I want to render a string using a variable, it throws an error. But I can pass a string directly to the render function with no problems. See comments in the code for what is working and what is not.

```
#include "Arduino.h"
#include "U8glib.h"
#pragma once

class Menu {
  U8GLIB_SSD1306_128X64& oled;

  public:
    Menu(U8GLIB_SSD1306_128X64& oled): oled(oled) {
      this->oled = oled;
    };
    void render() {
      this->oled.firstPage();
      do {
        String text = "test2";
        this->oled.setFont(u8g_font_unifont);
        this->oled.setPrintPos(0, 20);
        this->oled.drawStr(text); // not working
        this->oled.drawStr(text.c_str()); // not working
        this->oled.drawStr("works"); // works
      } while (this->oled.nextPage());
    }
  };

```

In the case of `this->oled.drawStr(text);` the error is:

```
error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(String&)

```

In case of `this->oled.drawStr(text.c_str())` the error is:

```
error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(const char*)

```

How I create the instance in `main.cpp`:

```
U8GLIB_SSD1306_128X64 oled(U8G_I2C_OPT_NONE);
Menu menu(oled);
menu.render();

```

# Answer
> 2 votes
Try with the new version, U8g2lib.

With that version, you can write code like this:

```
String t1 = "Grow";
String t2 = "Room";
u8g2.firstPage();
do {
  u8g2.setFont(u8g2_font_logisoso24_tf);
  u8g2.drawStr(32, 24, t1.c_str());
  u8g2.drawStr(32, 60, t2.c_str());
} while(u8g2.nextPage());

```

# Answer
> 0 votes
Forget the String class. It wastes memory on a system that is already constrained by memory. Define your strings as const char * and you won't have any problems.

```
const char* t1 = "Grow";
const char* t2 = "Room";
u8g2.firstPage();
do {
  u8g2.setFont(u8g2_font_logisoso24_tf);
  u8g2.drawStr(32, 24, t1);
  u8g2.drawStr(32, 60, t2);
} while(u8g2.nextPage());

```

---
Tags: lcd, string
---


# Question
Title: Controlling the Serial Monitor for 10 seconds
I am an amateur with Arduino and coding and I am learning in my lab class. My project consists of using a photoresistor to measure the brightness of a white LED. I have the following circuit built.

I am having problems with the code because I need the serial monitor to print every 1/10 of a second for 10 seconds. My professor started talking about the micros() function but never showed an example. I have an idea as to how I can utilize this function to control how long the Serial Monitor prints for but I have been unsuccessful. I know that setting a delay is good enough for reading every 1/10 of a second but how can I make the serial monitor print values for only 10 seconds?

I believe it should be a total of 100 readings.

This is my current code:

```
unsigned long start, finished, elapsed, total;
int analogInPin = A0;
int LEDreading;           // analog reading
int LEDpin = 9;           // LED on pin 9

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

void loop() {
  analogWrite(LEDpin,255);  // LED brightness
  start = millis();
  LEDreading = analogRead(analogInPin);
  Serial.println(LEDreading);
  delay(100);
  finished = millis();
  elapsed = finished - start;
  total = elapsed*100;

  if (total >= 10000){
    Serial.end();
}

```

# Answer
> 2 votes
Using `micros()` is very much like boiling an egg.

When you want your egg to be cooked just right you know that it needs to be in the boiling water for a certain amount of time. There's three ways you can achieve that:

1. Use an egg timer to alert you when the time has passed,
2. Sit and stare at the boiling pot counting the seconds as they slowly tick by (booooooring..... ...zzzZZZzzz...)
3. Remember what time you put the egg in the water and glance at the clock every so often to see how much time has passed.

Using `millis()` is like option 3. It tells you how many milliseconds have passed since the board was turned on (or since the last `millis()` rollover at roughly 49 days). So when you put the egg in the water you record the current time. Then you periodically compare the recorded time to the current time (a simple subtraction will suffice) to see if enough time has passed. When it has you remove the egg and chow down.

So to put that more in a coding context - when you start some operation, or want to measure a period of time from a point, you just save the time in a variable:

```
start = millis();

```

(`start` must be `uint32_t`, aka `unsigned long`). To find if enough time has passed you just subtract that saved time from the current time and it gives you the elapsed time, which you can compare to your required elapsed time:

```
if (millis() - start >= 100) {
}

```

1/10 of a second is 100ms, so if you hit a difference of 100ms (or more) then your time has arrived and you can do something.

If you want it to do it again after that then just set the "start" time to the current time again.

For instance, for your requirements:

```
void loop() {
    // Record the start time - the static means it
    // only happens once the first time loop() is run and
    // it remembers the value between iterations
    static uint32_t start = millis();

    // Somewhere to store the number of values we
    // have given - again, static so it remembers across
    // iterations of loop()
    static uint8_t count = 0;

    if (count < 100) { // No more than 100 counts
        if (millis() - start >= 100) { // Tick
            start = millis(); // Do it again in 100ms time

            // Add whatever you need for your readings here

            count++; // Add one to the count
        }
    }
}

```

# Answer
> 1 votes
Using `delay(100)` will cause the sketch to wait at that line for 100 milliseconds. That is not (quite) the same as **DOING** something every 100 milliseconds. The difference is that other things take time too, so the time will be 100 milliseconds plus how ever long everything else takes.

The solution used by @Majenko still has that problem in a small way, because a new `millis()` value is used to set the new value of `start`. In most situations, it will work fine, but it is possible that the either or both of the `millis()` results were more than 100 after the previous value of `start`. That would happen if code that replaces the comment took more than 100ms some time. The fix for that is very simple. Just change `start = millis()` to `start += 100`. That will attempt to speed up the following loop, if it was getting behind.

As a side note, it would be good to change the 100 millisecond references to a defined name. Either a `#define` or a `const`. Since the `millis()` function returns an "unsigned long" value, I would use the same data type for a related `const` value. That just means that the compiler will not have to (invisibly) convert between different types when doing the math operations.

```
#define REPORT_CYCLE 100
const unsigned long REPORT_CYCLE = 100; // milliseconds between measurement and reporting cycles

```

If you are a beginner, you may not have seen `static` variables yet. If you know about them, fine, but if not, they can be replaced by `global` scope variables.

The @Majenko code uses a fixed count of 100 iterations to do the measurement and reporting. That works fine as long as neither the *for 10 seconds* or *every 1/10 second* changes. If either of those change, the count limit would also need to be recalculated and changed. Instead, I would use another defined name for how long to do measurement and reporting cycles, and let the compiler handle how many times that actually is.

Doing an `analogWrite()` sets the value (brightness here), which will stay constant until changed again. Since your program only sets a single value, it only needs to be done once. Move that statement to `setup()`.

There is no need to do `Serial.end()` when the reporting is done. That disables serial communication, but is unneeded, if no more `Serial.println()` commands are executed anyway.

To avoid calling `millis()` multiple times in the same 'pass' (in each if test), I like to call it once, and save the result.

Taking the @Majenko code, plus your starting sample, and described changes gets

```
// Intervals in milliseconds
#define REPORT_CYCLE 100
#define REPORT_INTERVAL 10000
unsigned long nextStart, endTime;
int analogInPin = A0;
int LEDreading;           // analog reading
int LEDpin = 9;           // LED on pin 9

void setup() {
  Serial.begin(9600);
  analogWrite(LEDpin,255);  // LED brightness
  nextStart = millis(); // Time for "right now"
  endTime = nextStart + REPORT_INTERVAL;
}

void loop() {
  unsigned long now = millis();
  if (now < endTime) { // still need to do more reporting
    if (now >= nextStart) { // time to get and report another reading
      nextStart += REPORT_CYCLE; // When the next reading should be done

      LEDreading = analogRead(analogInPin);
      Serial.println(LEDreading);
    }
  }
  // do other things, both while still reporting, and after reporting is done
}

```

---
Tags: arduino-uno, serial, code-optimization
---


title: Changes to array not reflected

text:
# Question
Title: Changes to array not reflected
Here's a simple sketch. I have an array `data` and a variable `idx`. I'm assigning a value to each of the array element, and then sending them to my serial monitor.

```
volatile uint16_t data[5];
volatile uint16_t idx = 5;

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

  while (!Serial) { }
  Serial.println("\nHello!");

  data[0] = 1010;
  data[1] = 1011;
  data[2] = 1012;
  data[3] = 1013;
  data[4] = 1014;

  for(int i = 0; i< idx; ++i)
  {
    Serial.print(data[idx]);
    Serial.write(",");
  }

  while(1){  }
}

void loop() {}

```

When I look into my serial monitor, I get this:

```
Hello!
0,0,0,0,0,

```

Why is this happening? Did I overlook something fundamental? I'd appreciate if you could offer your thoughts on this.

I'm testing this code on Arduino Mega2560.

# Answer
You got confused here:

```
Serial.print(data[idx]);

```

You're printing array slice 5 (the sixth entry in a 5 entry array) 5 times.

You probably meant to write:

```
Serial.print(data[i]);

```

To improve clarity you may want to `#define` it instead:

```
#define DATA_SIZE 5
uint16_t data[DATA_SIZE];

...

for (int i = 0; i < DATA_SIZE; i++) {
    ....
}

```

Or you can do it the other way round (get the size from the array):

```
uint16_t data[5];
#define DATA_SIZE (sizeof(data) / sizeof(data[0]))

```
> 1 votes

---
Tags: array
---


# Question
Title: Digispark / Digikeyboard code doesn't execute inside setup{}
Here's sample code to demonstrate my problem:

```
#include <DigiKeyboard.h>

void setup() {
  // put your setup code here, to run once:
  delay(5000);
  DigiKeyboard.print("TESTING TESTING");
  pinMode(1,OUTPUT);
  digitalWrite(1,HIGH);
}

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

```

My problem is that I can't get Digikeyboard.print() or other Digikeyboard commands (e.g. sendKeyStroke()) to do anything while they are located inside the setup function. The led command after the print command executes properly.

The print command will work if I place it inside the loop function. However, I want to only execute this code once.

Any assistance would be appreciated, and I would be happy to provide more information if necessary.

EDIT: I worked around this by using a if-expression inside the loop function to only run the code once. However, I am still interested in learning why my original code doesn't work.

# Answer
> 0 votes
The (hard to find) documentation on the DigiKeyboard example: http://digistump.com/wiki/digispark/tutorials/digikeyboard

States:

> It is essential that DigiKeyboard.update() is called regularly (the beginning of the loop is good) to maintain USB communication. Using DigiKeyboard.delay() will automatically spam DigiKeyboard.update() calls during the delay period. If your loop code is fast just using DigiKeyboard.delay() will be sufficient.

Without looking deeper into it, I suspect that your initial call to `DigiKeyboard.print()` fills a buffer and `DigiKeyboard` needs subsequent repeated calls in order to empty the buffer.

Does the problem still exist if you put `DigiKeyboard.update()` as the only statement in the `loop()` function?

---
Tags: programming, digispark
---


# Question
Title: 10k ohm Potentiometer vs 10k ohm Resistor on LCD Display
I'm trying to use a LCD Display with my Arduino, but I don't have a potentiometer and all of the guides I find always require one, usually a 10k ohm potentiometer.

The point is that I'm not very good at this stuff, but I understand that the potentiometer is actually a resistor that can vary, am I correct? In that case, if I use a simple 10k resistor I would have the same result as if I was using that potentiometer at the higher resistance (10k).

Would it be correct to use the resistor instead of the potentiometer? Then I would have to plug the positive on one side of the resistor and both the negative and output to the LCD on the other side of the resistor?

# Answer
> 3 votes
No, it would not be correct to use a single resistor to replace a potentiometer.

On an LCD the potentiometer is used to adjust the *bias level* of the LCD - that is the contrast. You need to use it to set a voltage between Vcc and Vee, which you feed into Vo. That is, a voltage somewhere between +5V and -5V.

You can't do that with one resistor.

You can, however, do it with two resistors. Some experimentation will provide the right values to use. Pick a pair of resistors which add up to around 10K (the exact value doesn't matter that much) and join them together end to end. The two ends are the equivalent to the ends of the track of the potentiometer, and the join in the middle is the wiper.

To change the "value" of the potentiometer you then need to change the value of both resistors. If you reduce one resistor you need to increase the other so that they still add up to around the same value. What you are working with here is not the actual values of the resistors, but the ratio of the values of the two resistors.

# Answer
> 0 votes
you can use the digital pin to do this instead of resistance or potentiometer. I used a delay 500 which gave me good readable display. a value of 100 was to bright

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

void loop()
{
 digitalWrite(13, HIGH);
  delayMicroseconds(500);
/* 100 gives Approximately 10% duty cycle @ 1KHz with 500 i get a good value for screen text brightness*/
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 500);

/* now you can add your LCD code to print what ever you like.*/
}

```

---
Tags: lcd, display, electronics, resistor, potentiometer
---


# Question
Title: Upload sketch via Bluetooth using HC-06 module
I'm dealing with an application in which I need to upload sketches remotely to an arduino UNO board. I successufully managed to upload sketches using an HC-06 bluetooth adapter. The only problem is that I am forced to manually press the reset button once the bluetooth link is established. Is there a way to automatically reset the arduino, in a software or hardware way, so that it will be able to accept and install the incoming and sketch? Would it be enough to activate a digital pin connected to the reset at the right timing prior the upload process starts?

# Answer
Use a BJT/FET.

For a NPN, connect RST to COLLECTOR, a digital pin in series with a 220 ohm (or whatever’s appropriate) resistor to BASE, and EMITTER to GND.

Just bring the digital pin HIGH to reset your arduino.
> 1 votes

# Answer
Here's a instructable on how to reset the arduino with software

Instructables link
> 1 votes

---
Tags: bluetooth, sketch, uploading, bootloader, hc-06
---


# Question
Title: Xbee AT Commands failing. Something wrong with Serial? Tx commands working fine
The Xbee API library is working fine for TxRequests on my Arduino, but AT commands are failing every time. I've been at this for three days.

It seems that there is some sort of conflict happening with my hardware serial port, because if I try to repeat the command a second time (after a 3sec delay), I see that the 2nd transmission (which should trigger the "D\_in" light on my Xbee shield to flash) never gets sent. Then if I try to load and execute the sketch again (this shield on the nano allows me to do so with the Xbee still plugged in), I get an avrdude error suggesting that my arduino serial is busy. My PC should be out of the picture here, since I have no Serial.print() functions and the cable is plugged into a wall adapter with power only.

Basically I get no response and the parameter I'm trying to change remains unchanged. I'm at a total loss for why this is not working. Heres my code:

```
#include <XBee.h>

XBee xbee = XBee();

uint8_t D3[] = { 'D', '3' };
uint8_t high[] = { 0x05 };/////for DI03 pin parameter
uint8_t low[] = { 0x04};////for DI03 pin parameter

AtCommandRequest AtRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();

void setup()
{
    Serial.begin(9600);
    xbee.setSerial(Serial);
    delay(10000);

    AtRequest.setCommand(D3);
    AtRequest.setCommandValue(low);
    AtRequest.setCommandValueLength(sizeof(low));
    xbee.send(AtRequest);

    delay(3000);

    AtRequest.setCommand(D3);
    AtRequest.setCommandValue(low);
    AtRequest.setCommandValueLength(sizeof(low));
    xbee.send(AtRequest);

}

void loop()
{

}

```

And in addition, here's the code for the Tx example that works just fine:

```
/**
* Copyright (c) 2009 Andrew Rapp. All rights reserved.
*
* This file is part of XBee-Arduino.
*
* XBee-Arduino is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* XBee-Arduino is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <XBee.h>

/*
This example is for Series 1 XBee
Sends a TX16 or TX64 request and checks the status response for success
Note: In my testing it took about 15 seconds for the XBee to start reporting success, so I've added a startup delay
*/

XBee xbee = XBee();

unsigned long start = millis();

// allocate two bytes for to hold a 10-bit analog reading
uint8_t payload[5] = { 0x41, 0x42, 0x43, 0x44, 0x45 };

// with Series 1 you can use either 16-bit or 64-bit addressing

// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx = Tx16Request(0x03, payload, sizeof(payload));

// 64-bit addressing: This is the SH + SL address of remote XBee
//XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x4105B41E);
// unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
//Tx64Request tx = Tx64Request(addr64, payload, sizeof(payload));

TxStatusResponse txStatus = TxStatusResponse();

int statusLed = 11;
int errorLed = 12;

void flashLed(int pin, int times, int wait) {

    for (int i = 0; i < times; i++) {
        digitalWrite(pin, HIGH);
        delay(wait);
        digitalWrite(pin, LOW);

        if (i + 1 < times) {
            delay(wait);
        }
    }
}

void setup() {
    pinMode(statusLed, OUTPUT);
    pinMode(errorLed, OUTPUT);
    Serial.begin(9600);
    xbee.setSerial(Serial);
}

void loop() {

    // start transmitting after a startup delay.  Note: this will rollover to 0 eventually so not best way to handle
    if (millis() - start > 10000) {

        xbee.send(tx);

        // flash TX indicator
        flashLed(statusLed, 1, 100);
    }

    // after sending a tx request, we expect a status response
    // wait up to 5 seconds for the status response
    if (xbee.readPacket(5000)) {
        // got a response!

        // should be a znet tx status
        if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
            xbee.getResponse().getTxStatusResponse(txStatus);

            // get the delivery status, the fifth byte
            if (txStatus.getStatus() == SUCCESS) {
                // success.  time to celebrate
                flashLed(statusLed, 5, 50);
            }
            else {
                // the remote XBee did not receive our packet. is it powered on?
                flashLed(errorLed, 3, 500);
            }
        }
    }
    else if (xbee.getResponse().isError()) {
        //nss.print("Error reading packet.  Error code: ");
        //nss.println(xbee.getResponse().getErrorCode());
        // or flash error led
    }
    else {
        // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
        flashLed(errorLed, 2, 50);
    }

    delay(1000);

}

```

# Answer
> 0 votes
So it turns out that it was working the whole time. The problem was that that the values were not being written to the xbee, only changed. Hence, hen I would check the radio in XCTU, the values would have reverted to previous. I had no idea I needed to be calling a "write" function to save the parameters to the radio.

# Answer
> 0 votes
Just a thought from a point of ignorance.. When I use serial comm, I always use an interrupt watching loop. When data hits UART, a data available pin throws an interrupt that causes the loop to read the input register.

---
Tags: arduino-nano, xbee
---


# Question
Title: Arduino connection with the server failed
I am trying to connect arduino uno and ethernet shield and try to send some data to an asp.net web api application. When i upload the sketch, i get in the serial monitor connection failed. I don't understand what's going wrong ? Below is the code i am using

```
#include "cactus_io_DHT22.h"
#include <SPI.h>
#include <Ethernet.h>
#include <Client.h>

#define DHT22_PIN 2

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };

IPAddress ip(192,168,0,177);
IPAddress server(192,168,0,11);
EthernetClient client;

DHT22 dht(DHT22_PIN);
float heatindex1 =0.00;
float heatindex2 = 0.00;

void setup() {
  Ethernet.begin(mac,ip);
    delay(1000);  Serial.begin(9600);

    Serial.println("connecting...");
    if (client.connect(server, 80)) {
      Serial.println("connected :D ");
    }
  Serial.print("Arduino server IP address: ");
  Serial.println(Ethernet.localIP());
  Serial.println("DHT22 Humidity - Temperature Sensor");
  Serial.println("RH\t\tTemp (C)\tTemp (F)\tHeat Index (C)\t Heat Index
 (F)\t Max(C)\t\t Min(C)");

  dht.begin();
  dht.readHumidity();
  dht.readTemperature();

}

float max1=dht.temperature_C;
 float min1=100;

void loop() {
  dht.readHumidity();
  dht.readTemperature();
  heatindex1=dht.computeHeatIndex_C();
  heatindex2=dht.computeHeatIndex_F();

  if(dht.temperature_C>max1)
  {max1=dht.temperature_C;}
  if(dht.temperature_C<min1)
  {min1=dht.temperature_C;}

  // Check if any reads failed and exit early (to try again).
  if (isnan(dht.humidity) || isnan(dht.temperature_C)) {
    Serial.println("DHT sensor read failure!");
    return;
  }
  if (client) {

   // When a client sends a request to a webserver, that request ends with a blank line
    boolean currentLineIsBlank = true;

    Serial.println("OK"); }

  if (client.connect(server, 80)) {
    client.print("GET /api/todo?humidity=");
    client.print(dht.humidity);
    client.print("&temperature1=");
    client.print(dht.temperature_C);
    client.print("&temperature2=");
    client.print(dht.temperature_F);
    client.print("&heatindex1=");
    client.print(heatindex1);
    client.print("&heatindex2=");
    client.print(heatindex2);
    client.print("&max1=");
    client.print(max1);
    client.print("&min1=");
    client.print(min1);// And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.11"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server

  }

  else {
    //If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

   Serial.print(dht.humidity); Serial.print(" %\t\t");
  Serial.print(dht.temperature_C); Serial.print(" *C\t");
  Serial.print(dht.temperature_F); Serial.print(" *F\t");
  Serial.print(dht.computeHeatIndex_C()); Serial.print(" *C\t ");
  Serial.print(dht.computeHeatIndex_F()); Serial.print(" *F\t ");
  Serial.print(max1); Serial.print(" *C\t ");
  Serial.print(min1); Serial.println(" *C\t");

  delay(5000);
}

```

# Answer
I don't know of this library, but you're using the connection code twice, once in the setup() and later again in the loop().

You're already checking whether the client exists:

```
if (client) {

```

Why are you asking a few lines down again to connect?

```
if (client.connect(server, 80)) {

```

My guess is, that this if()-Clause is not necessary. Or the connection in the setup() should be removed.

If this isn't the source of the error, first test whether the server on 192.168.0.11 is running and that you can connect (from a different device) to the port 80.
> 1 votes

---
Tags: ethernet
---


# Question
Title: Soft debouncing from an interrupt during stand-by
My current setup has the arduino in 'stand-by' power saving mode, therefore i am unable to use any means of a traditional soft debouncer, such as Bounce2, as far as I know.

I went ahead and attached the buttons to pin change interrupts, since I have one button on each bank, i.e. pin 7 and pin 11.

The technique I'm using doesn't seem to be behaving since the routines are being fired too regularly (inconsistently), and at the rising edge too.

I have the pins set to use their internal pull-ups.

Using the PCI library:

```
void pciSetup(byte pin)
{
  *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
  PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
  PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the

pciSetup(POWER_SWITCH);
pciSetup(SELECTOR_BTN);

// check if IR IN or Power switch
ISR (PCINT0_vect) // handle pin change interrupt for D8 to D13 here
{

  if (digitalRead(POWER_SWITCH) == LOW)
  {
    noInterrupts();
    unsigned long last_millis = millis();
    while (millis() - last_millis >= 500);
    ir_power_pressed = true;
  }
  interrupts();
}

ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7
  noInterrupts();
  unsigned long last_millis = millis();
  while (millis() - last_millis >= 500);
  ir_selector_pressed = true;
  interrupts();
}

```

Am I doing something silly?

**Update 1**

As suggested in the comments, i've adjusted the code, but it still triggers on the rising edge, and a few times rapidly at the falling edge.

```
ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7 here
{
  if (digitalRead(SELECTOR_BTN) == LOW)
  {
    noInterrupts();
    static unsigned long last_millis = millis();
    if (millis() - last_millis >= 500)
    {
      ir_selector_pressed = true;
      interrupts();
    }
  }
}

```

# Answer
You don't update last\_millis.
Also, you don't know whether SELECTOR\_BTN went from HIGH to LOW or whether another pin fired the interrupt while SELECTOR\_BTN was low. Remember the previous state to solve this.

```
const unsigned long debounceTime = 50;
volatile bool ir_selector_pressed = false;

ISR (PCINT2_vect) { // handle pin change interrupt for D0 to D7 here
  static unsigned long previousStateChangeMillis = 0;
  static bool previousPinState = HIGH;

  bool pinState = digitalRead(SELECTOR_BTN);
  if (pinState != previousPinState) { // ignore pin changes of pins other than SELECTOR_BTN
    if (pinState == LOW) { // only falling events
      if ((millis() - previousStateChangeMillis) > debounceTime) { // debounce
        ir_selector_pressed = true;
      }
    }
    previousPinState = pinState;
    previousStateChangeMillis = millis();
  }
}

```
> 0 votes

---
Tags: arduino-uno, interrupt, sleep, isr, debounce
---