title: all in one Arduino robot

text:
# Question
Title: all in one Arduino robot
Can I make all in one arduino robot? Example - line follower, bluetooth control, sonar sensor,dtmf in one arduino robot just switch to any mode without change the parts.

# Answer
> 4 votes
Yes, actually it has been done before (multiple times). I, along with some other students did such a project at my school.

https://www.youtube.com/watch?v=GTJQ2VXtmk0 https://www.youtube.com/watch?v=sXXh3Q8WoEM

**Materials needed**

* Arduino (or other programmable microcontroller board with voltage regulation)
* Battery pack (and charger)
* 2 to 5 line sensors
* ultrasonic sensor
* Bluetooth module
* Robot chassis
* Atleast two motors (with encoders is nicer, but not neccesary)
* Motor driving circuitry
* Switch and emergency stop button

It can be useful to buy a "line follower robot kit"

**Connection**

This is the connection we used. You're free to make your own adjustments.

**Programming**

We used a server that (was connected via bluetooth) and has the map and a user-interface. When you press the end-point on the server, it would generate the shortest route, calculate the directions, and send it to the robot.

The robot would then drive until it comes to a junction and then executes the direction command.

I've attached some preview code. It's better to do it yourself, but if you really don't know where to get started, you can try this. You will have to implement the low-level code yourself.

The robot will wait for Bluetooth messages. You can set it to a "direct drive" modus or "line following" modus.

```
void setup() {
  // put your setup code here, to run once:
  setupBluetooth();
  setupUltrasonicSensor();
  setupMotors();
  setupLinesensors();
  state=waiting;
}

void loop() {
  char receivedCharacter = bluetoothReceiveCharacter();

  switch (state) {
    case waiting:
      switch(receivedCharacter){
        case 'd':
          bluetooth.println("Direct Drive enabled!");
          state = directDrive;
        break;
        case 'l':
          bluetooth.println("Line following enabled!");
          state = following;
          motor1.setSpeed(50);
          motor2.setSpeed(50);
        break;
      }
      break;
    case directDrive:
        directDrive(receivedCharacter);
      break;
    case following:
        followLine(receivedCharacter);
      break;
    default:
      bluetooth.println("STATE ERROR!");
      buzzer.buzz();
      led.blink();
    break;
  }
}

void followLine(){
    long distance = ultrasonicSensor.measureDistance();
    unsigned char lineSensorsPattern = lineSensors.getPattern();

    switch(receivedCharacter){
      case 'X':
        bluetooth.println("Line following disabled! (Now waiting)");
        state = waiting;
      break;
    }

    if(distance > 100 || distance == -1){
      switch(lineSensorsPattern){
        case 0b00000000:
          motor1.setSpeed(0);
          motor2.setSpeed(0);
          bluetooth.println("Following interrupted, lost path!");
          findPath();
        break;
        case 0b00000100:
          motor1.setSpeed(100);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle sensor on.");
        break;
        case 0b00000100:
          motor1.setSpeed(100);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle sensor on.");
        break;
        case 0b00000110:
          motor1.setSpeed(70);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle & right sensor on.");
        break;
        case 0b00001100:
          motor1.setSpeed(100);
          motor2.setSpeed(70);
          bluetooth.println("Following line, middle & left sensor on.");
        break;
        case 0b00000010:
          motor1.setSpeed(0);
          motor2.setSpeed(100);
          bluetooth.println("Following line, right sensor on.");
        break;
        case 0b00001000:
          motor1.setSpeed(100);
          motor2.setSpeed(0);
          bluetooth.println("Following line, left sensor on.");
        break;
      }
    }else{
      bluetooth.println("Following interrupted, obstacle in path!");
    }
}

void directDrive(char receivedCharacter) {
  switch (receivedCharacter) {
    case 'X':
      motor1.setSpeed(0);
      motor2.setSpeed(0);
      state = waiting;
      bluetooth.println("Direct Drive disabled! (Now waiting)");
      break;
    case 'w':
      motor1.setSpeed(motor1.getSpeed()++);
      motor2.setSpeed(motor2.getSpeed()++);
      break;
    case 'a':
      motor1.setSpeed(motor1.getSpeed()++);
      motor2.setSpeed(motor2.getSpeed()--);
      break;
    case 's':
      motor1.setSpeed(motor1.getSpeed()--);
      motor2.setSpeed(motor2.getSpeed()--);
      break;
    case 'd':
      motor1.setSpeed(motor1.getSpeed()--);
      motor2.setSpeed(motor2.getSpeed()++);
      break;
  }
}

```

**My advice**

My best advice is to work in iterations. Slowly add more features until you've got the product that you desire. Or develop parts of it individually.

1. Get a bluetooth link working, send some messages back and forth.
2. Connect motors to an Arduino and chassis let it drive a pre-programmed path.
3. Get some line sensors to work (non reflecting black tape!)
4. Get a ultrasonic sensor to work.
5. Start combining these! Control the robot over bluetooth. Let the robot follow the lines. Add a breaking when it sees something within range.

---

As addition/clarification. You could make a button, that increases the state every time you press it. If you then check which state the robot is in, you can make it perform his task for that state.

```
if(buttonPressed){state++;}
if(state>3){state=0;}

if(state==0){
  //code for DTMF handling
}else if(state==1){
  //code for bluetooth
}else if(state==2){
  //code for sonar
}else if(state==3){
  //code for line sensors
}

```

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


title: How to handle an error in setup()

text:
# Question
Title: How to handle an error in setup()
What is the "proper" way to handle an error during setup on an Arduino -- for example some attached component is missing or returning an error code or invalid response? The `setup()` function returns void so that's no help. This just doesn't seem to be an issue that is addressed in the official docs -- at least not that I have found so far.

Here are some options I have considered:

* Throw an exception (but where does that go?)
* Write a message to `Serial` and then go into an infinite loop or wait for a y/n to continue.
* Set a setup\_successful flag and then do `if (!setup_successful) return;` in the main `loop()`

# Answer
> 2 votes
> The setup() function returns void so that's no help.

You wouldn't be able to get the return value anyway even if it did return something - it's not you calling the `setup()` function, but `main()`, which is not in your code or control.

> This just doesn't seem to be an issue that is addressed in the official docs

That is because it is not within the remit of the API and its associated documentation.

> Throw an exception (but where does that go?)

It goes in the bin. Exceptions are disabled. They make little sense in an embedded system. Yes, it is possible to use them, but not worth it.

> Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.

That kind of thing is what most people do - or variations on that kind of theme.

> Set a setup\_successful flag and then do if (!setup\_successful) return; in the main loop()

That will just run `loop()` again - after all, it's called `loop()` for a reason.

