# Question
Title: WeMOS creating soft access point from old code even when new code doesn't have it
In the past I uploaded the code below:

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

#define DHTTYPE DHT22     // DHT 11
#define DHTPIN D5
DHT dht(DHTPIN, DHTTYPE);

const char *ssid = " Hello_IOT";
const char *pass = "12345678";
String command;
ESP8266WebServer server(8080);

void respond(){
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  server.send(200, "text/html", "<h1>Hello from Wemos R1 Mini</h1>");
}

void outputJson(){
  char temp[400];
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  int tf = dht.readTemperature(true);
  snprintf(temp, 400, "{\"wittyCloud\" : [{\"location\" : \"any\" ,\
    \"temperatureInC\" :%d ,\
    \"temperatureInF\" :%d ,\
    \"humidity\":%d,\
    \"ldr\":%d\
    }]}",
  t, tf, h, analogRead(A0));
  server.send(200, "text/json", temp);
}

void setup(){
  Serial.begin(115200);
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println("Connect to access Point");
  WiFi.softAP(ssid, pass);
  IPAddress IPserver = WiFi.softAPIP();
  Serial.println(" IP address server : ");
  Serial.println(IPserver);
  server.on("/", respond);
  server.on("/json", outputJson);
  server.begin();
  server.onNotFound([](){
    command = server.uri();
    server.send(200, "text/plain", command);
  });
}

void loop(){
  server.handleClient();
  if(command.equals("/mati")){
    digitalWrite(BUILTIN_LED, HIGH); //turn off BUILTIN LED
  }
  if(command.equals("/hidup")){
    digitalWrite(BUILTIN_LED, LOW); //turn on BUILTIN LED
  }
}

```

For learning purpose it worked, however when I modified it to the code below for WeMOS, to connect to my home wifi router, it creates instead an access point, and on opening the URL after connecting to the WeMOS access point it displays the web page of the updated code.

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include "control.h"
#include "webpage.h"
#include <DHT.h>

ESP8266WebServer server(80);
const char* sid = "router+ssid";
const char* passwd = "ssid_password";

#define DHTTYPE DHT22     // DHT 22
#define DHTPIN D5
DHT dht(DHTPIN, DHTTYPE);
const char* host = "nodemcu";

void outputJson(){
  char temp[400];
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  int tf = dht.readTemperature(true);
  snprintf(temp, 400, "{\"wemos\" : [{\"location\" : \"bangalore\" ,\
    \"temperatureInC\" :%2d ,\
    \"temperatureInF\" :%2d ,\
    \"humidity\":%2d\
    }]}",
  t, tf, h);
  server.send(200, "text/json", temp);
}

void handleRoot(){
  const int nsize = 2300;
  char temp[nsize];
  delay(200);
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf(temp, nsize,
    "%s\n<!-- add btns here --></\div></body>\n\
    </html>",webpage::html);
  server.send(200, "text/html", temp);
}

void handleNotFound(){
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message +=(server.method()== HTTP_GET)? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for(uint8_t i = 0; i < server.args(); i++){
    message += " " + server.argName(i)+ ": " + server.arg(i)+ "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void) {
  Serial.begin(9600);
  // config static IP
  IPAddress ip(192, 168, 1, 88);
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress dns(192, 168, 1, 1);
  WiFi.config(ip, dns, gateway, subnet);
  WiFi.begin(sid, passwd);
  Serial.println("");
  EEPROM.begin(512);

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

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(sid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if(MDNS.begin(host)){
    Serial.println("MDNS responder started");
  }
  MDNS.addService("http", "tcp", 80);
  server.on("/", handleRoot);
  server.on("/json", outputJson);
  server.on("/control", control::toggleRelay);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println(F("HTTP server started"));
}

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

```

# Answer
> it creates instead an access point

Did you use setmode() to put it in station mode?

**wifi.setmode()**

Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

* Station mode, where the NodeMCU device joins an existing network.
* Access point (AP) mode, where it creates its own network that others can join.
* Station + AP mode, where it both creates its own network while at the same time being joined to another existing network.
* WiFi off.

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.

NOTE: WiFi Mode configuration will be retained until changed even if device is turned off.

**Syntax**

```
wifi.setmode(mode)

```

**Parameters**

mode value should be one of

* wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
* wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
* wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
* wifi.NULLMODE to switch off WiFi

**Returns**

current mode after setup

> WeMOS access point it displays the web page of the updated code

I think @Ciasto answered that part.
> 1 votes

# Answer
I had this issue with one of my chips. I eventually fixed it by using the SPIFFS uploader tool and uploading a blank "data" folder.
> 0 votes

---
Tags: programming, esp8266, web-server, nodemcu, software
---


# Question
Title: Powering ESP8266 from Leonardo's 3.3v pin
I'm new to Arduino, and I'm trying to connect my Leonardo via WiFi using a ESP8266 module. What I want to know is if I can power it directly from the onboard 3.3V pin like in the image:

Or do I need an external voltage regulator? I don't want to damage it. Thanks!

# Answer
> 4 votes
The Leonardo is specified to provide only 50mA on the 3V3 pin. A ESP8266 can use up to almost 300mA when transmitting. Consider using a LDO regulator connected to the 5V pin instead.

# Answer
> 1 votes
Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module.

---
Tags: power, esp8266, arduino-leonardo
---


# Question
Title: Conflicts with USB and external power supply
I want to power an Arduino Leonardo with an external power supply and simultanously communicate via USB. I have read some other threads on this topic, therefore, I know that if one supplies more than 7V over the power jack, the board will use the external power supply in this case.

My suspicion is rather concerning the ground connection. From the schematic, I can tell that the USB ground is connected via a tiny coil to the board ground, so with DC it is shorted. Wouldn't that cause problems if the computer's USB ground is at a different potential than the external power supply of the board, resulting in a voltage between the two grounds? What if this voltage is up to several Volts?

Thanks a lot!

# Answer
Why do you suspect a potential difference? Where is th 7V coming from? If the 7V power supply is free floating and used for nothing else, there is no source for potential difference.

A typical wall wart will have a free floating output.
> 1 votes

# Answer
When you connect the USB, you also connect the ground of the computer to he arduino board. And then when the external power supply is connected to the arduino board the negative pin or the ground pin coming from the external power supply is connected to the ground pin of the USB. Thus the external power supply and the PC share the same ground.
> 1 votes

# Answer
I am going to clear one thing, many students and hobbyists are still confused and think that their Arduino board will blow away if they use the External power supply at the same time when Arduino board is connected to the pc through USB cable. This statement is totally wrong, you can give power to the Arduino board by using both sources at the same time and Arduino board is intelligent device it will choose the best input power having more current as compared to the other one.
> 1 votes

# Answer
To answer your question: I have never seen a conflict like that.

I power my Unos with CCTV-style power supplies (12V) when I am using the HC-11 Wireless module which requires 100 mA or more in order to communicate.

When powered on just USB they can't talk at all. I mean, not at all - like you simply can't make them work until you plug in the second power supply to get more current.

Everything in the board is grounded together, and that it 99% of the battle when using two power supplies. Whether I am programming from a Raspberry Pi or a laptop, it all works the same.
> 0 votes

---
Tags: serial, power, arduino-leonardo, usb
---


title: ESP8266 not working properly

text:
# Question
Title: ESP8266 not working properly
It's the first time I use an ESP8266 and I didn't manage to get a proper response in the Arduino serial monitor. I only see weird characters, when I move the 3.3V wire.

You can see the connections in the following picture:

The code I run is the following one:

```
#include <SoftwareSerial.h>
SoftwareSerial BT1(3, 2); // RX | TX

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

void loop()
{
    String B= ".";
    if (BT1.available())
    {
        char c = BT1.read();
        Serial.print(c);
    }
    if (Serial.available())
    {
        char c = Serial.read();
        BT1.print(c);
    }
}

```

Maybe it's something really stupid. I am a total beginner, so I appreciate any help.

EDIT: I think power supply is 3.3V

SOLUTION: the problem was the power supply. I tried exactly the same using the 3.3V from the arduino instead of the power supply and it works perfectly!

# Answer
You may well have killed the ESP by supplying it 5v, you have to have a logic level shifter, as Juraj says.

Assuming it's not dead then your next problem is there have been posts about that hardware setup and SoftwareSerial doesn't work at high speed. I can't tell you what it is that doesn't work because turning the speed of the link cures the problem, try 9600 maximum.

\[Edited to be less accusational, which was not the original intent\]

**\[Update\]**

Please see the datasheet here: https://www.mikrocontroller.net/attachment/231858/0A-ESP8266\_Specifications\_v4.pdf

The table in section 8.4.4 says that the maximum input voltage is 3.6V Just after that it says all digital pins are "protected from over-voltage with a snap-back circuit". This snap back voltage is typically 6V. So does that mean the GPIO are safe up to 6V?

(It might be that this datasheet has been superseded, I am unable to access the EspressIF site at the moment).
> 1 votes

# Answer
**Step 1:** Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module. A voltage divider circuit is used to drop the Arduino 5V to ESP8266 3.3 V.

Step 2: Here is the schematic Diagram, in my code I used Digital pin 2 as a Tx and D3 as an RX.

Click Here for Necessary At Commands
> -1 votes

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