You seem to be in the mindset of a PC programmer. Embedded programming is a very very different beast. You don't (usually) have an operating system to handle exceptions and errors and things like that. You don't have a keyboard and mouse, and a screen with pretty pictures on it. Every single thing that the board does is what you program. If you want it to raise an error when an error occurs then it is up to you to program a suitable mechanism for that to happen. Reporting that error and asking for feedback in some way is entirely governed by your system's design. If you have a TFT screen you could put an error message on that. If you have a serial connection you can use that to show error messages. If you don't have any of those you can blink an LED or use a buzzer to beep in a specific pattern (like a PC's POST beeps).

# Answer
> 2 votes
Same way you would handle any error in an embedded system; either try to recover from it if you can, or use whatever communications mechanism you have to let the user know that something failed.

I normally use a combination of Serial.println in case I happen to have a serial connection at the time, and also a blinking pattern on an LED (which most boards I use have). As an example, look at my code here: https://github.com/jayeye/jardino/blob/master/libard/WiFiSPIFFSConfig/src/WiFiSPIFFSConfig.cpp#L11. `error()` will do a sequence of slow and then fast blinks, and either return if I think the error is recoverable and I'm merely warning the user, or just stay in an infinite loop and keep blinking in despair :)

Obviously this is not an original idea -- think beep codes!

---
Tags: arduino-setup
---


# Question
Title: Bluetooth module(HC05) works with Arduino Uno but not with breadboard (ATmega328)
I am currently working on a project that requires communication between an android phone(galaxy s4) and an ATmega328 microprocessor. To connect these devices wirelessly I'm using an HC05 bluetooth module and to understand the connection I'm using pre-built arduino codes(turn LEDs on and off) and an android app called blueterm.

This connection is established and able to transmit data when connected to the Arduino uno, but as soon as this chip is removed and connected to a standalone breadboard the connection fails. The standalone breadboard works fine and has been tested with many other projects and I have attached the breadboard connection below. The HC05 when connected to the breadboard changes the blinking pattern to notify the user it is connected but the serial connection is never made. Any help would be greatly appreciated, if any other information is needed feel free to ask.

# Answer
> 1 votes
If the LED is blinking, the device is waiting to pair with another Bluetooth transceiver (your phone). Once paired, the LED will stay lit. The factory-set pairing code is usually 1234. I can't tell from the photograph how the HC-05 Rx & Tx are wired to your ATmega328, but note that it must be cross-connected; that is Rx -\> Tx and Tx -\> Rx.

# Answer
> 0 votes
I had same issue and solved by below mentioned layout.

---
Tags: bluetooth, atmega328
---


# Question
Title: My code is stuck in a loop involving Serial.read. How can I break this?
So I'm running a program that involves both Arduino and a Raspberry PI and they are communicating between the Serial port. As you can see below when my an emergency stop door, involving a magnetic switch, is opened then the PI sends a message to the Arduino. When the door is closed the PI sends a different value telling the Arduino to continue with the program. The Arduino is receiving and reading the messages correctly as I have ran a few tests with the serial monitor.

When the door is open the PI is printing '1' which shuts down the Arduino correctly. My problem is that when I close the doors nothing happens when in theory it should break the loop and continue to run the main Arduino code. The raspberry PI is correctly printing '2' and the Arduino is correctly reading this value as it prints "Logoff" in the serial monitor.

If anyone can help or lead me to correctly breaking this loop and returning to the main code that would be great.

Thanks.

Below is the emergency part of the code that continues to run. If the full code is needed I will gladly edit it into this post. Also if the PI code is needed I will post that too, I don't believe is necessary because there are no problems on that side.

```
void Estop() {
    if (Serial.available()) {
        int d = Serial.read() - '0';

        while (d == 1) {
            digitalWrite(green, HIGH);
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(estopout, HIGH);
            digitalWrite(piston, LOW);
            digitalWrite(belt, HIGH);
            Serial.read() - '0';
            Serial.print(d);
            delay(2000);
            break;

            if (d == 0) {
                Serial.print("Logoff");
                delay(2000);
            } else {
                break;
            }
        }
    }
}

```

\`

# Answer
> 1 votes
You never reassigned the variable d anywhere within the loop. The `while` breaks after a 2 seconds delay after printing what is the value of d. That means that your `if (d == 0) [...]` never gets hit. I presume that you expect to read 'logoff' on your code?

```
void Estop() {
    if (Serial.available()) {
        int d = Serial.read() - '0';

        while (d == 1) {
            digitalWrite(green, HIGH);
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(estopout, HIGH);
            digitalWrite(piston, LOW);
            digitalWrite(belt, HIGH);
            d = Serial.read() - '0';
            Serial.print(d);
            delay(2000);
            #break;

            if (d == 0) {
                Serial.print("Logoff");
                delay(2000);
            } else {
                break;
            }
        }
    }
}

```

# Answer
> 0 votes
Inside your while loop, **you never change the condition**, running into an infinite while loop.

Further: Your program does not delay until `d` equals `0` or `1`. This can be problematic as `d` can have other values. It is an `int`.

**Plus**, you do a `while` loop while `d` equals `1` and ask, if `d` equals `0` without changing the value of `d` in between. Your `if` would never be true.

I also don't know, what this line should do:

```
int d = Serial.read() - '0';

```

did you mean:

```
int d = Serial.read();

```

I dont't see any sense, to subtract `0` from your the value you read.

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


title: What is a flag in programming Arduino?

text:
# Question
Title: What is a flag in programming Arduino?
I have seen many tutorials on programming an Arduino to control a HC-05 bluetooth module. In that I did not understand the term called 'flag'. What does that mean?

# Answer
I've always used flag to indicate a boolean logic value. I would also suggest this is an archaic term.

Was going to come up with my own explanation but found the following at In C language, what does flag mean?:

> A 'flag' is a variable that is supposed to signalize something. Think about the word itself - flags are used in sending signals. In our world of programming a basic boolean flag can either be "up" or "down", either true or false.
> 4 votes

---
Tags: arduino-uno, hc-05
---


title: Second I2C address not accepted

text:
# Question
Title: Second I2C address not accepted
I have set up 2 DHT22 sensors and 2 BMP280 sensors with an Arduino Uno SMD R3 board. The DHTs are working fine and are outputting correct temperature and humidity values to the Serial monitor. The BMPs are connected via I2C and do not. I assigned the standard address (0x77) to one of them, and set the other to 0x76 by placing a jumper between GND and SDO. However, in the Serial output, both devices are detected and connected (this is checked in the `loop()` by using the Wire library), but only one of them (0x77) shows up with the correct pressure and temperature. The other address is recognized, but it seems not to be able to transmit data. There are already pullups on the SCL and SDA lines to the +5V terminal. Both BMP280 sensors work, by reversing their position, it is still address 0x77 that works, however, once I change the jumper, neither works. Might this be simply an issue with the breadboard or is there an address conflict somehow? Also, I have tried several values for the pullup resistors (4.7 kOhm, 10kOhm and 140kOhm), they all seem to have the same effect.

The output looks like this:

```
Found address: 118 (0x76)
Found address: 119 (0x77)
Found 2 device(s).
DHT22_1: hum1 = 28.00 %, temp1 = 24.80 C
DHT22_2: hum2 = 24.80 %, temp2 = 24.70 C
BMP280_0x77: t_77 = 25.83 Cp_77 = 100039.43 Pa
BMP280_0x76: t_76 = 0.00 Cp_76 = 0.00 Pa

```

and I used the following code:

```
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

// Constants
#define DHTPIN_1 5     // pin for data
#define DHTPIN_2 4
#define DHTTYPE DHT22   // what type of sensor: DHT 22  (AM2302)

DHT dht1(DHTPIN_1, DHTTYPE); // initializes sensor
DHT dht2(DHTPIN_2, DHTTYPE); // initializes sensor

Adafruit_BMP280 bm77; // I2C
Adafruit_BMP280 bm76(0x76); // I2C

// Variables
int chk;
float hum1;  // stores humidity
float temp1; // stores temperature
float hum2;  // stores humidity
float temp2; // stores temperature

// --- Setup --- //
void setup()
{
  delay(1000);
  Serial.begin(9600);
  dht1.begin();
  dht2.begin();
  bm77.begin();
  delay(500);
  bm76.begin();
}

void loop()
{
  byte count = 0;
  Wire.begin();
  for (byte i = 1; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");

  hum1 = dht1.readHumidity(); // reads and stores hum
  temp1= dht1.readTemperature(); // reads and stores temp
  hum2 = dht2.readHumidity(); // reads and stores hum
  temp2= dht2.readTemperature(); // reads and stores temp
  // serial output commands

  delay(2000); // reading needs to be delayed by at least 2000ms
  Serial.print("DHT22_1: ");
  Serial.print("hum1 = ");
  Serial.print(hum1);
  Serial.print(" %, temp1 = ");
  Serial.print(temp1);
  Serial.println(" C");

  Serial.print("DHT22_2: ");
  Serial.print("hum2 = ");
  Serial.print(hum2);
  Serial.print(" %, temp2 = ");
  Serial.print(temp2);
  Serial.println(" C");
  delay(500);
  Serial.print("BMP280_0x77: ");
  Serial.print("t_77 = ");
  Serial.print(bm77.readTemperature());
  Serial.print(" C");
  Serial.print("p_77 = ");
  Serial.print(bm77.readPressure());
  Serial.println(" Pa");
  delay(500);
  Serial.print("BMP280_0x76: ");
  Serial.print("t_76 = ");
  Serial.print(bm76.readTemperature());
  Serial.print(" C");
  Serial.print("p_76 = ");
  Serial.print(bm76.readPressure());
  Serial.println(" Pa");

  Serial.println();

}

```

The setup I used. red = +5V, black = GND, green = SCL, blue = SDA, yellow = DHT data lines, white = jumper between GND and SDO. Pictured is a different model of the BMP series, but in my case, I used the BMP280 and did not connect the other connectors. Edit: seems to be missing in the diagram, but of course, the positive and ground terminal are connected to the breadboard.

# Answer
According to the datasheet:

> SDA and SCL are not pure open drain. Both pads contain ESD protection diodes to VDDIO and GND. As the devices does not perform clock stretching, the SCL structure is a high-Z input without drain capability.

I'm not sure if this affects the operation with two together as you have them, but I must say that your debugging seems very thorough. :)

The words "without drain capability" are a bit worrying. There is a thread on the Adafruit forum about this, where they suggest an I2C multiplexer.

On my page about I2C I have a schematic and code for a simple multiplexer using the CD4051 multiplexer chip (reply #11).

The schematic is this:
> 1 votes

---
Tags: arduino-uno, i2c, adafruit, temperature-sensor, pull-up
---


# Question
Title: Driving numerous chips from 2 separate SPI connectors w/ Arduino Micro
I want to drive numerous chips (L9823, TLC5925, ADG1414, MCP23S08) from an Arduino Micro as well as read input from analog pins connected to momentary buttons, toggles, potentiometers and such. The chips and input controls will be on various boards connected to the Arduino using ribbon cables.

The current idea is to have two sets of 8 pin FFC connectors with the following pins:

```
FFC digital "bus" conductors:
--
SCLK
VL
SDI
RST
SDO
LE3
LE2
LE1

```

The clock, VL (5V), SDI and SDO will be shared by both connectors but I still need 6 latches (which can also be commandeered for an interrupt or analog input) and 2 reset pins. This will allow me to run up to 3 types of chips per connector (minus latches used for something else).

I will also have a third 8-conductor FFC connector for 7 analog inputs (the eighth conductor is 5V analog ref).

So my question is, does anyone see any holes in this strategy? I don't think I'm going to try to even breadboard something like this. PCB fab is so easy now (and the first run is always wrong anyway) so I'm just going to make the boards and go from there.

So I just need to settle on what pins to use. Here is a diagram of the Arduino Micro:

So the connectors could use pins:

```
Connector 1 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  11
SDO  MISO
LE3  A8
LE2  A7
LE1  SS

Connector 2 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  13
SDO  MISO
LE3  A9
LE2  7 (Arduino INT)
LE1  5

Connector 3 - Analog Inputs:

5V
A0
A1
A2
A3
A4
A5
A6

```

A10 and A11 are reserved for other purposes as well.

Does this look ok?

UPDATE 1:

I have updated the text of this question to consider many of the great comments. The changes include:

1. Share MISO and MOSI between connectors. Not sure why I thought I needed to use separate ports for the different connectors. SLCK, MISO and MOSI should indeed be shared by both connectors.
2. Moved 5V to be in between SCK and MISO and moved RST to be in between MISO and MOSI. The idea is that the low impedance of these lines will shield from capacitive crosstalk described by Majenko. The connectors are 1mm pitch which isn't terribly small so hopefully this will not be an issue. It does make routing a little harder since the data pins tend to be next to each other but the same bus is going to connect to multiple boards in a daisy chain fashion so capacitive crosstalk could definitely be an issue. Fortuntely things don't have to run really fast since everything is ultimately for interfacing with humans who are relatively slow.

# Answer
> 3 votes
The micro only has one SPI bus. It is SCK/MISO/MOSI. You may *want* a second one, but you don't *have* one. You can't magic one up out of thin air.

You *could* emulate one in pure software (bit-banging) but it won't be anywhere near as efficient as using a real hardware one.

Why do you feel you need to have two independent buses anyway? What are you wanting to achieve that you can't achieve with a single shared bus? That same bus can quite happily appear on multiple connectors.

One thing to note with your strategy: Ribbon connectors and SPI don't mix well together. There is a lot of crosstalk and capacitance in a ribbon cable that high speed serial communication really doesn't like. If I had to use ribbon cable for SPI communication for anything longer than a couple of inches I would use twice as many connections and interleave ground between each signal. That is what the ribbon cables for later IDE drives in PCs used to get higher speed, more reliable, communication down ribbon cables.

# Answer
> 0 votes
The MOSI (Master Out Slave In) and MISO (Master In Slave Out) will be much better for your SPI pins. Your SDI (Slave Digital In iirc) will equate to MOSI and your SDO (Slave Digital Out iirc) will equate to MISO. Those are the hardware SPI pins and will be much better than trying to emulate SPI in software.

---
Tags: analogread, spi, arduino-micro, multiplexer
---


# Question
Title: arduino mega overheat when connected to TFT 7" and TFT shield
I have bought a 7" LCD (`TFT01-7`) and a shield to make it work with arduino mega (http://www.elecfreaks.com/store/lcd-tft01-mega-shield-v10-p-214.html), but when I upload my code to the arduino and plug my LCD to the shield the arduino get overheated and the LCD lose power and I don't know why even when I power my arduino with external 9V 2A adapter, I even tried uploading an example from the library but it does the same, I used to work with the same code and the same shield but with 5" LCD `ITDB50` and I didn't have this problem before, how can I fix this?

# Answer
7" LCDs need a lot of current. They need it for the back light.

That current comes from the 5V pin. That 5V pin is supplied by a linear regulator that has limited current capacity. As you draw more current it gets hotter and hotter and eventually shuts down.

You will need to power your LCD screen with another external 5V source. The best solution may be a powerful (2A) phone charger (USB) which you then plug direct into the USB port of the board thus bypassing the weak regulator.
> 1 votes

---
Tags: arduino-uno, arduino-mega, lcd
---


# Question
Title: Visibility of #define between sketch and library
I want to have a define from my sketch be picked up by a library. Here is a similar question for references: Using #define and multiple classes

I have a CI server that compiles my arduino sketchs on commmit. It pulls all my personal libs from an other repository and compiles the sketch using arduino-builder.

Now i want it to also make a debug build. (Some of my library's have debugstatments in them i enable using a #define debugsomething.

Is there any way i can get the compiler to pickup the #define in the sketch or am i better off making a very complex build script that modifies the headers between builds?

# Answer
> 2 votes
You need a common place that the building of all the places can get the definition from.

That isn't the sketch. The sketch is one of the things that would have to look at that common place.

That can either be a single shared header that everything else (that needs it) includes, or it can be a `-D` flag added to the compilation command.

For instance, adding:

```
-DDEBUG=1

```

to your compilation command is the same as adding

```
#define DEBUG 1

```

to every single file you compile.

---
Tags: build
---


title: NRF24L0 wireless modules

text:
# Question
Title: NRF24L0 wireless modules
I have two arduinos (one uno and another nano) with NRF24L0 modules attached to both and they are communicating between each other. All good.

However, I have a load of different ones and have switched them with the working receivers to test them but they just refuse to work despite the pinouts being correct.

Does the pinout vary between manufacturers or something else perhaps? What really perplexes me is that some of the modules I've tried are brand new (just taken out of the antistatic)

I have followed https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/

Any help would be really appriciated. Thanks

# Answer
I was having the same kind of problems (even with new modules) when supplying them by mistake with 5v instead of 3,3V. It even happened that the system was working fine for days after the communication problems due to wrong power supply started to appear.

Also many people have reported similar problems(sometimes communicating, sometimes not) with this module due to poor built-in decoupling especially when using relatively long cables between arduino and module. Just to make sure, put a decoupling capacitor near the module's power and ground pins.

(this is more of a comment but I cannot comment due to reputation.)
> 1 votes

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


# Question
Title: Max double value or NAN as a sentinel value?
I am in need of a sentinel value to use to assign to a double variable initially. 0 or -1 won't work because these values are valid values in my computation and I need a value that will stand out.

Possible choices are:

1. Maximum double value
2. Minimum double value
3. NAN (I would also need a method to check is\_nan as well)

How can I accomplish this in the Arduino language?

# Answer
> 1 votes
This is a matter of personal preference. I like NAN because it is almost always obvious it cannot be a valid value.

You can test for the value being NAN with `isnan()`.

---
Tags: c++, float
---


# Question
Title: Will I be able to control stuff from anywhere in the world if I use a wifi shield like ESP8266?
Currently, I am using a Bluetooth shield, HC-05, which is working perfectly but there are two problems:

* Only one person can connect to Bluetooth at a time.
* I have to be in a specific place to be able to control the lights.

I want to be able to control everything from anywhere in the world. I've thought about using an Ethernet Shield, but I'd prefer using a Wifi Shield if it can do the task.

# Answer
> 3 votes
answer on your comment on Majenko's answer: (cannot comment due to reputation)

* build a simple web server on your device and make sure it is accessible from a local network node (e.g. a PC).To do this open from a web browser the page `ip:port` where `ip` is the ip assigned to arduino (usually from your router's DHCP service) and `port` is the port which your web server listens to. This is configured in your arduino code. For an arduino Wifi shield you can find a tutorial for this step here
* Now you have to set up port forwarding. This means that when somebody from the internet sends a request on your router, the router will forward this request on your arduino and not on another node on your local network. The nodes on your local network are individually recognized by their IP address. Port forwarding is configured per port, so you must set up port forwarding from a specific in-port to a specific ip,local-port combination. For example if your arduino has been assigned ip 192.168.2.10 and your web server listens on port 80, you can forward all requests from port 8080 to 192.168.2.10:80. This means that every request comes from the internet on port 8080 on your router (internet side) will be forwarded on your local node on ip 192.168.2.10 and port 80. Note that for simplicity in-port and out-port can be the same and they usually are. Port forwarding is configured in your router's menu and the exact procedure is different for every modem. Your best bet is to search google for your modem's model + `port forwarding`. If you succesfully configure this, then you will be able to load web server's page from a node outside your local network by visiting ip:port where `ip` is your router's internet ip and port is the aforementioned in-port. A simple page to see your internet ip is this.

These are basically the main steps to have access from internet. Further improvements could be:

* solving dynamic IP issue (in order to access your arduino, you have to know your router's internet ip which can change by your ISP anytime. Buying a static IP or setting up a dynamic DNS solves this issue)
* turning your web server to *non web* server (more advanced topic).

# Answer
> 1 votes
The WiFi shield connects your Arduino to your local network. What you then do with that network is entirely up to you.

Yes, it is possible.

Is it easy, though? Well, if you have to ask the question then for you it won't be easy. You have to know how networks work for a start. Routing, port forwarding, client-server models, etc.

# Answer
> 1 votes
If you haven't already, take a look at Blynk.cc's website. Blynk provides a (drag-and-drop configurable!) smartphone/tablet app and a number of skeleton programs for many platforms and interfaces including, of course, the Arduinos.

In brief, your Arduino program can report data to their server, and the smartphone app can read and display that, as well as send control signals back to your board. They make it simple to accomplish basic things and quite easy to expand it to do more. The ESP8266 is a good choice for a web interface, especially if you're using an Arduino Uno or other Atmega328p-based platform, because it takes about the least amount of the MCU's limited resources of any of the compatible network interfaces.

Because your Arduino program will be configured as a network client you will avoid the hassles and potential security issues of configuring your local network to allow access to internal server from outside. The Arduino sketch opens an outboud connection to their server, just as a web-browser would, so you won't need to "poke holes" in your router's firewall to let in your client and anyone else that wants to mess with your stuff.

(Note: I have no connection with them, but I think they have a strong platform for Internet of Things hobbyists and I use their stuff.)

Update: Blynk supports Arduino WiFi, WiFi 101, CC3000, and ESP8266 w/original (AT) firmware. This device (Atmega328p with ESP8266) is logging temperatures from 3 DS18b20 thermo sensors to Blynk as I type this:

# Answer
> 1 votes
It is definitely possible to control anywhere from the World where internet is available.

As @forivaras noted, there are a few accidental complexities involved in the network setup. It is nothing specific to Arduino, these come from the fact how Internet works nowadays.

For start, I suggest using an ESP8266 module (instead of any other solution), which is connecting to a readily available 3rd party server (such as dweet.io and visualize with freeboard.io, or Adafruit IO, or IFTTT).

In fact, you don't need the Arduino at all. The ESP8266 is a way more powerful than an Arduino, and yuu can program it as if it would be an Arduino plus Wifi.

So the hardware comes for less than $10, and you can find ready made howtos on the web such as: https://learn.adafruit.com/home-automation-in-the-cloud-with-the-esp8266-and-adafruit-io/introduction

This ensures a smooth start! Have fun :)

---
Tags: wifi, esp8266, hc-05
---


# Question
Title: DS1307 RTC not working with CC3000 WiFi shield (I2C bus hangs)
I am trying to use a DS1307 (from Sparkfun, BOB-12708) with an Arduino Leonardo. I have connected the SDA, SCL, GND, and 5V pins from the RTC to the Arduino. However, with a CC3000 WiFi shield on the Arduino, the I2C bus hangs. Specifically, `Wire.endtransmission()` hangs, called by `rtc.isrunning()`. I have confirmed that it works properly on the same Arduino without the WiFi shield. I am using the ds1307 RTClib example for testing it.

# Answer
It could be that the CC3000 interrupts are affecting the Wire library's behaviour since the latter is interrupt-driven itself. Try disabling the CC3000 IRQ before calling `rtc.isrunning()` or any other RTC functions. First `#include "ccspi.h"` in your sketch. Then place `WlanInterruptDisable()` before any `RTClib` function call, and then `WlanInterruptEnable()` after the RTC function returns.

Even if this works, it may affect the functionality of the CC3000, since it increases the chances of missed interrupts. You can search for DS1307 libraries that employ SoftwareI2C instead such as this one. They should be better able to recover from the CC3000 interrupts.
> 1 votes

---
Tags: i2c, wifi, rtc
---


title: Simple Calculator

text:
# Question
Title: Simple Calculator
I'm trying to make a basic calculator with the Serial monitor but it doesn't seem to work.

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

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()) {
    Serial.println("First Number: ");
    a = Serial.read();
    Serial.println("Second Number: ");
    b = Serial.read();
    Serial.println(a + b);
  }
}

```

# Answer
Serial.read() reads in only the first byte of the data from the serial.This is not what we want, We everything that the user has entered to be treated as an Integer and then read it into the variables. You should use Serial.parseInt() for the job.

See the modified program below:

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

void loop() {
  Serial.println("Enter the First number");
  while(!Serial.available()); // wait till the user has entered something
  a = Serial.parseInt(); // treat what the user has entered as an Integer and read the whole number
  Serial.println("Enter the second number");
  while(!Serial.available());
  b = Serial.parseInt();
  Serial.println(a+b); // Print the sum
}

```
> 5 votes

---
Tags: arduino-uno
---


# Question
Title: How to write a sketch when adding more devices to an I2C data line?
I am building a weather station, using a battery-operated outside unit, that transmits data from a DHT22 sensor to a unit inside my house.

The inside unit is using I2C communications from my Arduino Uno to my LCD display.

I would like to add a BMP180 sensor which also uses I2C communications.

My question is, how would you write a sketch to incorporate both the BMP180 sensor and the LCD display on to one I2C line?

# Answer
> 1 votes
Yes you can connect multiple devices on one I2C bus. Every device on the bus needs to have its own address. Some libraries have the default address included. Some do allow to change it. Others don't. For example the SE95 temperature sensor (page 10) does allow for setting a few bits of the address allowing more than one sensor on a bus.