# Question
Title: Storage usage of methods compared to copied code
When you have really small snippets of code that are repeated several times in your micro controller program, is it better to write a method? I mean better in terms of performance and storage usage. I know that when programming for PC, code repetition is a big no go, but what about micro controllers?

In the following example (Arduino Nano with Adafruit 2,8" cap touch display) the snippet should look if the back button is pressed in several screens. I checked in the Arduino IDE how much storage each version takes:

Version 1, 15114 Bytes for complete program:

```
void battScreen(TS_Point p){
  // some other code
  // ....
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void alarmScreen(TS_Point p){
  // some other code
  //...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

```

Version 2, 15234 Bytes for complete program:

```
void checkBack(TS_Point p){
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void battScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void alarmScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

```

As you can see, version 2 with the extra method takes 120 Bytes more storage. Is there a rule of thumb when it makes sense to create a new method instead of copying code?

# Answer
It.... depends

A call to function involves a few things

1. Save the context
2. Move the parameter(s) to the appropriate registers
3. Enter the function
4. **Execute**
5. Eventually save the return value to a register
6. Restore the context
7. **Eventually copy the returned value to the variable**

As you can see, quite a lot of things. The bold points are the ones executed also if you don't use a function.

Please note that if these functions are "methods", you have also a "hidden" parameter (the object you are applying the method onto)

So why use functions? Well, you will have to write this code in flash only once instead of more times.

What is best? It depends on your application.

* You are calling this function only once? Don't use a function
* Your function is really short (for instance, a one-liner)\*? Don't use a function
* You are running out of flash memory? Use a function
* You need a lot of speed? Don't use a function (you add overhead)
* You are not in one of the previous cases? Do as you prefer

+ With one-liner I mean something like, for instance, `byte sum(byte a, byte b) { return a + b; }`; in this case the function also occupies more space, since the call function instruction is compatible with the byte sum

Please note that usually more readability is more important than performances, so maybe using functions should be encouraged. I mean, in your case I'd probably use them unless there is a problem

What to do if you don't want to use a function? Well, there are other techniques:

* Mark the function as inline; this is a hint for the compiler not to create a function but to replicate this every time. This is only a hint, so the compiler may ignore this
* Instead of a function write a macro. This will be substituted every time, but the code will be maintainable. As a drawback, it is much harder to debug with the usual methods.

Just a remark: usually smart compilers can guess what is the best option (inline or function) on their own also for non-inline functions. So you can also trust the compiler in 90% of the cases
> 5 votes

# Answer
The reason I would tend towards the second method more is there is less opportunity for bugs in the second version.

If storage size is a major concern and you know that repeating the code requires less storage, then I would #define it as a macro and get the best of both worlds.

You could improve the code though. At the moment you are passing copies of the variable into functions, passing const references might use less room, `void checkBack(const TS_Point& p){`
> 2 votes

---
Tags: programming, arduino-nano, code-optimization
---


# Question
Title: Trying to create a beats per minute monitor but having diffuctly with the coding? coding wont print any values
Any advice on what coding to adjust. New to Arduino.

```
const int sensorPin = A0;
float voltage=0.0;
int sensorVal=0;
int heartbeats=9;
float BPM=0.0;
const int led1=2;
const int led2=3;
int starttime = 0;
boolean counted = false;

void setup() {
pinMode(sensorPin, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
boolean counted = false;
}
void loop() {

starttime = millis();
while (millis()<starttime+10000)
{
  sensorVal = analogRead(sensorPin);
  if (sensorVal >550 && counted == false)
  {
    counted = true;
  }
  else if (sensorVal < 500)
  {
    counted = false;
  }
}

    BPM = heartbeats*6;
 Serial.println("Your BPM is");
 Serial.println(BPM);
BPM =0;
heartbeats =0;

}

```

# Answer
> 1 votes
There's two basic methods of measuring a frequency, which is basically what you are trying to do.

There is Frequency Counting and Frequency Timing. The latter involves measuring the time between successive pulses and calculating the instantaneous frequency from that. Good for rapidly changing frequencies where you need to know the frequency right away.

Frequency counting is what you are attempting, and is basically counting the number of edges that occur within a certain timeframe.

However your method is slightly flawed: chiefly because you forgot to actually count the edges. You wrote some reasonable code for finding an edge, but failed to actually do anything with that edge.

Also your code is blocking for 10 seconds, which may be fine in this scenario, but is not a good habit to allow yourself to get into.

Instead you should consider something more like this:

```
void loop() {
    static int count = 0;
    static bool counted = false;
    static uint32_t ts = millis();

    int val = analogRead(sensorPin);

    if ((val > 550) && (counted == false)) {
        counted = true;
        count++;
    } else if (val < 500) {
        counted = false;
    }

    if (millis() - ts >= 10000) {
        ts += 10000; // You could assign ts the millis() value, but
                     // by adding 10 seconds it cancels any drift
                     // caused by other delays in your sketch.
        int BPM = count * 10;
        count = 0;
        Serial.print("BPM: ");
        Serial.println(BPM);
    }
}

```

# Answer
> -1 votes
Assuming the input waveform is a low frequency square wave. Multiple ways to do it.

1. Use the input to gate a counter on internal clock. It gives the most precise measurement, with a sub-us resolution.
2. Use external or pcint interrupts to time the start and beginning of an edge.
3. Wait in between edges.

...

Oversampling and algorithm will help smooth out the measurement.

---
Tags: arduino-uno
---


# Question
Title: Connecting ESP8266 with Arduino Uno - WiFi shield not present
I have an Arduino Uno and ESP8266. I want to connect and control an LED from a web server. I made a connection referring to this:

I uploaded the WifiWebServer code to the Arduino, and applied my router's credentials.

```
char ssid[] = "Router SSID";      // your network SSID (name)
char pass[] = "Router's WPA Password"; `

```

I'm getting a "Wifi Shield not present" message from the Serial Monitor. I even tried giving external 3.3v power supply to my ESP8266 module, but no change. What am I missing here? Can someone help me fix this issue?

# Answer
From your diagram, you appear to be using an ESP8266-01?

Another ESP8266 AT command library that may be of interest/use.

Note that the AT command libraries are very dependent on the version of the firmware that you have on the device. Depending on when/where you bought the device, this firmware will vary significantly. I've not had any of the libraries work correctly with current versions of the firmware.

Run the `AT+GMR` at command (using your serial terminal) to determine the firmware version. If you're on Windows/PC updating the firmware to a previous version (the 0.9.x.x range seems to be the most stable according to my research) is relatively straightforward. If you're on Mac, it's not as straightforward...

Official/current release of the firmware is available from Espressif's Github repo.

There are plenty of directions on the net for getting firmware onto the ESP8266 for both Mac and Windows/PC. YMMV as to their accuracy/ease of use.

Note that different versions of the firmware default to different baud rates. Some default to 115200, others to 9600. If you decide to use SoftwareSerial (rather than Serial, which your diagram suggests is what you're currently using) you'll need it to run on 9600. I've not personally tested what Serial supports up to (but my understanding is that you can run up to 115200). Note that there are different commands for setting the ESP8266 AT command firmware baud rate depending on the firmware version/supplier. The official SDK uses the `AT+IPR=9600` command. This stores the baud rate to the device (i.e. you don't need to send it every time, just once and it's then persistent).

If you haven't already, I'd recommend you get the system working with a simple serial terminal program (CoolTerm, for example) before getting into Arduino-land.

Note that the ESP8266 does not reliably run from the 3v3 power rail on the Arduino. The ESP8266 requires up to 300mA, the Arduino is capability of around 50mA to my understanding. Symptoms of insufficient power include random resetting of the device. Best to run a separate 3v3 source to the ESP, or if you have a strong enough 5v supply, use a step-down converter. Your diagram indicates you're using a standard Arduino, which runs 5v out of the serial pins (or digital outs), but your comments indicate you're running 3v3 (which means you're probably running a 3v3 Pro Mini or similar)? If you're not running a 3v3 device, you'll definitely need to run a 5v-3v3 logic level converter (I can't link to examples due to not having enough reputation points—but these are relatively easy to get from SparkFun or similar. I picked up a combined step-down converter with logic level converter which does both tasks.

Lastly, If you don't need the ADC from the Arduino device for your application (which it sounds like you don't given your project description) I'd **strongly** recommend you reconsider the advice from gmag11 and yeti re: running Arduino on the ESP8266. It is much more stable, and the extra SRAM will make a big difference with processing/building HTTP request strings etc. I wasted a *lot* of time (unsuccessfully) trying to get AT commands working before switching to Arduino on the ESP8266, which has been a breeze by comparison.
> 1 votes

# Answer
You can program and upload code to ESP8266 using Arduino programming environment, reusing code and libraries with small changes. Check https://github.com/esp8266/Arduino for more information.

For most tasks ESP8266 may substitute Arduino board completely. It has more flash, more RAM and integrated WiFi, and is faster (80MHz).
> 3 votes

# Answer
The WiFiWebServer tutorial describes how to use the ArduinoWiFiShield. This shield is based on different WiFi hardware than the ESP8266 modules.

You need a WiFi library driving the ESP8266 modules instead, e.g WeeESP8266.

Your favourite internet finding machine sure will find lots of similar libraries.

A different approach would be ArduinESP (https://github.com/esp8266/Arduino), which means to develop code to run on the ESP8266 module directly.

---

...aaaand please rethink your wiring. The ESP8266 modules are a pure 3.3V pets and your wiring connects a 5V logic signal directly to the ESP8266 and this may send your ESP8266 into the digital heaven with or without waving goodbye using blue smoke...
> 2 votes

# Answer
ArangaNathan has posted another Fritzing diagram with the same errors as the opening diagram:

1. You can't drive the ESP8266 from the Arduino 3.3V pin as it can only supply 50mA but the ESP requires \> 200mA to transmit properly.
2. All I/O wires between Arduino and ESP must be level shifted from 5V to 3.3V otherwise you will damage the ESP. It may not happen straight away, but it will happen.
3. If you wire Arduino Tx \<-\> ESP Tx and Arduino RX \<-\> ESP Rx you must remove the Arduino MCU chip completely before powering on, and use the Arduino IDE monitor to send commands to the ESP.
4. If you don't remove the MCU then you have to wire Arduino TX-\>RX and Arduino Rx\<-TX.
5. If also you want to use the Arduino IDE in this mode (MCU installed) then you can't wire ESP TX/RX to D0/D1 and must use other pins instead (e.g. D2/D3) and SoftSerial to create another serial UART port.
> 1 votes

# Answer
Fritzing's wiring diagram has errors. 1) the serial connections wrong way around. You need to swap them so that Arduino TX -\> ESP Rx and Arduino RX \<- ESP Tx. Also 2) the ESP-01 require more than 200mA so supplying voltage reg cannot be provided from the Arduino 5V pin. It must be supplied by VIN with a supply able to provide 1A.
> 0 votes

# Answer
For the esp you must use an external 3.3v power source (300 mA or more), and a logic level converter for the esp Rx (arduino Tx is in 5v logic).
> 0 votes

# Answer
Here is how to send commands to an ESP8266, without using an FTDI Programmer (NOTE: the IC used is LM117 (5V to 3.3v) IC for level shifting.)
> -1 votes

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


# Question
Title: Conversion between boolean and int went wrong
I have a small problem with conversion from bool array to int. It is working fine until it comes to the 12th cycle of while. I don't know why but this is really weird.

I try to paste here a code where I am doing this conversion.

```
int* BoolToInt(bool* set) {
  int* ret = (int*)malloc(3*sizeof(int));
  int sum0 = 0;
  int sum1 = 0;
  int sum2 = 0;
  //bool test[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1};
  for(int m=0; m<24; m++) {
    if(m<8) {
      sum0 += (int)set[m] * (pow(2,m));
    }
    if(m>7 && m<16) {
      sum1 += (int)set[m] * (pow(2,(m-8)));
    }
    if(m>15 && m<24) {
      sum2 += (int)set[m] * (pow(2,(m-16)));
    }
  }
  ret[0] = sum0;
  ret[1] = sum1;
  ret[2] = sum2;
  Serial.print("\n ret[0] = ");
  Serial.print(ret[0]);
  Serial.print("\n ret[1] = ");
  Serial.print(ret[1]);
  Serial.print("\n ret[2] = ");
  Serial.print(ret[2]);
  return ret;
}

```

And this is where I am using this function:

```
void Fitness(bool** set) {
  int maX = 0;
  int index = 0;
  int* temp;
    for(int i=0; i<10; i++) {
    int* phenotype = BoolToInt(set[i]);
    _fitness[i] = 1000/((phenotype[0] - _colours[0])*(phenotype[0] - _colours[0]) + (phenotype[1] - _colours[1])*(phenotype[1] - _colours[1]) + (phenotype[2] - _colours[2])*(phenotype[2] - _colours[2]) + 1);
    Serial.print("\n phenotype[0] = ");
    Serial.print(phenotype[0]);
    Serial.print("\n phenotype[1] = ");
    Serial.print(phenotype[1]);
    Serial.print("\n phenotype[2] = ");
    Serial.print(phenotype[2]);
    free(phenotype);
  }
  for(int i=0;i<10;i++) {
    temp = BoolToInt(set[i]);
    if(_fitness[i]>maX) {
      maX = _fitness[i];
      index = i;
    }
  }
  setColorOnSecond(temp[index]);
  free(temp);
}

```

As seen in the Fitness function, I have some debugging prints to see if everything is fine. My main is in the while cycle. Everything is fine and "ret" from BoolToInt function is the same as "phenotype" in Fitness, which is a good thing and this is what I want. But then the 12th cycle comes and phenotype\[1\] gives me 1200 as int. And of course everything in ret\[\] is fine(0-255). Am I doing something wrong?

NOTE: bool\* set in BoolToInt is 24 bool array (yes 3 numbers as you can see).

NOTE 2: every previous cycle before 12th cycle is good and the result are equal.

# Answer
> 0 votes
Your problem is using pow. It works in floats. It may come as some surprise, but pow(2,3) gives 7 when you put it into an int.

Don't waste time on pow for powers of 2. Just use a bitshift. It's way smaller and faster.

# Answer
> 0 votes
Let me the first one to say that 1. Boolean to int conversion shouldn't be this complicated and 2. Much simpler ways to do what you are trying to do.

Like this.

If (bool) boolint |= mask; Mask = mask \<\< 1; ...

You get the idea.

---
Tags: arduino-uno, convert
---


title: Detecting step motor effort

text:
# Question
Title: Detecting step motor effort
I'm working on a project using steper motor which turn a threaded shaft (long screw) in order to open or close a water valve (high flow, high pressure).

My fear is that, after a long time of use, the grease on the threaded shaft will dissapear and it can became hard for the stepper motor to rotate correctly the threaded shaft.

In order to tell the user to add grease, I have to know when the stepper needs more effort than before to rotate the threaded shaft. So, would it be possible to detect the "effort" made by the stepper in order to get this information on the Arduino?

Any ideas are welcomed!

# Answer
> 2 votes
I suggest that if the answer involves the Arduino, the question might be appropriate to this forum.

If you can mount your stepper motor in such a manner as to apply pressure to a force sensor, you may have a method to resolve your goal.

As the motor rotates, under normal conditions, pressure on the sensor will give you a baseline on which you can base your program for consideration of the amount of force involved.

Picture the motor mounted in the center of a circle, with cut-outs appropriate for the mounting bolts. On the outside of the circle, you would have suitable bearing surfaces to reduce rotational friction. From the motor circle platform, a lever pressing against a fixed point on the outside of the circle provides the contact points for the pressure sensor.

If you will be rotating the motor in both directions, perhaps a pair of sensors mounted to encase the lever would be suitable.

When the screw is new, clean and lubricated, you can collect pressure readings and establish a safe and comfortable range. Those numbers would be fixed into your code and measured during motor activity.

If the activity results in force outside the range, you can either stop or reverse the motor and have the same checks apply.

The logic and code is beyond my capability, but you'd have very few parameters to examine during operation.

# Answer
> 1 votes
After fred\_dot\_u answer I have made other research. Not sure this can help us (Look Alterno and me), but some post are talking about "can I detect the over intensity".

Here is a very interresting post (in French, but Google Translate can help). The guy use and Arduino to control a step motor using to open a fence. And he wants to detect when the motor need more effort:

http://forums.futura-sciences.com/electronique/687244-lecture-de-lintensite-dun-moteur-un-arduino.html

Here the text from this site, I translated:

> **QUESTION**
>
> Hello everyone, I have a DC motor powered at 30 V. In normal operation, it consumes 2.5A (the power supply is OK, no problem on that side). It is an electric gate motor (sliding gate). I want to control it with an arduino. So far, not too much trouble, I go through a MOSFET (for the moment, I do not run the engine in one direction, later, I will make a bridge in H to go both ways). All this works well but I would also be able to detect when the engine forces (to stop it). When the motor forces, it consumes more, so more intensity in the circuit. The problem is that an Arduino can not read an intensity, I can only read a voltage between 0 and + 5V. So I was thinking of putting a resistor in series with the motor and measuring the voltage across the resistor with the arduino. If I take a max intensity not to exceed 5 A, Ohm's law gives me a resistance of 1 Ohm to have a voltage of + 5V (I'm good?) The problem is that a resistance of 1 Ohm at 5A will dissipate 25W (R x I x I, I'm always good?). How to solve this power dissipation problem? the big resistors I have at the moment are 3/4 W, they will not take long
>
> My problem is the following: if I take a smaller resistance to have a smaller power (like 0.1 Ohm or less), the voltage has its limits will be too low to be read by my arduino,
>
> How to do ? Does anyone have an idea?
>
> Thank you in advance for your answers.
>
> Steph.
>
> **ANSWER 1** Just amplify the signal: rail-to-rail operational amplifier (to power it with a single positive voltage), a non-inverting device with a gain of 10 for example.
>
> **ANSWER 2** Indeed, it's an idea. So I was thinking of putting a resistor in series with the motor and measuring the voltage across the resistor with the arduino. . The risk of this type of assembly is: \- the maximum voltage overshoot (5V) at the input of the uC (ARDUINO) at the change of direction (see ground point). \- the maximum voltage surge (5V) at the input of the uC (ARDUINO) in the event of a break in the resistance. Explanations: The ARDUINO board must have a common point (Ground) and an Ax input, therefore when changing polarity (change of direction of the motor) the DDP is no longer 0V-\> 5V but 0V-\> 30V and there it smokes, ditto in case of rupture of this resistance. The good solution in my opinion would be a system like http://www.gotronic.fr/cat-courant-1125.htm Regards

The answer 2 give link to products like the i-Snail-VC: Current Transducer with 0-5VDC Output. Can be linked directly to the PIN of an Arduino.

# Answer
> 0 votes
Yes, most certainly. Use an ammeter to detect the "effort" required to actuate the motor. Both hall-effect and series measurements are acceptable here. Make sure to sample and average because motors can cause huge current spike (both positive and negative) which confuse naive readings. If your averages are climbing, as they eventually should, you know that it's getting harder to do the work. The hard part is deciding how hard is "too hard", and that depends on a lot of factors you're in the best position of judging.

# Answer
> 0 votes
A few ways, assuming that it is a DC motor.

1. Measure the current through the motor: current is proportional to torque, everything else being equal.
2. Put a strain gauge on the axle.
3. Put a frictional plate on the axle.

...

Or to completely abandon the idea and control the movement via a position sensor.

---
Tags: motor, stepper
---


# Question
Title: Arduino is not recognized by any computer
I have an Arduino Uno R3 and when I plug it into any computer, the computer doesn't recognize the Arduino. I checked up and the LEDs are working fine and when I open the device manager it doesn't show any `Unkown Device`.

What it could be? Could the ATMega be dead? I tried on two Windows 7 and one Linux machines, none recognized the Arduino.

# Answer
> 3 votes
The reason that it is not connecting can be anything from wrong driver installation to the dead Atmega 16u2 chip. But I must exclude the former option as you said you'd tried on different OS and different computers. So double check the driver installation. And if does not work try to find out whether Atmega16u2 is fried or not. One solution might be to reflash the original firmware through an external ICSP programmer. If don't have any programmer but another arduino uno you might try out the gamon's tutorial on flashing firmware on the little USB to serial interface chip. Anyway if your arduino is new and official you can get the right support online on arduino.cc. but if it is a clone you may try to contact the reseller whom you bought from.

# Answer
> 0 votes
I had the same problem. When I connected the board to PC the ON Green LED turned on and the arduino run the last code was uploaded but the board wasn't recognized. Changing the cable fixed this problem for me.

# Answer
> 0 votes
If your arduino runs the last uploaded sketch, the problem is with the ATMega16U2 chip in your Arduino. Try to update the firmware with this tutorial https://www.arduino.cc/en/Hacking/DFUProgramming8U2

If you can't update the 16U2 firmware don't throw away, you can program the Arduino with a ISP programmer like this https://www.pololu.com/product/1300

---
Tags: arduino-uno
---


title: Reset Arduino Uno R3

text:
# Question
Title: Reset Arduino Uno R3
I have an Arduino Uno R3 board and I compiled a test code. But now I'm trying to delete it. There are many tutorials with the same way, that is rewrite BLANK CODE. But it's not the genuine way. I want to delete all code that I manually compiled. Because the previous code will also take space in memory and after some time memory will be full. Is there anyone who has the right solution for this problem? Thanks in advance.

# Answer
Every time you rewrite an Arduino, the previous code is completely wiped out (except for the bootloader, which doesn't change).

You will not fill up your arduino -- it is not like a filesystem where you are continually adding new files. Each new programming/upload overwrites all the existing code.

Uploading a blank sketch is the genuine way to "erase" an unwanted program from an arduino.
> 4 votes

# Answer
When you upload a new sketch the flash memory (Arduino hard disk) is deleted completely and the new sketch is loaded.

If you want a blank code, just upload:

```
void setup() {
}

void loop() {
}

```
> 0 votes

---
Tags: arduino-uno, reset, genuine
---


# Question
Title: Programming Arduino with FTDI via Tx and Rx pins
How program Arduino with a FTDI cable/breakout\_board via pins 0 (Rx) and 1 (Tx)?

In case the USB to UART chip (16U2 or other) is broken, you can program Arduino with a FTDI instead of 16U2 or other chip.

What are the connections to reset the Arduino microcontroller automatically when sketch is upload?

# Answer
> 0 votes
It's exactly the same as for a breadboard Arduino. That is, connect the DTR pin of your breakout board through a 0.1uF capacitor to the RESET pin. TX and RX then connect to the RX and TX pins of the Arduino respectively, along with of course the ground connection.

---
Tags: arduino-uno, arduino-mega, arduino-leonardo
---


# Question
Title: Button with switch timer and reset time function + LED feedback. What am I doing wrong?
Beginner here.

I´ve been trying to implement a button function timer working with millis() instead of delay as I want the button to be responsive while the timer is running.

So far I´ve managed to start the counter on the button´s state change and let it time out. Unfortunately all kind of strange behavior is coming out of my sketch and I am yet to understand why.

Help is appreciated.

**This is the desired behaviour of the timer:**

1. On startup the Arduino is ready to recieve a button push. The relay is off (HIGH).
2. Once the button is pushed:
• The relay state is changed to LOW in order to turn it on
• A green LED switches on.
• A millis() based timer is switched on.
3. If the user presses the button while the switch is on, the timer is reset to 0 and continues counting.
4. If the on-time is going to end, a red LED starts blinking. Say in the last minute.
5. As soon as the timer reaches the specified on-time:
• The green LED switches off
• The relay switches off • The system returns to step 1. and is awaiting a push.

In my code example the red blinking Led is not implemented yet. The following code switches the switch and the green LED on but does not switch them off anymore.

```
//CONSTANTS

#define BUTTON_PIN        2  // Button
int in1 = 7;
int greenLED = 4;
int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

//MILLIS
unsigned long previousMillis = 0;
const long interval = 10000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // compare the buttonState to its previous state
    if (buttonState != lastButtonState) {

        buttonState = digitalRead(BUTTON_PIN);

        if (currentMillis - previousMillis < interval){
        //SWITCH ON, LED ON
          digitalWrite(in1, LOW);
          digitalWrite(greenLED, HIGH);
        }

        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
        }

        // Delay a little bit to avoid bouncing
        delay(50);

        // Reset buttonState:
        lastButtonState = buttonState;
   }
}