You can use the Wire library from Arduino to request data from I2C. When you want to pull data from a sensor, you have to send a command depending on the specs than request data from the address.

Example: for the SE95 address 0x4F (you can repeat this for any address you have a sensor on your bus) the SE95 ranges from 0x49 to 0x4F depending on the pin settings:

```
//Please note that the example is not complete because Wire has to be loaded and initialized
byte address = 0x4F;
byte read1;
byte read2;
Wire.beginTransmission(address);
Wire.write(0x00);
Wire.requestFrom(int(address), 2);
if(Wire.available()) {
  read1 = Wire.read();
  read2 = Wire.read();
}

```

So depending on the libraries, this would be quite easy.

# Answer
> 0 votes
Like Nick Gammon said, they have different addresses, so there shouldn't be a problem. Connect their SDAs and SCLs together, with the necessary pull-ups.

The libraries you are using should handle the low-level reading and writing. Proceed as though they are any 2 devices connected to your Uno. Print to the LCD as usual, and poll the sensor with library functions.

---
Tags: i2c
---


# Question
Title: Is a 9v battery appropriate for a piezo and 1 LED?
I'm making a basic "door open" detector that, when a door is opened, it turns on an LED and then sounds an alarm via a piezo.

This is controlled via a 5v Adafruit Trinket.

Is a 9v battery the correct thing to power this with, if the goal is to change batteries as infrequently as possible?

Here's the code, incase that's relevant.

```
#include <elapsedMillis.h>
elapsedMillis timeElapsed;

const int switchPin = 2;
const int ledPin = 1;
const int piezoPin = 0;
const uint32_t openLength = 5 * 1000L; // X seconds
int notes[] = {862,294,730};

void setup() {
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  digitalWrite(switchPin, HIGH);
}

void loop() {
  if(digitalRead(switchPin) == LOW){
    digitalWrite(ledPin, LOW);
    timeElapsed = 0;
  } else {
    digitalWrite(ledPin, HIGH);

    if (timeElapsed > openLength){
      for (int n = 0; n < 200 ; n++){
        beep(notes[random(0,2)]);

        if(digitalRead(switchPin) == LOW){ break; }
      }
    }
  }
}

void beep(int delayAmount)
{
  for (uint16_t t = 0; t < 30*1000/2; t += delayAmount)
  {
    digitalWrite(piezoPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(piezoPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

```