```

# Answer
> 3 votes
Written and tested. I also included the red blinking led.

```
//CONSTANTS

const int BUTTON_PIN = 2; // Button
const int in1 = 7;
const int greenLED = 4;
const int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
bool relayOn = false;

//MILLIS
unsigned long previousMillis = 0;
const unsigned long interval = 10000;
const unsigned long redLedInterval = 2000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // if button is pressed, turn relay on (if it wasn't already on), and reset the timer
    if( buttonState==LOW ) // no need to check for previous state, in this specific case
    {
        previousMillis = currentMillis;
        digitalWrite(in1, LOW);
        digitalWrite(greenLED, HIGH);
        digitalWrite(redLED, LOW);
        relayOn = true;
    }

    // if relay is currently on...
    if( relayOn )
    {
        // turn red led on, if close to turning off the relay
        if (currentMillis - previousMillis >= interval-redLedInterval )
            digitalWrite(redLED, (millis()/300)%2);//blink red led; 300ms on; 300ms off

        // if enough time has elapsed, turn of the relay
        if (currentMillis - previousMillis >= interval)
        {
            // .. turn of relay
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
            digitalWrite(redLED, LOW);
            relayOn = false;
        }
    }
}

```

Added advantage here is that the timer will never run out if the button is keep being pressed down.

---
Tags: arduino-nano, timers, button, millis, switch
---


# Question
Title: Not long tweets published using ESP8266-01 with Arduino UNO
I'm trying to create a setup with which an Arduino UNO sends out a tweet (one random quote) every time a button is pressed. I want to use it as a Mailbox Watcher.

I'm not new to Arduino but ESP8266 is all new to me, so I'm trying to figure things out from how-to articles, youtube videos, etc.

My current setup is an ESP8266-01 attached to an Arduino UNO and I adapted the code found here (link) to my needs. I ended up with something that resembles this:

```
#include <SoftwareSerial.h>
#include <Bounce.h>

#define DEBUG true

#define APIKEY "THING_SPEAK_KEY" //  api key ThingSpeak
#define TARGET_IP "184.106.153.149"///         //local  direccion IP o Hosting  ThingSpeak
#define TARGET_PORT "80"          ///  port 80
#define ID "WIFI_NAME"  //name of wireless access point to connect to
#define PASS "WIFI_PASSWORD"  //wifi password

#define BUTTON_PIN 8

#define RX_PIN 10
#define TX_PIN 11

SoftwareSerial esp8266(RX_PIN,TX_PIN);

Bounce button=Bounce(BUTTON_PIN, 5);

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

    pinMode(BUTTON_PIN, INPUT);

    initializeModem();

    Serial.println("ready player One");
 }

void initializeModem(){

     sendData("AT+RST\r\n",1000,DEBUG); //

     sendData("AT+CWMODE=1\r\n",1000,DEBUG); //

      String cmd="AT+CWJAP=\"";
      cmd+=ID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
     sendData( cmd+"\r\n",1000,DEBUG); //

     sendData("AT+CIPMUX=0\r\n",1000,DEBUG);

  }

boolean buttonState(){

  if (button.update() && button.read()==HIGH){

      return true;

    }else {
      return false;
      }
  }

void loop() {

if (buttonState()) {

   //  String con tweet
   String  updateTwitterStatus = "The best and most beautiful things in the world cannot be seen or even touched - they must be felt with the heart. Helen Keller #quoteoftheday";
   Serial.println(updateTwitterStatus);

    String webpage = "AT+CIPSTART=\"TCP\",\"";
    webpage += TARGET_IP;
    webpage += "\",80\r\n";
    sendData(webpage,1000,DEBUG);

    // Create HTTP POST Data

    String tsData = "api_key=" APIKEY "&status=" + updateTwitterStatus ;

    String webpage1 = "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n";
    webpage1+="Host: api.thingspeak.com\n";
    webpage1+="Connection: close\n";
    webpage1+="Content-Type: application/x-www-form-urlencoded\n";
    webpage1+="Content-Length: ";
    webpage1+=tsData.length();
    webpage1+="\n\n";
    webpage1+=tsData;

     //// envia   comando AT + cantidad de caracteres

     String cipsend = "AT+CIPSEND=";
     cipsend+= webpage1.length();
     cipsend+="\r\n";

     sendData(cipsend,1000,DEBUG);
     sendData(webpage1,1000,DEBUG);

      //// comando AT de cierre de conexion
     sendData("AT+CIPCLOSE=0\r\n",1500,DEBUG);

              /// DELAY para reenvio de datos a twitter
     delay(10000);  //3 seg
}

}

 //// rutina de depuracion via puerto serial