**UPDATE:** I had a 9V plugged in to this for about 3 days before it used all the power in 9V. Is that an issue w/ voltage on the battery (i.e. I should be using AA's instead of a 9V)? Or does that point largely to some other inefficiency w/ the code or hardware?

# Answer
> 1 votes
A couple things to note:

* Get rid of the PWR LED on the Trinket so it's not always drawing current.
* Sleep the MCU whenever possible, only waking on interrupts.
* Converting 9V to 5V with an LDO (in this case, the MIC5225) implies a 55% efficiency, *max*, which isn't great. But at least the LDO has a low ground current.

Also, ask yourself if you really need a micro for this task.

If you want a ballpark for runtime, find the capacity of your battery, estimate your current draw, and see what your upper bound on runtime is.

# Answer
> 0 votes
You can power the Trinket (ATTiny85) from as little as 2.7 volt. So you could power it by connecting 2 (or 3) AA-batteries directly to the 5V pin.

Using a 9V battery means you would "throw away" 4 of the 9 Volts to get 5Volt. So you'd waste almost half of the capacity of the battery.

Also a 9V battery only has around 500mAh, where as an AA battery has 2500mAh.

---
Tags: power, led, adafruit, piezo
---


# Question
Title: Error in using buttons to input numbers!
This is a mini project of mine, which is to be implemented in another. Here, I'm trying to make arduino output numbers in the serial window based on the diff. buttons pressed(there are four of them in my case).
What I want:

* the initial array is 0000.
* if I press button one, then button three, the array should be 1010
* if I press button one two times, and button 4 three times, the resultant array should be 2003......and so on.you might have got what I'm trying to do here. the problem is , all I'm getting is 0000, ALL THE TIME.

My code is below, and I'm a newbie, so any corrections(+advice?) given would be greatly appreciated.
(Also I don't know where to print the output :P I did it in `loop()` so it keeps on printing it :P)

```
CODE:

//the buttons:

const int b1=8;
const int b2=9;
const int b3=10;
const int b4=11;
//variables to store previous button press and currend button press , used to eliminate switch bouncing
boolean pb1=LOW;
boolean cb1=LOW;

boolean pb2=LOW;
boolean cb2=LOW;

boolean pb3=LOW;
boolean cb3=LOW;

boolean pb4=LOW;
boolean cb4=LOW;

//variables to store numbers:

int w=0;
int x=0;
int y=0;
int z=0;

int var_array [4]={w,x,y,z};

void setup() {
  // put your setup code here, to run once:
  pinMode(b1,INPUT);
  pinMode(b2,INPUT);
  pinMode(b3,INPUT);
  pinMode(b4,INPUT);

 Serial.begin(9600);

}

boolean debounce1(boolean last)
{
   boolean current=digitalRead(b1);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b1);
      return current;
  }

boolean debounce2(boolean last)
{
   boolean current=digitalRead(b2);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b2);
      return current;
  }

  boolean debounce3(boolean last)
{
   boolean current=digitalRead(b3);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b3);
      return current;
  }

  boolean debounce4(boolean last)
{
   boolean current=digitalRead(b4);
  if(last != current)
  {
      delay(5);
    }
      current=digitalRead(b4);
      return current;
  }

void loop() {
  // put your main code here, to run repeatedly:
  cb1=debounce1(pb1);
  cb2=debounce2(pb2);
  cb3=debounce3(pb3);
  cb4=debounce4(pb4);

     if (pb1==LOW&&cb1==HIGH)
   {
      w++;
    }
    pb1=cb1;

    if (pb2==LOW&&cb2==HIGH)
   {
      x++;
    }
    pb2=cb2;

    if (pb3==LOW&&cb3==HIGH)
   {
      y++;
    }
    pb3=cb3;

    if (pb4==LOW&&cb4==HIGH)
   {
      z++;
    }
    pb4=cb4;

for(int i=0;i<4;i++)
Serial.print(var_array[i]);

Serial.println();

delay(500);

}

```

# Answer
In your C program all the variables including the array occupy their own space in memory. In the line "int var\_array \[4\]={w,x,y,z};" all you did was create 4 more variables (elements of the array var\_array) in memory and initialized them to the values found in variables (w, x, y & z) in a different part of memory. So when you incremented the variables in memory pointed to by the names w, x, y and z... you did nothing to the variables in memory pointed to by the elements of the var\_array.

For example, in this program:

```
main()
{
 int w=0;
 int x=1;
 int y=2;
 int z=3;

 int var_array [4]={w,x,y,z};

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", var_array[0],var_array[1],var_array[2],var_array[3]);

 w += 1;
 x += 2;
 y += 4;
 z += 5;

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", var_array[0],var_array[1],var_array[2],var_array[3]);
}

```

The output is this:

```
w 0 x 1 y 2 z 3
var_array 0 1 2 3
w 1 x 3 y 6 z 8
var_array 0 1 2 3

```

Notice how the array values do not change.

If you really want to do this, you need to make the array var\_array an array of pointers and point each element to each variable (w, x, y & z).

For example:

```
main()
{
 int w=0;
 int x=1;
 int y=2;
 int z=3;

 int * var_array [4]={&w,&x,&y,&z};

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", *var_array[0],*var_array[1],*var_array[2],*var_array[3]);

 w += 1;
 x += 2;
 y += 4;
 z += 5;

 printf("w %d x %d y %d z %d\n",w,x,y,z);
 printf("var_array %d %d %d %d\n", *var_array[0],*var_array[1],*var_array[2],*var_array[3]);
}

```

Now produces this output:

```
w 0 x 1 y 2 z 3
var_array 0 1 2 3
w 1 x 3 y 6 z 8
var_array 1 3 6 8

```
> 1 votes

---
Tags: serial
---


# Question
Title: Compilation fails with non-explicit error message
I have written the following code for a project comprising an ultrasonic distance sensor, a buzzer and a few buttons. When the distance is less than 60 cm, the buzzer rings and stops only when the appropriate passcode is pressed.

When I try to compile it, I get:

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

This does not give the **reason** for the compilation failure.

My code is below, any help would be appreciated.

```
#include<NewPing.h>

int r;
boolean ctr;

#define TRIGGER_PIN  10  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     9  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

//the buttons:

const int SPEAKER=8;

const int b1=4;
const int b2=5;
const int b3=6;
const int b4=7;
//variables to store previous button press and currend button press , used to eliminate switch bouncing
boolean pb1=LOW;
boolean cb1=LOW;

boolean pb2=LOW;
boolean cb2=LOW;

boolean pb3=LOW;
boolean cb3=LOW;

boolean pb4=LOW;
boolean cb4=LOW;

//variables to store numbers:

int w=0;
int x=0;
int y=0;
int z=0;

void setup() {
  // put your setup code here, to run once:
  pinMode(b1,INPUT);
  pinMode(b2,INPUT);
  pinMode(b3,INPUT);
  pinMode(b4,INPUT);

 Serial.begin(9600);

}

boolean debounce1(boolean last1)
{
   boolean current1=digitalRead(b1);
  if(last1 != current1)
  {
       delay(5);
    }
      current1=digitalRead(b1);
      return current1;
  }

boolean debounce2(boolean last2)
{
   boolean current2=digitalRead(b2);
  if(last2 != current2)
  {
      delay(5);
    }
      current2=digitalRead(b2);
      return current2;
  }

  boolean debounce3(boolean last3)
{
    boolean current3=digitalRead(b3);
  if(last3 != current3)
  {
      delay(5);
    }
      current3=digitalRead(b3);
      return current3;
  }

  boolean debounce4(boolean last4)
{
   boolean current4=digitalRead(b4);
  if(last4 != current4)
  {
      delay(5);
    }
      current4=digitalRead(b4);
      return current4;
  }

boolean distance(int o)
{
  boolean control;
  if (o<60)
    control=true;
    return control;
  }

void loop() {
  // put your main code here, to run repeatedly:
  cb1=debounce1(pb1);
  cb2=debounce2(pb2);
  cb3=debounce3(pb3);
  cb4=debounce4(pb4);

     if (pb1==LOW&&cb1==HIGH)
   {
      w++;
    }
    pb1=cb1;

    if (pb2==LOW&&cb2==HIGH)
   {
      x++;
    }
    pb2=cb2;

    if (pb3==LOW&&cb3==HIGH)
   {
      y++;
    }
    pb3=cb3;

    if (pb4==LOW&&cb4==HIGH)
   {
      z++;
    }
    pb4=cb4;

    delay(50);
    unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds   (uS).

    Serial.print(uS / US_ROUNDTRIP_CM);
    Serial.print(" ");
     int r=uS / US_ROUNDTRIP_CM;

     ctr=distance(r);

  if(ctr==true)
    tone(SPEAKER,1000);

Serial.print(w);
Serial.print(x);
Serial.print(y);
Serial.print(z);

Serial.println();

delay(100);
if(w==1&&x==3&&y==3&&z==1)
  noTone(SPEAKER);

}

```

# Answer
There is a reason. There is always a reason. You may just have to scroll back in the output panel to see it.

```
Tone.cpp:536: multiple definition of `__vector_7'
NewPing/NewPing.cpp:284: first defined here
collect2: error: ld returned 1 exit status

```

In this case it is that you are using `NewPing.h` and `tone()`. Both of them use the same timer.

You can't use both `tone()` and the `NewPing.h` library together without first making one of them use a different timer or no timer at all. The easiest is the `NewPing.h` library. As it says in the header file:

```
#define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true

```

So edit that header file and set `true` to `false` for that line and it should start working.
> 0 votes

---
Tags: sensors, compile
---


# Question
Title: Low current in a motor used in a line following robot
I'm trying to make a line following robot for my students, the problem is that I have not done any calculations (I don't know how).

The motor can't move the robot unless I connect it directly to the 9 V power supply, but when i connect the other compenents(arduino) in parralel to the same 9v powersuply the motor doesn't get enough current when put on the floor so it just freeze's.

Where do you think should i start ?

The transistor I used is: NPN C1815 the motor is a brushed dc motor

# Answer
Due to only a tiny amount of gearing (what is it - 2:1? 3:1? something like that) your motor is operating near the stall point unless it is able to pick up enough speed (at which point it would smash into the nearest wall and pulverise itself).

Consequently it is drawing far more current from the battery than you'd like. And that is, without the Arduino connected, about all the puny little PP3 battery can provide. Add the Arduino etc into the mix and you are over-stepping your current budget by enough to mean the motor cannot start turning (the 1A stall current).

So what to do? Well, two options:

* Use a bigger battery.
* Increase the gearing of the motor.
* (my personal recommendation) Do both.

Increasing the gearing of the motor will decrease maximum output speed, increase the torque, and most importantly, decrease the start-up current. The whole load on the motor will be reduced making it much easier to start.

By increasing the power of the battery (use a 2S or 3S Li-Ion depending on what your motor's voltage limits are) you have a much bigger current budget to play with.
> 0 votes

---
Tags: motor, current, robotics
---


title: STPM10 using Arduino SPI communication

text:
# Question
Title: STPM10 using Arduino SPI communication
I am working with STPM10 energy metering chip (evaluation board) and I want to read the data from 8 internal registers of the chip each containing 32 bits.

The datasheet of the STPM10 chip suggested to have a simplex synchronous SPI where the MOSI of the Arduino is not connected to any pin on the energy chip. Instead they provided a timing diagram to switch from reading and writing on the energy chip.

After the t5, datasheet stated that we should apply 32 serial clocks per data record and up to 8 data records can be read this way. My problem is how to apply 32 serial clocks to the chip. Is the Serial clock on the Arduino SPI automatically activated after `SPI.begin()` ? If not, how can I start the serial clock? By the way, this is the code I've written:

```
#include <SPI.h>

SPISettings settingA(32000000, LSBFIRST, SPI_MODE0);
const byte SYN = 8;
void setup() {
  Serial.begin(9600);
  pinMode(SYN,OUTPUT);
 /*Initializes the SPI bus by setting SCK, MOSI and SS to outputs
  Pulling SCK, and MOSI low, and SS high */
  SPI.begin();
  SPI.beginTransaction(settingA);

  }

void loop() {
  //0----->t1
  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(500);
  //t1----->t2
  digitalWrite(SYN,LOW);
  delayMicroseconds(1000);
  //t2----->t3
  digitalWrite(SYN,HIGH);
   delayMicroseconds(0.035);
  //t3----->t4
  digitalWrite(SS, LOW);
  delayMicroseconds(0.035);
  //t4----->t5
  digitalWrite(SYN, LOW);
  delayMicroseconds(0.035);
  //t5---->t6
  digitalWrite(SYN, HIGH);
  delayMicroseconds(0.035);

  byte d1 = SPI.transfer(0x00);
  byte d2 = SPI.transfer(0x00);
  byte d3 = SPI.transfer(0x00);
  byte d4 = SPI.transfer(0x00);
  byte d5 = SPI.transfer(0x00);
  byte d6 = SPI.transfer(0x00);
  byte d7 = SPI.transfer(0x00);
  byte d8 = SPI.transfer(0x00);
  byte d9 = SPI.transfer(0x00);
  byte d10 = SPI.transfer(0x00);
  byte d11 = SPI.transfer(0x00);
  byte d12 = SPI.transfer(0x00);
  byte d13 = SPI.transfer(0x00);
  byte d14 = SPI.transfer(0x00);
  byte d15 = SPI.transfer(0x00);
  byte d16 = SPI.transfer(0x00);
  byte d17 = SPI.transfer(0x00);
  byte d18 = SPI.transfer(0x00);
  byte d19 = SPI.transfer(0x00);
  byte d20 = SPI.transfer(0x00);
  byte d21 = SPI.transfer(0x00);
  byte d22 = SPI.transfer(0x00);
  byte d23 = SPI.transfer(0x00);
  byte d24 = SPI.transfer(0x00);
  byte d25 = SPI.transfer(0x00);
  byte d26 = SPI.transfer(0x00);
  byte d27 = SPI.transfer(0x00);
  byte d28 = SPI.transfer(0x00);
  byte d29 = SPI.transfer(0x00);
  byte d30 = SPI.transfer(0x00);
  byte d31 = SPI.transfer(0x00);
  byte d32 = SPI.transfer(0x00);

  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(499);

  Serial.println(String(d4,BIN) + " " + String(d3,BIN) + " " +  String(d2,BIN) + " " +  String(d1,DEC));
  Serial.println(String(d8,BIN) + " " + String(d7,BIN) + " " +  String(d6,BIN) + " " +  String(d5,BIN));
  Serial.println(String(d12,BIN) + " " + String(d11,BIN) + " " +  String(d10,BIN) + " " +  String(d9,BIN));
  Serial.println(String(d16,BIN) + " " + String(d15,BIN) + " " +  String(d14,BIN) + " " +  String(d13,BIN));
  Serial.println(String(d20,BIN) + " " + String(d19,BIN) + " " +  String(d18,BIN) + " " +  String(d17,BIN));
  Serial.println(String(d24,BIN) + " " + String(d23,BIN) + " " +  String(d22,BIN) + " " +  String(d21,BIN));
  Serial.println(String(d28,BIN) + " " + String(d27,BIN) + " " +  String(d26,BIN) + " " +  String(d25,BIN));
  Serial.println(String(d32,BIN) + " " + String(d31,BIN) + " " +  String(d30,BIN) + " " +  String(d29,BIN));
  Serial.println(" ");

```

# Answer
> 1 votes
The STPM10 specification describes a SPI bus unlike any I have seen. Apparently the STPM10 "SYN" line controls the direction of the "SDA" line. As far as I know, there is no "SYN" line in a SPI bus. As such I do not think a normal Arduino SPI library will talk to an STPM10.

A normal single port (MOSI and MISO combined) SPI slave would automatically switch between reading and writing bits. When interfacing with a two port master (such as an Arduino) a resistor is used between the MISO and MOSI nets.

This is the best image I could find. Ignore the chip names. And substitute MOSI for SDO and MISO for SDI. Note there is no "SYN" line in this SPI bus.

I'm showing this diagram as it appears the STPM10 is using a single line for both input and output data.

Because of the missing "SYN" line I do not think you can even use the SPI hardware in the Arduino's Atmel processor. I think your only option is to create a SPI driver from scratch only using software.

I see where STMicroelectronics offers an evaluation software package that talks to the STPM10. Guessing, it looks like they wrote it in National Instruments Lab View. If you could get the source code for that it may provide hints on writing your own STPM10 driver.

# Answer
> 1 votes
Like the datasheet says, its best if you implement writing in software and use the hardware SPI for reading. The steps for writing to the registers are as follows:

> 1. disable the SPI peripheral;
> 2. set MISO, SCLK and SS to be output;
> 3. set the pin which is connected to SYN to be output high;
> 4. activate SCS first and then SYN;
> 5. activate SCL;
> 6. apply a bit value to SDA and deactivate SCL;
> 7. repeat the last two steps seven times to complete one byte transfer;
> 8. repeat the last three steps for any remaining byte transfer;
> 9. deactivate SYN and the SCS;
> 10. enable again the SPI module;

In Arduino-speak:

```
#define SCS 4  // define your own CS to have better control

void setup(){
  pinMode(SS, OUTPUT);  //needed to use the SPI

  pinMode(SCS, OUTPUT);  // set SCS and SYN as output
  pinMode(SYN, OUTPUT);
  digitalWrite(SCS, HIGH);  // idle state
  digitalWrite(SYN, HIGH);
  SPI.beginTransaction(SPISettings(32000000, MSBFIRST, SPI_MODE3)) // mode 3, max read clock is 32mhz
}

void write_reg(byte addr, byte val){
  val = (val << 7) | (addr << 1);  // 6-bit addresses!
  SPI.end();  // disable SPI
  pinMode(MISO, OUTPUT);
  digitalWrite(SYN, HIGH);
  delayMicroseconds(10);

  digitalWrite(SCS, LOW);  // assert SCS and SYN
  digitalWrite(SYN, LOW);
  for (int i = 0; i < 8; i++){  // shift out a byte
    delayMicroseconds(10);
    digitalWrite(SCK, LOW);  // max clock is 100kHz
    digitalWrite(MISO, (val & 0x80) ? HIGH : LOW);
    delayMicroseconds(10);
    digitalWrite(SCK, HIGH);
    val <<= 1;
  }

  digitalWrite(SYN, HIGH); // deassert SCS and SYN
  digitalWrite(SCS, HIGH);

  SPI.beginTransaction(SPISettings(32000000, MSBFIRST, SPI_MODE3)); //restart SPI
}

```

For reading, you use the hardware SPI like this:

```
void read_regs(uint32_t data[], uint8_t len){  // an array to hold register data is passed
  digitalWrite(SYN, LOW);  // latching operation
  digitalWrite(SCS, LOW);
  digitalWrite(SYN, HIGH);

  uint32_t val = 0;
  for (int i = 0; i < len; i++){  // read the 8 32-bit registers into the array
    val = SPI.transfer(0);  // your 32 serial clocks
    val |= (uint32_t)SPI.transfer(0) << 8;
    val |= (uint32_t)SPI.transfer(0) << 16;
    val |= (uint32_t)SPI.transfer(0) << 24;
    data[i] = val;
  }

  digitalWrite(SCS, HIGH);  // deassert SCS
}

// Use the functions this way:

uint32_t reg_data[8];  // array to hold read data, max is 8

void loop(){
  write_reg(47, 1);  // set config bit 47
  read_regs(reg_data, 8);  // read all reg data into array

  for (int i = 0; i < 8; i++)
    Serial.println(reg_data[i], HEX);
}

```

The connections are:

```
Arduino MISO = SDA
Arduino SCK = SCL
Arduino D4 = SCS
Arduino D5 = SYN

```

Each call of `SPI.transfer()` yields 8 serial clocks i.e. a clock for each bit, so 32 serial clocks is merely 4 `SPI.transfer()` calls. Your code is actually producing 32 x 8 = 256 serial clocks. I suggest you read up on SPI.

I didn't include some of the delays in the datasheet because `digitalWrite()` on an Uno takes about 5us which is more than enough for this case. Of course, the code is untested so...I've done most of your work already, almost feels like I should be getting paid or something...

---
Tags: spi
---


title: Esp 8266 doesn't reply to AT commands

text:
# Question
Title: Esp 8266 doesn't reply to AT commands
I am working on esp8266 module with arduino uno board. This is my program.

```
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
   Serial.print("START");
  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
     pinNumber += (esp8266.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    Serial.println(esp8266.print(command)); // send the read character to the esp8266

    long int time = millis();
    while( (time+timeout) > millis())
    {

      while(esp8266.available())
      {
        Serial.print("Coming");

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

```

the problem is i am not getting any output from esp module but arduino is transmitting the data. power supply for esp is given by 3.3v regulator (LD3.3)feeding 12v from arduino power supply adapter to regulator input . TX esp to rx arduino arduino tx to esp rx by voltage divider (R1=1k and R2=1.8k) esp gnd to arduino gnd chpd and esp vin are 3.3v from regulator Can anyone tell me where the problem is ?

# Answer
> 1 votes
Try powering the ESP from an external 3.3V power supply if possible - some people say the Arduino 3.3V regulator may not provide enough power for it (it is quite power hungry at startup).
Another option worth trying is to put a 100uF capacitor between ESP VCC and GND. Put some small delay at the beginning of your `setup()` function if you do that just in case.
Also, there are several pins you need to pull UP: CH\_PD, RESET, GPIO0. If you have GPIO15 broken out (depends on the board), pull it to ground. I have also noticed the ESP won't boot properly if GPIO2 is LOW - either leave it floating or pull it up.
Here is a picture you can use as a guide
Of course, you should make sure the ESP is flashed with the AT commands firmware (they usually are) and your baud rate is correct. If you don't know - try 9600, 57600, 115200.
If you have a USB to TTL converter, it might be better (easier) to test your setup using it, without Arduino. Any serial terminal program (including Arduino IDE Serial Monitor) will be fine. Just make sure you send both CR and LF for new lines. If you send "AT" and receive "OK" your wiring is correct, if you don't - it is not.

---
Tags: esp8266
---


# Question
Title: How to not wait for USB to become active?
*EDIT: My original question was a bit "off" since the Arduino Nano I was using appeared to be faulty. This edited question is based on my other Arduino Nano which is working.*

When I plug my Arduino into the PC, it keeps blinking it's LED until I open the Serial Monitor.

After opening the serial monitor the Arduino will start to execute my code.

How can I get my Arduino to "not wait on a connection", or simply put, start whenever it receives power.

I believe it's the bootloader which somehow doesn't time-out (I'm not sure if that's how the bootloader works).

The code below (though I don't see why this would make it hang until a connection):

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(256000);
  Serial.write("Restart");
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) {
    incomingByte = Serial.read();

    // say what you got:
    startSend();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
    stopSend();
  }else{
    startSend();
    Serial.println("I'm still standing");
    stopSend();
    delay(400);
  }
}

```

(Code is only for testing purposes)

# Answer
After you post your code this answer may not apply. But, guessing, you may benefit from changing your code from:

```
loop()
{
 data = Serial.read();
 // Do other sutff
}

```

To something like this:

```
loop()
{
 if(Serial.available() > 1)
 {
  data = Serial.read();
 }
 // Do other stuff
}

```
> 0 votes

---
Tags: arduino-nano, bootloader
---


# Question
Title: Possible to "inline" PROGMEM strings into a structure array initialization?
I have the following structure:

```
struct inst_t {
    const char *s1;
    const char *s2;
};

```

I'd like to initialize a constant array of this structure like this where all the strings are `PROGMEM`'ed:

```
const char START[] PROGMEM = "START";
const char ATZ[] PROGMEM = "ATZ";
const char ATE0[] PROGMEM = "ATE0";
const char OK[] PROGMEM = "OK";

static inst_t insts[] = {
    { START,      NULL },
    { ATZ,        OK },
    { ATE0,       OK }
};

```

You can see there is a lot of duplication here though. Is there anyway way I can inline the `PROGMEM` strings directly into this array initialization without separately declaring each string as being in `PROGMEM`?

# Answer
> 2 votes
If the strings are similar size you can, like this:

```
const int NUMBER_OF_ELEMENTS = 10;

typedef struct {
   char description [12];
} descriptionType;

const descriptionType descriptions [NUMBER_OF_ELEMENTS] PROGMEM = {
 { "Furnace on" },
 { "Furnace off" },
 { "Set clock" },
 { "Pump on" },
 { "Pump off" },
 { "Password:" },
 { "Accepted" },
 { "Rejected" },
 { "Fault" },
 { "Service rqd" },
 };

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
    // make a copy of the current one
    descriptionType oneItem;
    memcpy_P (&oneItem, &descriptions [i], sizeof oneItem);

    Serial.println (oneItem.description);
    }   // end of for loop

  }  // end of setup

void loop () { }

```

---

This is a bit wasteful of program memory, because you need to allow for the largest string (your example had them all similar sizes) but what you *save* is not needing a two-byte pointer for each string, so if they are all similar lengths, it will take about the same memory.

See my page about PROGMEM.

---
Tags: progmem
---


# Question
Title: Ways to implement touch sensitive surface?
I'm building a tic tac toe board for my kids where tapping on a plexiglass surface in any one of the 9 squares would light it up.

What are some ways I can pull off making each of those 9 squares touch sensitive?

Doesn't need to be anything fancy, but the kicker is that it can't be something attached directly to the plexiglass surface (as that'd obscure the LED light underneath).

Current thinking is buy a sheet of this pressure-sensitive conductive material and cut it in to squares, then somehow transfer pressure form the plexiglass down to the square on the bottom of the box, but I may be overcomplicating it.

# Answer
> 1 votes
Transparent touch sensitive surfaces are usually based on parasitic capacitance like on an iPhone. While you can buy loose glass touch surfaces, it is difficult to use such devices if not already attached to an LCD. The same is true for the much cheaper resistive touch surfaces like on a Newton.

If you are already using LEDs, I would suggest investigating using the LED to detect the light from the reflection of a finger. I found people talking about this here, here and here.

I believe this is a still from a video that someone else made using this technique:

For your tic tac toe box I could see touching a location for X's or for O's. Then touching 1 of 9 boxes you would want to place the symbol in.

Added later...

As @Gerben pointed out there are other options. I like solving hardware problems in software. And reversing the potential on an LED then sampling the voltage over time is a snap to implement on many modern embedded processors.

If you are open to hardware solutions, microchip.com makes a chip which projects an electrical field in front of a PCB for 3 dimensional gesture recognition. However, the PCB layout is touchy.

Also, there are gesture sensors that (probably) use IR radiation to track movement. Here's one that supposedly does X Y & Z as well as sense colors. And it sounds like there is already an Arduino library written for some simple gestures. Looks like there's a YouTube video as well.

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


title: Can I short this code?

text:
# Question
Title: Can I short this code?
```
int r = 12;
int g = 11;
int b = 10;
int sw = 4;
int x;
int c = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

void loop() {
    x = digitalRead(sw);
  if(x==HIGH) {
    delay(250);
    c++;
    if(c==1) {
        digitalWrite(r, HIGH);
        digitalWrite(g, LOW);
        digitalWrite(b, LOW);
       {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }

    }
    else if(c==2) {
        digitalWrite(r, LOW);
        digitalWrite(g, HIGH);
        digitalWrite(b, LOW);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
        else if(c==3) {
        digitalWrite(r, LOW);
        digitalWrite(g, LOW);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
        else if(c==4) {
        digitalWrite(r, HIGH);
        digitalWrite(g, HIGH);
        digitalWrite(b, LOW);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
            else if(c==5) {
        digitalWrite(r, LOW);
        digitalWrite(g, HIGH);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }

    }
            else if(c==6) {
        digitalWrite(r, HIGH);
        digitalWrite(g, LOW);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        c=0;
      }

    }

  }
}

```

# Answer
> 1 votes
```
int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

void loop() {
  x = digitalRead(sw);
  if(x==HIGH) {
    delay(250);
    c++;
    if(c==1)      setRGBandBlink13(HIGH,LOW,LOW,1);
    else if(c==2) setRGBandBlink13(LOW,HIGH,LOW,2);
    else if(c==3) setRGBandBlink13(LOW,LOW,HIGH,3);
    else if(c==4) setRGBandBlink13(HIGH,HIGH,LOW,4);
    else if(c==5) setRGBandBlink13(LOW,HIGH,HIGH,5);
    else if(c==6){
      setRGBandBlink13(HIGH,LOW,HIGH,6);
      c=0;
    }

  }
}

void setRGBandBlink13(bool newR,bool newG,bool newB,int times){
  setRGB( newR, newG, newB);
  blinkPin13(times);
}

void setRGB(bool newR,bool newG,bool newB){
  digitalWrite(r, newR);
  digitalWrite(g, newG);
  digitalWrite(b, newB);
}

void blinkPin13(int times){
  for(int i=0;i<times;i++){
    digitalWrite(13,HIGH);
    delay (250);
    digitalWrite(13, LOW);
    delay (250);
  }
}

```

# Answer
> 1 votes
This Sketch is way shorter and way better to maintain.
Note that 1/3 (26 out of 78) of the lines are comments.

Note:
Your RGB is able to display 8 states, but only 7 can be reached.
binc - c - RGB
000 - 0 -
001 - 1 - R
010 - 2 - G
011 - 3 - RG
100 - 4 - B
101 - 5 - R B
110 - 6 - GB
111 - 7 - RGB - NEVER REACHED

```
int r = 12;
int g = 11;
int b = 10;
int sw = 4;
int c = 0;
int maxC = 6;
int minC = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

// for  (pulses)-times
// set  (targetPin) HIGH
// wait (msDelay)
// set  (targetPin) LOW
// wait (msDelay)
void pulse( int targetPin, int msDelay, int pulses ){
    // count to pulses
    // for each count, set targetPin HIGH and LOW
    // wait msDelay between each state change
    for ( int i = 0; i <= pulses, i++ ){
        digitalWrite( targetPin, HIGH );
        delay( msDelay );
        digitalWrite( targetPin, LOW );
        delay( msDelay );
    }
}

// int rgbBinary will set RGB according to its binary value.
// R ~= BIT_1
// G ~= BIT_2
// B ~= BIT_4
void setRGB( int rgbBinary ){
    // set each LED OFF
    // This is by far more performant than
    // checking which should keep its state.
    digitalWrite( r, LOW );
    digitalWrite( g, LOW );
    digitalWrite( b, LOW );

    // if rgbBinary contains BIT value 1, set R to HIGH
    if ( rgbBinary & 1 ) {
        digitalWrite( r, HIGH) ;
    }
    // if rgbBinary contains BIT value 2, set R to HIGH
    if ( rgbBinary & 2 ) {
        digitalWrite( g, HIGH );
    }
    // if rgbBinary contains BIT value 4, set R to HIGH
    if ( rgbBinary & 4 ) {
        digitalWrite( b, HIGH );
    }
}

void loop() {
    // INPUT on SW ?
  if ( digitalRead( sw ) == HIGH) {
    // wait 250ms
    delay( 250 );
    // incement c
    c++;
    // increment RGB status
    setRGB( c );
    // pulse OUTPUT 13 (c)-times
    // starting by HIGH
    // delay 250ms between each HIGH/LOW
    pulse( 13, 250, c );
    // reset (c) on maxC
    if ( c == maxC ){
        c = minC;
    }
  }
}

```

# Answer
> 0 votes
I don't have an appropriate circuit handy for testing, but I've condensed the code a bit and renamed some things to be more readable. Hopefully the result is the same! Importantly, I've changed your `c` to `step` and it is now zero-based, so "step 1" is 0 and "step 6" is 5, etc.

```
const int rPin = 12;
const int gPin = 11;
const int bPin = 10;
const int swPin = 4;
const int pin13 = 13; // Needs a better name!
const int msDelay = 250;

int step = 0;

// By pure luck, your patterns overlap, so they can be condensed like so.
const byte patterns[13] = {
    // 0         1          2          3          4           5
    HIGH, LOW, LOW, HIGH, LOW, LOW, HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH
};

void setup()
{
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
    pinMode(swPin, INPUT);
    pinMode(pin13, OUTPUT);
}

void loop()
{
    if (digitalRead(swPin) == HIGH)
    {
        delay(msDelay);

        // Write red/green/blue pattern
        int index = step * 2;
        digitalWrite(rPin, patterns[index]);
        digitalWrite(gPin, patterns[index + 1]);
        digitalWrite(bPin, patterns[index + 2]);

        // Blink once for each step (0 through 5)
        for (int i = 0; i <= step; ++i)
        {
            digitalWrite(pin13, HIGH);
            delay(msDelay);
            digitalWrite(pin13, LOW);
            delay(msDelay);
        }

        // Increment or reset step
        step = (step < 5) ? step + 1 : 0;
    }
}

```

# Answer
> -1 votes
Make all those ints in a single line.

```
int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

```

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


# Question
Title: Arduino struggling to power a large LED strip
I'm building a word clock and its a grid of 20x20 letters, each with its own LED (I know, its absurd for just a clock). I've recently got the LED's on a strip. Its the WS2812B type, just like the neopixels. There are 3 rolls of 5m strips and a single 1m strip. When I tried to power the 1m strip, everything worked perfectly and all looked quite lovely. But when I tried the 5m strip (just one of them), this happened: https://www.dropbox.com/s/5w1lok6wa7dfvzd/IMG\_0046.MOV.mov?dl=0

If you didn't see the video I recorded of it, for a second or two after powering the arduino (uno) on, it works as expected but not long after it all stops the colors and fades to red, sometimes it just instantly jumps to it, like the second time in the video. I don't know what happened but all I can guess is that the arduino is not able to power the strip properly. Any ideas on what I should do to be able to power a total of 16m of these strips?

# Answer
WS2812 use around 1mA when they are off. So that's already 400mA with no LED lighted. USB can supply around 500mA. So you only have 100mA available.

Each led package has three colored leds inside; Red, Green and Blue. Every color will use around 20mA when fully turned on.

So you can only turn on 5 colors at full brightness at 500mA.

Using a 2.5A supply you could go up to 105 colors, or 35 leds full white.

This would be more than enough for a word-clock, as most leds will be off.
> 1 votes

# Answer
You're trying to power a consumer which draws more current than the arduino could provide.

To fix this, you need an transistor and a ~5V battery (e.g. 4.8V NiMh, or a stronger batteries plus suitable resistors, to not burn out the leds)

Look at this (awesome paint) shematic to understand the principle. The arduino will switch the transistor through S2 which then closes the circuit. Through S1, the arduino can set the LEDs values.

Note that for savety, you should also set a diode between S1 and the LEDs, so the battery cannot burn out your arduino, if the LED strip is cheap made.

The reason why the behavior at your setup differs might be because of a capacitor on the arduino which works similar to a batterie (With extreme little capacity). The capacitor might provide enough power to run the LEDs for a very short periode. After discharging, the capacitor needs some time to recharge and thus it may vary in effect.
> 0 votes

---
Tags: arduino-uno, power, led, rgb-led
---


title: UNO Power supply to USB

text:
# Question
Title: UNO Power supply to USB
If UNO is supplied with 9VDC to Power Jack. **Will it supply power to USB** connector?

# Answer
**No**

As you can see in the schematic, the USBVCC is only connected (via a MOSFET) to the 5V line, when the voltage on VIN (barrel jack) is LOW.

If you connect 9V to the power jack, the mosfet will turn of, and disconnect the USB power from the 5V on the UNO.
> 2 votes

---
Tags: arduino-uno, power
---


# Question
Title: Power Arduino from 230v with battery fallback
I've build a fairly simple doorbell using Arduino Pro Mini 3.3V: https://www.youtube.com/watch?v=WFd94CYT2Lw&feature=youtu.be

Here's the current setup:

* Arduino running off the 9 V battery
* A simple speaker is connected to Arduino (powered from the battery, Arduino just drives it through a transistor)
* Arduino is reading light level from the light meter every 200 ms.
* Bulb is connected to the wire that is lit up when someone presses the doorbell button.

It works well - someone presses the doorbell button, bulb gets lit up, Arduino notices that (using light meter) and doorbell rings.

**Problem**

In short - battery life. This kind of setup lasts around 2-3 days off a single battery. I was reading all about how to run Arduino off a single battery for a few weeks, even months, but I'm not sure it's feasible in my case. First of all, I need to wake up Arduino every 100-200, maybe 500 milliseconds, to read the light level. Plus, many of those long-battery-life solutions involved basically building own Arduino-compatible scheme from scratch, which I'd like to avoid.

**Idea**

But... I have a 230 V power source - the one that drives the bulb. Issue is that this power source is down all the time, unless someone is pressing the doorbell button.

I could approach it in two ways:

1. When someone presses the button, I'd power the Arduino and immediately play a song. Issue with that approach is that if someone presses the button for just a split second, my Arduino would be powered up for just that short amount of time, and I wouldn't have enough time to play the complete song.
2. If I could possibly reverse the way doorbell button works, I could have +230V all the time, and 0 when someone presses the button. This way Arduino would be on all the time, and it would "notice" someone pressed the button when power would go down. Issue with that approach is that song would be played only once guest would release the doorbell button, + the time it takes for an Arduino to boot.

In both #1 and #2, I need two things then:

a) have Arduino on all the time, regardless of whether button is pressed or not

b) power Arduino from the doorbell to avoid having to use a battery

Which kind of means that I need to power Arduino from a dual source - 230 V and rechargeable battery. 230 V when available, and battery when 230 V goes down. In a perfect scenario, this battery would be charged from 230 V source too :)

Any ideas how to built such a thing? Is there some AC power module that I could use? How would I wire things up in such a case - Arduino, AC power module, rechargeable battery?

Or maybe I'm missing some easier, simpler solution here?

# Answer
> This kind of setup lasts around 2-3 days off a single battery.

I measured 15.8 mA consumption on my Pro Mini, running from 9V. A typical 9V battery may have a capacity of 500 mAh, so that is 500 / 15.8 = 31.6 hours. Thus your observed consumption is about right.

Probably 10 mA of that is the LED, so removing it would help. I have a page about power saving. You would want to investigate going into sleep mode, and waking long enough to check the light. You might be able to arrange a LDR in such a way that it generates an interrupt and wakes the processor immediately from a deep sleep.

---

## Example of waking using an LDR

I made up a test like this:

D2 is one of the external interrupt pins so we can write a simple low-power sketch that sleeps all the time until the LDR gets enough light that the resistance drops, and D2 goes HIGH.

```
#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precautionary while we do other stuff
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  }  // end of setup

void loop ()
{

  // flash LED 5 times
  for (byte i = 0; i < 5; i++)
    {
    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
    delay (100);
    digitalWrite (LED, LOW);
    delay (100);
    }

  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes high
  attachInterrupt (0, wake, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

```

---

My example just flashes an LED on pin 9 five times, that is where you can play your doorbell sound. Now, with no major external circuitry (like LEDs that are always on) it should have low power consumption.

> What would be a good replacement for it, with low power draw and support for interrupts?

The LDR as described above. I measured 3 µA through the LDR when it was partly covered with a black box (my glasses case) and the room lights off. However it was daylight. I think that is pretty acceptable.

---

Come to think of it, you could probably turn this into a nice "doorway detector" (like they have in shops where it plays a sound when you break a light beam at the doorway). By arranging the LDR in a tube at one side of the door, and shining a light across the doorway into it (and probably tweaking the resistor values a bit) it would play a sound once you cross the beam.
> 3 votes

# Answer
You can run a Pro-Mini just fine of a battery. It's the UNOs that cause a lot of problems, because of the onboard USB-to-Serial chip. The only thing you might want to tweak on this board, is removing the power-led, which I've recently done with a knife.

I poll the reflectivity of my power-meter every 250ms, and I'm getting at least 3 months of battery life out of 2 AA-batteries.

Depending on the light sensor you are using, you could even use interrupts to wake up the Arduino when the light is on, instead of having to poll every few milliseconds.
> 2 votes

# Answer
A small solar cell would not require excitation and would probably generate enough voltage to trigger an interrupt pin and wake up the MCU.
> 1 votes

# Answer
If you make it so that the light only goes out when you press the button, and connect a battery charger with that bulb in parallel, put a battery in the charger and plug the arduino into the battery, then use the light sensor approach to detect the button press and play a tune, it would work just fine... Really the only 3 things you might wanna worry about are the user holding the button for a few hours (which is very unlikely), power outages (can be solved using a UPS), and replacing the battery/bulb once every few years, depending on how good it is... Probably the simplest approach, not sure if it is the best tho... But why not just plug the arduino to a phone charger that is then connected to the wall, and then use the doorbell switch as input for the arduino?
> 1 votes

---
Tags: power, arduino-pro-mini, battery
---


title: Arduino Blocks at Uploading

text:
# Question
Title: Arduino Blocks at Uploading
I am trying to make an operating hours counter with arduino, i started with a basic script to make the arduino work as a stop watch, This is my script:

```
unsigned long start=0, finish=0, elapsed=0;

 void setup() {
 Serial.begin(9600);
 Serial.println("Clock START");
 }
 void displayResult(unsigned long elapsed){
   float h,m,s,ms;
   unsigned long over;
   h=int(elapsed/3600000);
   over=elapsed%3600000;
   m=int(over/60000);
   over=over%60000;
   s=int(over/1000);
   ms=over%1000;
   Serial.print("Elapsed time: ");
   Serial.print(h,0);
   Serial.print("h ");
   Serial.print(m,0);
   Serial.print("m ");
   Serial.print(s,0);
   Serial.print("s ");
   Serial.print(ms,0);
   Serial.println("ms");
   Serial.println();
 }

 void loop() {
   start = millis();
   delay(200);
   Serial.println("Start");
   Serial.println("doing Operations and stuff");
   delay(800);
   finish=millis();
   elapsed=finish-start;
   Serial.println("Ended !!!");
   displayResult(elapsed);

 }

```

Unfortuantly the arduino compiler blocks at the Uploading part, i tried compiling it at first without uploading, it gave me no warning errors. I tried compiling other scripts they worked, it only blocks for this stop watch code.
Thank you for your help

# Answer
> 2 votes
There is a bug in early versions of the Mega2560 bootloader. It crashes on `!!!` (or enters some other special state that stops uploading happening).

Your string that contains `!!!` will be breaking it:

```
Serial.println("Ended !!!");

```

Simple solution: don't use so many exclamation marks.

---
Tags: arduino-mega, uploading, millis
---


# Question
Title: I want to begin with arduino programming
I want to start programming with the Arduino Uno, but I don't know where to start or what a good start is. I can program a bit in c#, but I red that you have to program in c++.

Any idea's where to start?

Thanks!

# Answer
The other suggestions are great. If you want to make a more "academic" approach, I can recommend two courses on Coursera:

I've followed and completed these 2 courses, and I think they were great fun. They give a light-weight introducton to the Arduino, with only a little time consumption needed.
> 1 votes

# Answer
You can purchase some great starter kits too:

They're easy to search for, here's a few that popped up right away:

http://www.arduino.cc/en/Main/ArduinoStarterKit

http://www.amazon.com/Kuman-Project-Complete-Starter-breadboard/dp/B016D5KUHS/

And here's one that I own, and I've recommended to other people:

http://www.microcenter.com/product/458578/Arduino\_Compatible\_Maker\_Kit\_with\_LCD\_Display

If you have a microcenter or radio shack or Fry's in your area, they all stock a variety of different starter kits.
> 2 votes

# Answer
Welcome to the world of Arduino. You can start by going directly to the Arduino Site -\> Learning & tutorials. Also the internet full of 100's, if not 1000's of information and tutorials.
> 1 votes

---
Tags: arduino-uno
---


title: Using buttons with Arrays

text:
# Question
Title: Using buttons with Arrays
I am trying to write a simple program that will cycle through an array using push buttons. My current version of the program uses if statements and prints lines.

My goal is to have contact information for 4 people stored in an array. I can either have an array of strings per person or make different arrays of strings for the different type of information (ie names, phone numbers).

I would like one push button to cycle through the data in one direction and another push button to cycle through the data in the other direction. This is my code so far using the if statements. I modified the code from a traffic light tutorial hence you will see some of the variables named after colors.

```
//------------------------------- Declare variables
int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
char user_name_array[32];
char econ_one_name_array[32];
char econ_two_array[32];
char econ_three_name_array[32];

//------------------------------- Setup
void setup() {
  Serial.begin(9600);
  //------------------------------ Sets pins for I/O
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("ID");
  Serial.println(user_name_array);
}

//------------------------------- Main Program
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      Serial.println("Athlete");
      Serial.println("John Smith");
      Serial.println("No allergies, no medications");
      Serial.println("  ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      Serial.println("Emergency Contact - Sister");
      Serial.println("Eliza Smith");
      Serial.println("Cell - 333.888.777");
      Serial.println("  ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;

    } else if (state == 2) {
      Serial.println("Emergency Contact - Hermosita");
      Serial.println("Jackie Smith");
      Serial.println("Cell - 777.888.7777");
      Serial.println("  ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      Serial.println("Emergency Contact - Father");
      Serial.println("Michael Smith");
      Serial.println("Cell - 888.777.777");
      Serial.println("  ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

void setLights(int red, int yellow, int green, int blue) {
  digitalWrite(ledPinOne, red);
  digitalWrite(ledPinTwo, yellow);
  digitalWrite(ledPinThree, green);
  digitalWrite(ledPinFour, blue);
}

```

I also have a 4-LED setup. When the button is pushed one of the LEDs turns on and then when the button is pushed again it turns off and turns the second one on and so forth.

Thank you in advance for any help.

**EDIT:**

This question was asked again in a more detailed way and has more answers here:

Using a button to cycle an array

# Answer
Let's just deal with character strings.

The truth of the matter is that Arduino programming uses the language C. C is very common and you can search for help in many places.

There are several ways to deal with strings in C. In this example we are using an array of pointers to strings:

```
// let's make our own array of strings
char *states[] = {
    "California", "Oregon",
    "Washington", "Texas"
};
int num_states = 4;

for(i = 0; i < num_states; i++) {
    printf("state %d: %s\n", i, states[i]);
}

```

The output of this code looks like:

```
state 0: California
state 1: Oregon
state 2: Washington
state 3: Texas

```

I grabbed this example from here.

added later...

The method "printf" is normally not used in Arduino land. So that "for" loop would look more like:

```
for(i = 0; i < num_states; i++)
{
 Serial.println("state ");
 Serial.println(i)
 Serial.println(states[i]);
}

```
> 0 votes

---
Tags: programming
---