String sendData(String command, const int timeout, boolean debug) {
    String response = "";

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

    long int time = millis();

    while( (time+timeout) > millis()) {
      while(esp8266.available()) {
        // 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 setup works more or less as expected. It connects ok to the WiFi and so on, but it is only able to publish a tweet if it is not very long. As example, the quote on this example code will no be published whereas if it is half as long, it will be no problem.

In the end, I want to clean up the code and make use of private libraries to tidy things up and leave as few lines of codes as possible on the .ino file, but for testing and debugging purposes, I'm working on the code above.

I realize that a short text should be sufficient for my needs, but the fact of knowing that something is off bothers me to great extend. I have been dealing with this for three long days, so if anyone has an idea it would be much appreciated...

Thanks in advance

EDIT: It seems as the longest tweet I can send is 108 characters long. Together with the AT code to sent it, tha serial monitor gives the following feedback:

AT+CIPSEND=302

# Answer
> 1 votes
It's plausible and likely that you are running out of RAM on the Uno by making extensive use of the `String` object and it's concatenation function (overloaded + operator).

Every time you `+` a `String` object, a new block of RAM is allocated to hold the new string, and that RAM is nearer the "ceiling" of RAM than the previous block. The old blocks are de-allocated, but since they are smaller than the new one, they can't be re-used for new allocations of your continually-larger `String`, so you eventually run out of contiguous blocks of RAM into which to put your new, longer `String` object.

One solution here, and pretty much everywhere on an Arduino, is to avoid using the `String` object, and go with the classic C string handling routines.

I would allocate one buffer char array `char buf[512]` or whatever you compute your maximum desired total string length to ever be. Then use `strncat()` to repeatedly concatenate your other parts into that one buffer.

Also consider putting static strings in PROGMEM as described at https://www.arduino.cc/reference/en/language/variables/utilities/progmem/, so you won't be holding all static strings in RAM the whole time, but can copy each as you use it to working RAM as you build up your HTTP request string.

The real killer is `+=` used repeatedly with a `String` object. Arduino Uno has only 2k of RAM.

---
Tags: arduino-uno, serial, esp8266, wifi, softwareserial
---


# Question
Title: How to program ESP8266 with Arduino Uno pins 0 and 1?
I know that I can connect an ESP8266 with an Arduino Uno at pins 0 and 1, which is Rx and Tx, and enter commands manually in the serial monitor the commands to test it.

I had tried to use software serial and altserial to connect an ESP8266 to other pins, but it was error prone at sometimes.

My question is that how to use an automated program to control an ESP8266 when I connect the ESP8266 with an Arduino Uno at pins 0 and 1.

Sample code would be helpful.

Edit: I have added a simple program to blink led when it get response but it is not working. could you look at it too?

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  delay(3000);
  pinMode(12,OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(12,LOW);
  delay(2000);
  Serial.println("AT");
  if(Serial.available())
  {
    digitalWrite(12,HIGH);

    while(Serial.available())
    {
      char c=Serial.read();
    }

    delay(2000);
  }

}

```

# Answer
> 2 votes
The problem with using pins 0 and 1 is that they are also used to communicate with the PC for both serial monitoring *and* programming.

If you attach an ESP8266 to pins 0 and 1 chances are you will fail when uploading a new sketch - you will have to disconnect the ESP8266 every time you need to upload a new sketch - that is why most people use SoftwareSerial.

Also if you are using pins 0 and 1 for the ESP8266 you cannot then also use the serial monitor to see what is going on with your program and thus be able to debug it when it's not working.

If you're OK with both those caveats then by all means go ahead and use pins 0 and 1. You use it in exactly the same way as using SoftwareSerial but you don't need to define an object first - you just use the pre-defined Serial object.

One important thing to remember with the ESP8266 is that the default firmware's AT command interface is ropey as hell. It's most likely that which is tripping you up not your SoftwareSerial. You have to get the timing right with it from what I remember - always impose a 1 second delay after sending each command - it's the delay that terminates the command, not a carriage return (although I think a CR is also needed). Maybe later versions have been improved since, but that's one really good reason to directly program the ESP8266 and implement your own protocol for communicating. My ICSC library is a good candidate for communicating between the two - it runs on both the ESP8266 and the Arduino.

# Answer
> 0 votes
You need to use Arduino IDE serial Monitor Window for ESP8266 setup instead of using TTL or Serial Converters. I successfully Setup My ESP8266 Module by using just Arduino Nano and Arduino IDE Serial Monitor.

```
    #include <SoftwareSerial.h>
SoftwareSerial softSerial(3, 2); // RX, TX

void setup()
{
  uint32_t baud = 9600;
  Serial.begin(baud);
  softSerial.begin(baud);
  Serial.print("SETUP!! @");
  Serial.println(baud);
}

void loop()
{
    while(softSerial.available() > 0)
    {
      char a = softSerial.read();
      if(a == '\0')
        continue;
      if(a != '\r' && a != '\n' && (a < 32))
        continue;
      Serial.print(a);
    }

    while(Serial.available() > 0)
    {
      char a = Serial.read();
      Serial.write(a);
      softSerial.write(a);
    }
}

```

Necessary AT Commands

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


title: HTTPS with ESP8266WebServer?

text:
# Question
Title: HTTPS with ESP8266WebServer?
I see many ESP8266HTTPClient examples, pasting in a fingerprint from an outside website, but I want to *host* an html page from the ESP8266 in AP mode using HTTPS.

Judging by the lack of examples, and the lack of a domain for a cert in AP mode, I'm thinking this is impossible, but would like confirmation before I give up.

Is it impossible to get the browser's green padlock on an AP-served web page?

# Answer
> 0 votes
The ESP8266 just doesn't have sufficient CPU power to do this reliably.

It is possible, since the EPS8266 SDK docs have an "SSL User Manual" which describes this scenario.

In my experience, using the Arduino core for ESP8266, it doesn't work reliably.

Consider using an `nginx` reverse-proxy and having that proxy handle SSL negotiation. Understand that this is more for situations where the ESP8266 is local, in a network sense, to the nginx proxy, and you consider your WLAN secure enough.

On the plus side, you have room to grow in key sizes and/or complexity.

---
Tags: esp8266, web-server, http
---


# Question
Title: Stuck in While loop when case is activated. Arduino
I have an arduino uno that controls a light using an ir remote. The sketch works fine until I pressed button c which is case 0x10EF58A7. This case reads in values and dims the light accordingly but the only problem is i can not exit the case when another button on the ir remote is pressed! what should i do!?

```
#include <SoftwareSerial.h>

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#include <TimerOne.h>

int RECV_PIN = 13;

IRrecv irrecv(RECV_PIN);
decode_results results;
volatile int i=0;               // Variable to use as a counter
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin = 7;
int dim2 = 0;                   // led control
int dim = 128;                  // Dimming level (0-128)  0 = on, 128 = 0ff
int pas = 8;                   // step for count;

int freqStep = 65;
char incomingByte;

void setup() {
  Serial.begin(9600);
  // initialize the digital pin as an output.
  pinMode(RECV_PIN, INPUT);
  pinMode(AC_pin, OUTPUT);
  irrecv.enableIRIn(); // Start the receiver
  attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
  pinMode(AC_pin, OUTPUT);
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  // Use the TimerOne Library to attach an interrupt
}

void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);
}

// Turn on the TRIAC at the appropriate time
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(AC_pin, HIGH);  // turn on light
      i=0;  // reset time step counter
      zero_cross=false;    // reset zero cross detection
    }
    else {
      i++;  // increment time step counter
    }
  }
}

 void translateIR() // takes action based on IR code received
{

  switch(results.value){

  case 0x10EFD827:
  //power button
   dim = 00;
    Serial.println(" full brightness ");
    break;
  case 0x10EF20DF:
  //circle button
  dim = 128;
    Serial.println("off   ");
    break;
  case 0x10EFF807:
  // button A
  dim = 95;
    Serial.println(" dim level 1   ");
    break;

   case 0x10EF7887:
   //button B
   dim = 50;
    Serial.println("dim level 2     ");
    break;

 case 0x10EF58A7:
 // button C
 {
  while ( Serial.available() > 0) {
 unsigned int num = Serial.parseInt();
 num = map(num, 0, 255, 0, 128);
 unsigned int num1 = map(num, 0, 128, 128, 0);
// num1 = constrain( num1, 0,128);
 dim = num1 ;
   Serial.print(" auto   ");
   Serial.println(dim);

   delay(800);
   Serial.flush();
    //break;
   }
  break;
}
 break;

  case 0x10EF10EF:
//button left
    {
    if (dim<127)
   {
    dim = dim + pas;
    if (dim>127)
    {
     dim=128;
    }
    }
    }
    Serial.print(" dimming ammount=   " );
    Serial.println(dim);
    break;

  case 0x10EF807F:

  //button right
   {
      {
  if (dim>5)
  {
     dim = dim - pas;
  if (dim<0)
    {
      dim=0;  // in vechiul sketch era 1
    }
   }
   }
   }
     Serial.print(" dimming ammount=   ");
      Serial.println(dim);
    break;

   default:
    //Serial.print(" unknown button   ");
    //Serial.println(results.value, HEX);
{}
  }

}

void loop(){
  int i=0;
   if (irrecv.decode(&results)) {

   translateIR();
        irrecv.resume(); // Receive the next value

   }
     delay(700);
 }

```

# Answer
> 1 votes
The problem is that calling `Serial.parseInt()` does not remove data from the buffer. So, `Serial.available()` will not decrease in your case, but increase with every input you give. You will need to call `Serial.read()` and **then** convert the received bytes to a number.

@Majenko generally you're right, but it's okay to use a while loop in this situation. If there is data in the buffer, this data has to be handled. And as the arduino is not capable of multitasking it will need to take the required time, no matter if in the main loop or in a subfunction.

# Answer
> 0 votes
You shouldn't have while loops in your switch/case like that.

In fact, you shouldn't really have while loops at all.

Instead, your case should just set a "state" variable which tells the rest of your `loop()` function how to handle any serial data that arrives.

# Answer
> 0 votes
Don't use the while loop, set a boolean when the C has been pressed.

Within the loop (main loop, not the while loop within the C key check), check if the boolean is set, and if so, check if there is serial input. If so, handle it, e.g. after or before checking all keys in the switch statement. This way alternatively keys are checked and serial input is handled.

There are good reasons not to use a while loop:

* A while loop makes it impossible to do other tasks 'more or less' simultaneously.
* A while loop can never end, meaning the device stops responding/functioning.
* A while loop which takes too much time can affect the timing of other parts of your sketch.

IF you need a while loop, think twice, after thinking you need one, make sure it always ends within the condition or with a break

---
Tags: arduino-uno
---


title: Random(0,2) gives bad results

text:
# Question
Title: Random(0,2) gives bad results
All I need to do is generate a random integer between 0 and 3 for example. I am using this function:

```
void Crossover(int parents[2][3])
{
  int ranDpart;
  int ranDparent;
  for(int i=0; i<10; i++)
  {
    for(int j=0; i<3; j++)
    {
      ranDpart = random(0,3);
      ranDparent = random(0,2);
      newGen[i][j] = parents[ranDparent][ranDpart];
    }
  }
}

```

where as you see parents is input with size of 2x3 and `newGen` is 10x3 2D array. As seen here in the code, this function is supposed to randomly take one of parent and a part of this parent to make a new "child". Am I doing something wrong? I think that random gives me bad results. I tried some online compiler and random gives me numbers like "`1804289383`" even if I tried to make it long. Can you guys help me with random `int`?

# Answer
stdlib.h defines a few psuedo-random number functions. I am not familiar with a *random* function taking two arguments, presumably the low and high end of the desired range, that you've specified in your code.

For what it's worth, in plain old C use the modulo operator to achieve the range you want using stdlib's srand and rand functions:

```
/* seed psuedo-random number generator during setup with something */
srand(0xdeadbeef);

```

and in your function simply use modulus to get your range:

```
int ranDpart = rand() % 3; /* range: 0,1,2 */
int ranDparent = rand() % 2; /* range: 0,1 */

```

If your ranges should be inclusive e.g. \[0,3\] and \[0,2\] then

```
int ranDpart = rand() % 4; /* 0,1,2,3 */
int ranDparent = rand() % 3; /* 0,1,2 */

```
> 2 votes

# Answer
Unfortunatly, "real random" value don't really exist in computer. If you just call a random function many time, you'll get (in many cases) same result. For that, before calling a random generator, you have to set a "seed". The example here: https://www.arduino.cc/reference/en/language/functions/random-numbers/random/ give a solution, using:

```
 randomSeed(analogRead(0));

```

If the PIN 0 (used in this example) is not connected, you'll get some "noise" on it and this will create the seed for your random function.
> 0 votes

# Answer
The random(a,b) function does work. If it doesn't there is something else going on. You mention the program is long. A couple of things to remember when programming Arduinos is that

1. In C there is no boundary checking, so when an array is indexed out of range unexpected behavior or crashes occur.
2. Arduinos have very little RAM. The UNO only has 2K. Part of that is used for the stack. When memory runs low the stack can overwrite program variables and again create unexpected results or crashes e.g. endless reboots.

There are some functions that return the amount of free RAM available at run time, use those with Serial.print() for debugging. There are some freeRam() functions here, the last one works well for me (with UNO)
> 0 votes

---
Tags: arduino-uno
---


title: Arduino Yun external antenna

text:
# Question
Title: Arduino Yun external antenna
Can someone help me understand how the external antenna IPX connector actually stays connected to the Yun? Do I have to "force" it in so it snaps in? I've been somewhat gentle with it in fear I'll break something. However when I get close to getting it in, it just pops back out.

I've never worked with an IPX connector before, and I'm trying to not break anything.

EDIT: I may have figured this out. Looks like the socket on the Yun is an IPEX socket, which is female. The cable I have is an IPX/uFL/u.FL connector, which also appears to be female.

It looks like I need to use an MCX cable adapter as found here: http://www.adafruit.com/products/1532 If someone could confirm this for me, that'd be great.

Here's a picture of the cable I purchased and my Yun.

# Answer
> 4 votes
There's a discussion on the Arduino Forum about this:

Mystery component on Yun board?

From what I read it's only for testing purposes.

> the connector is a MM8430-2610 (see this). You can plug in a MXGS83RK3000/MM126036: once plugged in, the switch connector will turn the internal antenna off and use the probe as an external antenna

# Answer
> 1 votes
Testing with my Yún, it took quite a bit of force to install the connector. I had to use pliers to get extra leverage, but it eventually snapped in place.

# Answer
> 1 votes
I went through this last night. I got the adapter cable \[ .../852\] and antenna from Adafruit. It appeared to be hard to snap into place, but it did go.
**It did not improve performance** though when testing signal strength with the Example\>Bridge\>WiFiStatus

Which leads me to believe that the connector didn't mate -or- I damaged it -or- it isn't the proper connector. I am thinking the latter is the case. Still looking for the answer.

Jim

I bought: 1 ea. RP-SMA to uFL/u.FL/IPX/IPEX RF Adapter Cable $3.95 http://www.adafruit.com/products/852 1 ea. 2.4GHz Dipole Swivel Antenna with RP-SMA - 5dBi $8.95 http://www.adafruit.com/products/945

# Answer
> 0 votes
I have several old mini-pci mini-pcie wifi cards laying around and the poster is correct: for some reason, they put the female end on the board whereas any wifi antenna you pull from a laptop, the cable will be female; all of my cards are the male version of the port on the YUN.

I can actually snap my old wifi cards onto the YUN's antenna port and they snap together perfectly just like the cable does in the laptops they belong.

For hobbyists, an old laptop wifi antennas are something we all have.

Why they did this I don't know.

# Answer
> 0 votes
@Jim was very close, the /851 part is the female to work with that connector. I have an adafruit Flora GPS with the same thing, a male connector on the board. I asked Adafruit for the adapter lead for it and they said the SMA to uFL #851 was what I needed. I just tried it on my shield and it fits.

---
Tags: arduino-yun, wifi
---


# Question
Title: I have a diagram of my Arduino circuit. How do get it ready for PCB manufacture?
For my engineering class, I am building a digital scale. My team has assembled the prototype out of:

* Arduino Uno
* Hx711 amplifier module
* 1 kg load cell
* 2 push buttons
* A 4 digit 7-segment display module we found online, but we don't know its specific name
* HC-05 Bluetooth module, no specific manufacturer
* Lilypad switch CR2032 battery module
* DC-DC step up to 5V boost converter module

Our prototype works. Well, sort of (we're still trying to work out the boost converter and c2032 to work). We have diagrammed how each module connects to each other on a piece of paper. However, we want to properly diagram this in a way so we can create a PCB for it.

I have tried the Eagle and Fritzing programs. I am very inexperienced with them. I am not able to find the HC-05 and LED display .sch or .fzz files online for this, so I have came to a halt. I am not sure how each of these modules are actually wired together either.

What can I do next?

# Answer
You can find the parts on fritzing.org. Anyway. You can get rid of some parts and save money if you pick the right ones. Instead of an Arduino Uno take an Arduino Pro Mini with 3.3V and HC-05 without a breakout for 5V Arduinos.

Doing that everything will smaller and running on 3.3V thus getting rid of the DC-DC converter.
> 0 votes

# Answer
You can try to implement the circuit without an Arduino board on a breadboard. So you can get more information about what works and what not. From there after making necessary changes (if there is any), you can draw the schematics and create a PCB layout using Orcad, Eagle etc.There are a lot of tutorials out there about PCB designing.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno + MSD-11-EM stepdriver + NEMA 17
I am working on Arduino code for stepper motor rotations control. I want to rotate a stepper for only 4 rotations.

The code is working fine but that will run only once as I have put that in `setup()`.

I want to know if there will be any reverse current flowing in the circuit that would damage the Arduino or stepper. What if I want to run the stepper in the `loop()`? I tried but that will force the stepper to run continuously.

How can I run stepper for only 4 rotations and then stop?

I want to run it in `loop()`.

Below is the code I am using:

```
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(110);
  // initialize the serial port:
  Serial.begin(9600);
  for(int i=0;i<25;i++) {
    Serial.println("Anti-clockwise");
    myStepper.step(stepsPerRevolution);
    delay(50);
  }
}

```

# Answer
In loop add flag to change after what you desired plus a statement to check the flag.
Code below (assuming what is in for() being enough to do 4 revolutions):

```
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
bool flag = true;

void setup() {
 // set the speed at 60 rpm:
 myStepper.setSpeed(110);
 // initialize the serial port:
 Serial.begin(9600);
}

void loop {
 if (flag) {
   for(int i=0;i<25;i++) {
     Serial.println("Anti-clockwise");
     myStepper.step(stepsPerRevolution);
     delay(50);
   }
   flag = false;
 }
}

```

This solution gives you a flexibility to add a pushbutton to change flag and do another 4 revolutions.
> 2 votes

# Answer
I still wonder how code which I have posted earlier worked but no worries code below is working as expected.

```
int dirpin_T1 = 7;
int dirH_T1 = 8;
int steppin_T1 = 9;
void setup() {
  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);
}

void loop() {
  static int count = 0;
  if(count < 4) {
    count++;
    digitalWrite(dirpin_T1, LOW); // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);
    for (int i = 0; i<3193; i++) {
      // Iterate for 4000 microsteps.(32767)
      digitalWrite(steppin_T1, LOW);
      // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH);
      // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(500);
    }
  }
}

```
> 2 votes

# Answer
I can't validate what you are doing in the `for` statement, but if you want to execute that only 4 times, this sketch will do

```
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup()
{
    // set the speed at 60 rpm:
    myStepper.setSpeed(110);
// initialize the serial port:
    Serial.begin(9600);
}

void loop() {
    static int count = 0;

    if(count < 4)
    {
        count++;

        for(int i=0; i<25; i++) {
            Serial.println("Anti-clockwise");
            myStepper.step(stepsPerRevolution);
            delay(50);
        }
    }
}

```

`count` keeps the count of how many times you execute the `for` loop. It's declared `static` to keep his value between `loop()` executions; otherwise, it will be zero on each `loop`
> 1 votes

---
Tags: arduino-uno, programming, stepper
---


# Question
Title: Is it right to connect Serial module directly?
I find a strange thing that the led is on when power is off. And it's the problem of my serial module. Arduino may get power from my serial module. My serial module use max2322. I don't if it will harm my arduino or has influence to my program. Is it needed to add a resistance?

# Answer
> 0 votes
Maybe the serial module has a serial cable attached to it which gives a voltage.

I think it can hurt, since you have two voltage sources, one from the Arduino and one from the Serial cable. Not using the power wire from the serial cable should fix the problem.

A resistor will not help because you still have two power sources in case you have both voltage from the Arduino (adapter/USB) and serial.

---
Tags: voltage-level, wireless, electronics
---


# Question
Title: Built-in LED turns on when I touch the input port
I'm a beginner. I bought a new Arduino and I uploaded the basic example button code.

```
const int buttonPin = 2;
const int ledPin =  13;
int buttonState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

```

But the problem is that when I touch port 2 the output is getting so I changed the port number 2 to 3 even though without any supply the output is getting on.

Give me some suggestion.

# Answer
When you are reading digital data through a pin you must make sure that you are steering that input pin to a stable state when no input is present. You can do this by using either a pullup or a pulldown resistor which you can connect externally or you can use the in built pullup. You can use a 10k ohm resistor to pulldown by connecting it to the button end where your digital pin is connected and the other to ground. By doing this your above code must work fine. I think by touching the pin you are actually pulling the voltage state down. Hope this helps
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How to drive a stepper motor, by having it go even steps forward and odd steps back?
I have a question about driving a stepper motor back and forward. Basically I want it to do a total of 24 steps (12 forward and 12 back) but I don't want to repeat the same steps when coming back.

So 2, 4, 6, 8, 10, 12 (step numbers) forward and 11, 9, 7, 5, 3, 1 (step numbers) backwards.

Here is the code I have at the moment and I just cannot get the motor to drive properly.

EDIT: It goes 6 times 2 steps forward, then 5 times backwards and after that it starts to just jerk around. What I want it to do is to go 6 times 2 steps forward (so step 2, step 4, step 6, step 8, step 10, 12) and then come back but fill in the odd steps (step 11, step 9, step 7, step 5, step 3, step 1 and step 0). The idea is that then it doesn't just overlap when going forwards and backwards.

```
#include <Stepper.h>
#include <TimerOne.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
int backwardsCount = 0;
int stepCount = 0;

void setup() {
  Serial.begin(9600);
  Timer1.initialize(2000);
  Timer1.attachInterrupt(callback);
}

void callback(){
  if(stepCount < 12) {
    myStepper.step(2);
    stepCount += 2;
  } else if(stepCount == 12) {
    myStepper.step(-1);
    backwardsCount = 11;
    stepCount += 1;
  }
  if(backwardsCount > 1) {
    myStepper.step(-2);
    backwardsCount -= 2;
  } else if(backwardsCount == 1) {
    myStepper.step(-1);
    stepCount = 0;
    backwardsCount = 0;
  }
}

void loop() {
}

```

# Answer
Ok, I tried to fix a couple of things from your code.

First of all I implemented a small state machine with two states: going forwards and going backwards. Normally you advance by 2 steps, but when you switch state you go directly to 0 or 11. In my opinion this is the most correct way to handle this problem.

Then I modified the way you trigger a movement. I totally dislike interrupts, specifically when not needed like in this case (at least in my opinion). I used the usual approach with `millis()`. Please note, however, that I had to put 2 milliseconds as period, but I think this was a mistake from your side (I think you wanted 2 seconds). If this is the case, write `const uint16_t moveStepMs = 2000;` instead of `const uint16_t moveStepMs = 2;`. If you want to keep the 2ms, please be aware that `2ms * 6 = 12ms`, so it will go back and forth in about 25ms. This means it is too fast for you to see anything (and probably also for the motor to move).

Here is the code. I hope it is clear; I tested it online, but there wasn't a stepper in the simulator so I just used some LEDs (I think it works, anyway).

```
#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);

const byte State_MovingForw = 1;
const byte State_MovingBack = 2;

byte currentState;
int8_t position; // Note: max 127 for position

const uint16_t moveStepMs = 2;
unsigned long prevMillis;

void setup() {
    Serial.begin(9600);
    prevMillis = millis() - moveStepMs;
    currentState = 0; // Invalid, so it will trigger a change
}

void executeStep(int8_t numOfSteps)
{
    myStepper.step(numOfSteps);
    position += numOfSteps;
}

void loop() {
    if ((millis() - prevMillis) > moveStepMs)
    {
        prevMillis += moveStepMs;
        byte nextState = currentState;

        // Check for a state change
        switch (currentState)
        {
        case State_MovingForw:
            if (position >= 12)
                nextState = State_MovingBack;
            break;
        case State_MovingBack:
            if (position <= 1)
                nextState = State_MovingForw;
            break;
        default:
            nextState = State_MovingForw;
        }

        if (nextState != currentState)
        {
            // Exit condition: what to do when exiting from one state
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(0 - position); // Reset position to 0
                break;
            case State_MovingBack:
                executeStep(11 - position); // Reset position to 11
                break;
            }

            // Advance to next state
            currentState = nextState;
        }
        else
        {
            // no state change (so move to the next value)
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(2); // Move two steps forwards
                break;
            case State_MovingBack:
                executeStep(-2); // Move two steps backwards
                break;
            }
        }
    }
}

```
> 1 votes

---
Tags: motor, stepper
---


# Question
Title: Problem with a DHT11 Temperature & Humidity sensor
I'm new in the Arduino world and today i was trying to make a simple program to show the temparature an humidity with this sensor. I made a circuit following one tutorial and nothing happend, **the result was Temperature: 0 Humidity: 0.** My question is, what is wrong? Probably the sensor is broken or the code is wrong. *I also need to say that i use a 5K1 resistor in exchange of the 4.7K resistor and accidentally I connected the sensor without the resistance for a few seconds.*

**This is the code:**

```
#include <DHT.h>
#include <DHT_U.h>

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

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

void loop() {
TEMPERATURE = dht.readTemperature();
HUMIDITY = dht.readHumidity();
Serial.print("Temperature: ");
Serial.print(TEMPERATURE);
Serial.print(" Humidity: ");
Serial.println(HUMIDITY);
delay(1000);
}

```

**This is the circuit scheme:**

**This is a photo of the circuit and the sensor (probably damaged):**

***Thanks for your time and sorry for my bad english.***

# Answer
Finally I was able to solve the problem by **not using the resistor** and connecting it directly, I also had a problem with the sensor pins since some were badly connected, but it was also solved. **Now both sensors are working well** including the melted one. ***Thanks!***.
> 2 votes

---
Tags: sensors, temperature-sensor, code-review
---


# Question
Title: All the differences between Arduinos: Pro Mini & Pro Micro
I'd like to know the differences between these two boards: Arduino Pro Mini and Arduino Pro Micro.

Even if I've read this and this related post, it is not clear enough. I've always used the Arduino Uno or Leonardo and I'm a little bit scared of using these compact miniaturised boards.

I have seen so far those differences:

* The Micro doesn’t need the separate FTDI, while the Mini does
* The Micro takes more time to boot up due to USB device (keyboard/mouse) emulation (is more like a Leonardo than an Uno)
* They both have 5 V and 3.3 V versions
* The Mini has 2 more digital IO and 2 more analog Inputs (1 more PWM)
* The pinout is the same (a shield designed for the Pro Mini is OK also with Pro Micro)
* Micro is more expensive (IF you don't have already an FTDI cable).

So, what I care about most is the boot up time (because it could make debug harder) but other than that.. if I don't need the 2 more Digital IO and the 2 more Analog Inputs.. why buy one over the other?

And some more question: can I use the Mini boot loader inside the Micro to avoid the boot up time (if I do not need the keyboard/mouse emulation)?

Is the power consumption the same? Can I use the same battery?

Sorry if this is a silly question but I'm little bit confused.

# Answer
> 14 votes
It is more the differences between ATMega328P + FTDI (Pro Mini) vs ATMega32u4 (Pro Micro)

Apart from the minor pin differences, the peripherals for both MCUs are the same. The major difference is the ATMega32u4 has built in full-speed USB. This allows the board to function as a USB device by implementing the appropriate USB stack. E.g. it can act as a

* USB to serial converter (CDC device)
* Keyboard or mouse (HID device)
* USB hard drive (MSC device)
* MIDI controller
* and more...

The LUFA library from AVR devices can be used for this but means going outside of the Arduino IDE and compiling proper C code using the latest avr-gcc tools.

The Arduino core library has built-in support for the HID and CDC device profiles. The CDC profile is used for comms with the Leonardo, Micro, etc. while the HID profile is used for keyboard / mouse emulation.

The Leonardo / Micro boot loader implements a CDC profile for communications with the PC. This CDC profile uses Arduino vendor and product ids so unlike FTDI devices, requires an extra step to install an `*.inf` file on Windows.

You would have to recompile the Pro Mini bootloader for the Micro, but even then it would require an FTDI board as programming would need to be done via the TX and RX UART pins. If you we going to go to all that trouble you could just recompile the proper boot loader to have a shorter time out. Why is difference of 1 or 2 seconds in boot loader time important?

The ATMega32u4 uses more power than the ATMega328P.

# Answer
> 3 votes
Arduino Pro Mini
Pin Mapping

Arduino Micro
Pin Mapping

The Arduino page for the Arduino Pro Mini and the Arduino Micro.

**Microcontroller**
Arduino Pro Mini: ATmega328 (ATmega168 on older boards)
Arduino Micro: ATmega32U4

**Memory**
Both have 32KB of Flash and 1KB of EEPROM
The Arduino Pro Mini has 2KB of SRAM where as the Arduino Micro has 2.5KB

**Digital I/O**
The Arduino Pro Mini has 14 (of which 6 provide PWM output)
The Arduino Micro has 14 also (of which 7 provide PWM output)
Some of the analog pins can also be used as digital I/O

**Analog Inputs**
Arduino Pro Mini: 8 (some boards only break out 6 analog inputs)
Arduino Micro: 12 (6 dedicated and 6 from digital I/O pins)

**USB**
Arduino Pro Mini: Requires FTDI cable or Sparkfun breakout board to provide USB power and communication to the board.
Arduino Micro: Native USB

**Clock**
Both are 16 MHz (although the 3V Arduino Pros run at 8MHz)

**Power**
There are two version of each of the Arduinos. One runs at 3.3V and 8 MHz, the other at 5V and 16 MHz. Arduino Pro Mini: VRAW can accept voltage up to 12VDC.
Arduino Micro: USB or external supply of 6 to 20 volts (recommended range is 7 to 12 volts)

**Interrupts**
Arduino Pro Mini: The Atmega328 has 2 hardware interrupts available Arduino Micro: The ATMega32u4 has 5 hardware interrupts available
credit: Enric Blanco

# Answer
> 0 votes
In addition to what @geometrikal says (excellent answer, BTW) ATMega32u4 has 5 available true hardware interrupts (so-called "external"), whereas ATMega328p only has 2.

IMHO, that is a key advantage for some applications.

# Answer
> 0 votes
> So, what I care about most is the boot up time (because it could make debug harder)

still couldn't figure out the link between boot up time and debug.

> but other than that.. if I don't need the 2 more Digital IO and the 2 more Analog Inputs.. why buy one over the other?

sounds like there is no reason for you to the other board.

> And some more question: can I use the Mini boot loader inside the Micro to avoid the boot up time (if I do not need the keyboard/mouse emulation)?

the only way to avoid boo up time in anything, pro mini or pro micro, is to not boot it up. you cannot have boot up time if you don't boot it up.

As to the two boards, they use different avrs. the U4 has amazing analog features, but most pro micros don't route out AIN0/AIN1 - rendering them as the same as pro mini. that's a shame.

obviously, if you don't use those features, they have no value to you and cannot justify the premium / added complexity.

---
Tags: arduino-pro-mini, arduino-pro-micro
---


# Question
Title: "avr/io.h: No such file or directory" while compiling for board Generic STM32F103C series
I'm trying to compile FastLED library for my STM32F103C using Arduino 1.8.5 IDE, but getting this error:

```
In file included from C:\Program Files
(x86)\Arduino\libraries\FastLED/led_sysdefs.h:32:0,

                 from C:\Program Files
(x86)\Arduino\libraries\FastLED/FastLED.h:44,

                 from
C:\Projects\ioSmartHome\arduino\ColorPalette_stm32\ColorPalette_stm32.ino:1:

C:\Program Files
(x86)\Arduino\libraries\FastLED/platforms/avr/led_sysdefs_avr.h:12:20: fatal
error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board Generic STM32F103C series.

```

I just have no idea why it's trying to include this file which isn't existed for this platform. Any idea?

# Answer
> 2 votes
More specifically, for a variety of historical reasons, if FastLED can't determine the hardware platform/board being built for, it falls back to avr - and this particular STM chipset isn't directly supported in FastLED at the moment - there's a fork running around that has added support for it, but I haven't had a chance to pull it back into the main library.

# Answer
> 0 votes
`<avr/io.h>` is a header file used to interface the IO registers of the AVR micro-controllers. Most Arduinos are AVR-based, and some Arduino libraries assume an AVR core. This seems to bee the case with the FastLED library you are trying to use.

Your microcontroller, however, is an STM32, with an ARM core. It is not an AVR, and it will not work with code that assumes you have an AVR core.

---
Tags: arduino-ide, library
---


# Question
Title: Arduino JSON extract using ArduinoJSON Library
I'm having a problem extracting the Object/Array from this sample json `[
 {
 "sensor":"gps1",
 "time":1351824120
 },
 {
 "sensor":"gps1",
 "time":1351824120
 }
]`

Would anyone have some pointers or sample code to allow me to extract the 'time' from each of the objects ?

Thanks

# Answer
You can use the ArduinoJson Assistant on arduinojson.org to create a skeleton.

Here is what it generates in your case:

```
const size_t bufferSize = JSON_ARRAY_SIZE(2) + 2*JSON_OBJECT_SIZE(2) + 70;
DynamicJsonBuffer jsonBuffer(bufferSize);

const char* json = "[{\"sensor\":\"gps1\",\"time\":1351824120},{\"sensor\":\"gps1\",\"time\":1351824120}]";

JsonArray& root = jsonBuffer.parseArray(json);

const char* root_0_sensor = root[0]["sensor"]; // "gps1"
long root_0_time = root[0]["time"]; // 1351824120

const char* root_1_sensor = root[1]["sensor"]; // "gps1"
long root_1_time = root[1]["time"]; // 1351824120

```
> 1 votes

---
Tags: arduino-uno, json
---