# Question
Title: Arduino Mega 2560 + ESP8266 Problem with GET Request
I have an ESP8266 module connected to my Arduino Mega 2560. My goal is to send a GET request as below to the network:

```
api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295?tempData=cabbages

```

If that is successful, I will get the string "cabbages" along with the timestamp inside my Google Sheets. Note that I intend to change the string "cabbages" with many other data once this is working, but for now, just cabbages. Pasting the link above inside a web browser and pressing Enter seems work fine, but doing it automatically from inside Arduino with ESP8266 attached is somehow not as I expected.

After connecting to my home wifi I tried making a GET request to Google.com:

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

  delay(3000);
  Serial2.write("AT\r\n");
  delay(3000);
  Serial2.write("AT+CWMODE=1\r\n");
  delay(3000);
  Serial2.write("AT+CIPMUX=0\r\n");
  delay(3000);

  Serial2.write("AT+CIPSTART=\"TCP\",\"www.google.com\",80\r\n");
  delay(500);
  Serial2.write("AT+CIPSEND=80\r\n");
  delay(500);
  Serial2.write("GET / HTTP/1.0\r\n");
  delay(500);
  Serial2.write("User-Agent: curl/7.37.0\r\n");
  delay(500);
  Serial2.write("Host: www.google.com\r\n");
  delay(500);
  Serial2.write("Accept: */*\r\n\r\n\r\n");
}

void loop()
{
  if (Serial2.available()) {
    Serial.write(Serial2.read());
  }
  if (Serial.available()) {
    Serial2.write(Serial.read());
  }
}

```

And I get the response as follows, which is actually the Google home page:

```
AT
OK
AT+CWMODE=1
OK
AT+CIPMUX=0link is builded
Recv 80 bytes

SEND OK

+IPD,1410:HTTP/1.0 200 OK
Date: Fri, 23 Sep 2016 08:49:38 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Set-Cookie: NID=87=TS-mbT3JjN_vZQurH0M4e1tbNsgmSPF4ALY_ohGFUD6uz76RmbxY41AA_XtC75Wqxfcqu5v1lbLxy-tMa_yrn5-BHrxN7Hn6CeYVnEfG1bBsVd78Y6eHtJ0hOUQPIwaDM0_2wGPO52e7HQ; expires=Sat, 25-Mar-2017 08:49:38 GMT; path=/; domain=.google.com; HttpOnly
Accept-Ranges: none
Vary: Accept-Encoding

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script>(function(){window.google={kEI:'ouzkV5yUFcO10gTUwL6wDQ',kEXPI:'1351569,1351634,1351727,3700317,3700398,4029815,4031109,4032678,4036509,4036527,4038012,4039268,4041303,4041899,4043492,4045841,4048347,4052304,4061155,4062186,4063879,4064904,4065786,4066707,4067342,4067860,4068550
+IPD,1410:,4069148,4069694,4069838,4069840,4069906,4070123,4070329,4071229,4071604,4071842,4072288,4072364,4072409,4072602,4072653,4072774,4073405,4073418,4073728,4073874,4073959,4074684,4074801,4074807,4075966,4075974,4076018,4076072,4076095,4076121,4076543,4076930,4076999,4077002,4077219,4077221,4077298,4078430,4078456,4078547,4078553,4078635,4079082,4079105,4079281,4079356,4079388,4079417,4079423,4079649,4079730,4079842,4079999,4080215,4080218,8300273,8502184,8503585,8504110,8504846,8505150,8505152,8505836,8506251,8506255,8506763,8506951,8507045,10200083,13500017',authuser:0,kscs:'c9c918f0_24'};google.kHL='en';})();(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};google.https=function(){return"https:"==window.location.protocol};google.ml=function(){return null};google.wl=function(a,b){try{google.ml(Error(a),!1,b)}catch(c){}};google.time=function(){return(new Date).getTime()};google.log=function(a,b,c,e,g){a=google.logUrl(a,b,c,e,g);if(""!=a){b=new Image;var d=google.lc,f=google.li;d[f]=b;b.onerror=b.onload=b.onabort=function(){delete d[f]};window.google&&window.google.vel&&window.google.vel.lu&&window.google.vel.lu(a);b.src=a;google.li=f+1}};google.logUrl=function(a,b,c,e
+IPD,1410:,g){var d="",f=google.ls||"";if(!c&&-1==b.search("&ei=")){var h=google.getEI(e),d="&ei="+h;-1==b.search("&lei=")&&((e=google.getLEI(e))?d+="&lei="+e:h!=google.kEI&&(d+="&lei="+google.kEI))}a=c||"/"+(g||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+d+f+"&zx="+google.time();/^http:/i.test(a)&&google.https()&&(google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a};google.y={};google.x=function(a,b){google.y[a.id]=[a,b];return!1};google.lq=[];google.load=function(a,b,c){google.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};})();var a=window.location,b=a.href.indexOf("#");if(0<=b){var c=a.href.substring(b+1);/(^|&)q=/.test(c)&&-1==c.indexOf("#")&&a.replace("/search?"+c.replace(/(^|&)fp=[^&]*/g,"")+"&cad=h")};</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}
</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#36
+IPD,1410:c}.q{color:#00c}.ts td{padding:0}.ts{border-collapse:collapse}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}a.gb1,a.gb2,a.gb3,a.gb4{color:#11c !important}body{background:#fff;color:black}a{color:#11c;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#36c}a:visited{color:#551a8b}a.gb1,a.gb4{text-decoration:underline}a.gb3:hover{text-decoration:none}#ghead a.gb2:hover{color:#fff !important}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#eee;border:solid 1px;border-color:#ccc #999 #999 #ccc;height:30px}.lsbb{display:block}.ftl,#fll a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#ccc}.lst:focus{outline:none}</style><script></script><link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon"></head><body bgcolor="#fff"><script>(function(){var src='/images/nav_logo229.png';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}
if (!iesg){document.f&&docu
+IPD,1410:ment.f.q.focus();document.gbqf&&document.gbqf.q.focus();}
}
})();</script><div id="mngb">    <div id=gbar><nobr><b class=gb1>Search</b> <a class=gb1 href="http://www.google.com/imghp?hl=en&tab=wi">Images</a> <a class=gb1 href="http://maps.google.com/maps?hl=en&tab=wl">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=w8">Play</a> <a class=gb1 href="http://www.youtube.com/?tab=w1">YouTube</a> <a class=gb1 href="http://news.google.com/nwshp?hl=en&tab=wn">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=wm">Gmail</a> <a class=gb1 href="https://drive.google.com/?tab=wo">Drive</a> <a class=gb1 style="text-decoration:none" href="https://www.google.com/intl/en/options/"><u>More</u> »</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="http://www.google.com/history/optout?hl=en" class=gb4>Web History</a> | <a  href="/preferences?hl=en" class=gb4>Settings</a> | <a target=_top id=gb_70 href="https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=http://www.google.com/" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div>    </div><center><br clear="all" id="lgpd"><div id="lga"><img alt="Google" height="92" src="/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png" style="padding:28px 0 14px" wid
+IPD,1410:th="272" id="hplogo" onload="window.lol&&lol()"><br><br></div><form action="/search" name="f"><table cellpadding="0" cellspacing="0"><tr valign="top"><td width="25%"> </td><td align="center" nowrap=""><input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden"><div class="ds" style="height:32px;margin:4px 0"><input style="color:#000;margin:0;padding:5px 8px 0 6px;vertical-align:top" autocomplete="off" class="lst" value="" title="Google Search" maxlength="2048" name="q" size="57"></div><br style="line-height:0"><span class="ds"><span class="lsbb"><input class="lsb" value="Google Search" name="btnG" type="submit"></span></span><span class="ds"><span class="lsbb"><input class="lsb" value="I'm Feeling Lucky" name="btnI" onclick="if(this.form.q.value)this.checked=1; else top.location='/doodles/'" type="submit"></span></span></td><td class="fl sblc" align="left" nowrap="" width="25%"><a href="/advanced_search?hl=en&authuser=0">Advanced search</a><a href="/language_tools?hl=en&authuser=0">Language tools</a></td></tr></table><input id="gbv" name="gbv" type="hidden" value="1"></form><div id="gac_scont"></div><div style="font-size:83%;min-height:3.5em"><br></div><span id="footer"><div style="font-size:10pt"><div style="margin:19px auto;text-alig
+IPD,1410:n:center" id="fll"><a href="/intl/en/ads/">Advertising Programs</a><a href="/services/">Business Solutions</a><a href="https://plus.google.com/116899029375914044550" rel="publisher">+Google</a><a href="/intl/en/about.html">About Google</a><a href="http://www.google.com/setprefdomain?prefdom=MY&prev=http://www.google.com.my/&sig=__7K51G9uSjvgDR9Qb9AlXCF_YSJg%3D">Google.com.my</a></div></div><p style="color:#767676;font-size:8pt">© 2016 - <a href="/intl/en/policies/privacy/">Privacy</a> - <a href="/intl/en/policies/terms/">Terms</a></p></span></center><script>(function(){window.google.cdo={height:0,width:0};(function(){var a=window.innerWidth,b=window.innerHeight;if(!a||!b)var c=window.document,d="CSS1Compat"==c.compatMode?c.documentElement:c.body,a=d.clientWidth,b=d.clientHeight;a&&b&&(a!=google.cdo.width||b!=google.cdo.height)&&google.log("","","/client_204?&atyp=i&biw="+a+"&bih="+b+"&ei="+google.kEI);})();})();</script><div id="xjsd"></div><div id="xjsi"><script>(function(){function c(b){window.setTimeout(function(){var a=document.createElement("script");a.src=b;document.getElementById("xjsd").appendChild(a)},0)}google.dljp=function(b,a){google.xjsu=b;c(a)};google.dlj=c;})();(function(){window.google.xjsrm=[];})();if(google.y)google.y.first=[];if(!google.xjs){window._=window._||{};window._._DumpException=function(e){throw e};if(google.timers&&google.timers.load.t){google.ti
+IPD,1093:mers.load.t.xjsls=new Date().getTime();}google.dljp('/xjs/_/js/k\x3dxjs.hp.en_US.qP2M4Nmr0aA.O/m\x3dsb_he,d/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oEsHMah2R9GNISWp1OmWDR28RwSyQ','/xjs/_/js/k\x3dxjs.hp.en_US.qP2M4Nmr0aA.O/m\x3dsb_he,d/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oEsHMah2R9GNISWp1OmWDR28RwSyQ');google.xjs=1;}google.pmc={"sb_he":{"agen":true,"cgen":true,"client":"heirloom-hp","dh":true,"dhqt":true,"ds":"","fl":true,"host":"google.com","isbh":28,"jam":0,"jsonp":true,"msgs":{"cibl":"Clear Search","dym":"Did you mean:","lcky":"I\u0026#39;m Feeling Lucky","lml":"Learn more","oskt":"Input tools","psrc":"This search was removed from your \u003Ca href=\"/history\"\u003EWeb History\u003C/a\u003E","psrl":"Remove","sbit":"Search by image","srch":"Google Search"},"nds":true,"ovr":{},"pq":"","refpd":true,"rfs":[],"scd":10,"sce":5,"stok":"hQ250lThE3z-O0zdRwiuIzzAggQ"},"d":{}};google.y.first.push(function(){if(google.med){google.med('init');google.initHistory();google.med('history');}});if(google.j&&google.j.en&&google.j.xi){window.setTimeout(google.j.xi,0);}
</script></div></body></html>CLOSED

```

However, when I try it with the actual URL I intend to use:

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

  delay(3000);
  Serial2.write("AT\r\n");
  delay(3000);
  Serial2.write("AT+CWMODE=1\r\n");
  delay(3000);
  Serial2.write("AT+CIPMUX=0\r\n");
  delay(3000);

  Serial2.write("AT+CIPSTART=\"TCP\",\"api.pushingbox.com\",80\r\n");
  delay(500);
  Serial2.write("AT+CIPSEND=135\r\n");
  delay(500);
  Serial2.write("GET /pushingbox?devid=vEB39F555B1B8295&tempData=cabbages HTTP/1.0\r\n");
  delay(500);
  Serial2.write("User-Agent: curl/7.37.0\r\n");
  delay(500);
  Serial2.write("Host: api.pushingbox.com\r\n");
  delay(500);
  Serial2.write("Accept: */*\r\n\r\n\r\n");
}

void loop()
{
  if (Serial2.available()) {
    Serial.write(Serial2.read());
  }
  if (Serial.available()) {
    Serial2.write(Serial.read());
  }
}

```

I get the following response:

```
AT
OK
AT+CWMODE=1
OK
AT+CIPMUX=0
OK
AT+CIPSTART=Accept: */*ERROR
ERROR
ERROR

+IPD,212:HTTP/1.0 408 Request Time-out
Cache-Control: no-cache
Connection: close
Content-Type: text/html

<html><body><h1>408 Request Time-out</h1>
Your browser didn't send a complete request in time.
</body></html>
CLOSED

```

The code is exactly the same except for the different URLs used, so what is causing the problem here? Why can't I send "api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295?tempData=cabbages" to the internet? Please help! :-/

# Answer
> 1 votes
I did notice you also changed

AT+CIPSEND=80\r\n

to

AT+CIPSEND=135\r\n

probably you send your request wrong or something?!? (sorry I post this as answer but I didn't unlock comments yet)

# Answer
> 0 votes
First you must check if the problem is on your side or not. You call http://api.pushingbox.com and you send parameter which are "pushingbox?devid=vEB39F555B1B8295&tempData=cabbages"

When I glue them together http://api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295&tempData=cabbages and copy past this on my browser, I get an error with "Daily limit exceeded" with a status of 429 meaning "too many request". So maybe there is a problem with the server?

# Answer
> -1 votes
Try changing:

```
Serial2.write("AT+CWMODE=1\r\n");

```

to:

```
Serial2.write("AT+CWMODE=2\r\n");

```

or:

```
Serial2.write("AT+CWMODE=3\r\n");

```

---
Tags: esp8266, wifi, networking
---


title: Calling I2C functions inside an ISR

text:
# Question
Title: Calling I2C functions inside an ISR
I have an Adafruit 2.8" cap touch display, which has an interrupt pin (IRQ). I tried to use this with my Arduino Nano, but encountered a problem:

When trying to get the touched point from the display during a display triggered interrupt, it would not work because the touch screen is connected via I2C and according to this post, it is not possible to call I2C functions inside an ISR on an Arduino. Therefore the IRQ pin does not make much sense to me, as I would have to poll if the screen is touched inside the main loop.

My question now is: is this a problem specific for the AtMega 328p? I am thinking about getting an ESP32 based board. Would it be possible to get the I2C data inside an ISR on this chip? Or is it just not possible at all?

# Answer
> 9 votes
Here is an analogy for you to help you understand why using the IRQ is a good idea.

Imagine you are at a conference. There's hundreds of you in the audience, and you are in a question and answer session with the person on the stage. Maybe their presentation has just come to the end and they're fielding questions from the audience.

Lots of people have questions, and any member of the audience can raise their hand at any time to ask a question.

Now there's three ways of the presenter handling it.

The first way is your way of using an interrupt and responding to the interrupt within the interrupt handler itself. This is like the presenter stopping what he is saying mid sentence to answer the new question. That's just nasty, and both confusing for the presenter and the audience.

The second way is for the presenter to continue until the current question has finished being answered, then pick someone at random from the sea of hands. While the question is being answered people are getting antsy waving their hands around to get noticed, and there's no guarantee that it will be first come first served. People may then not be paying attention to what is a good answer to an important question because they are fixated on theirs. That's just the same as you polling the interrupt line, or polling the screen directly. If the interrupt line isn't active at the time you poll it you'll miss it.

The third, and best way, is if the presenter sees a hand go up while he's answering a question, and acknowledges that person with an "Ok, I'll come to you next.". Everyone else knows that waving their hand around is pointless, so don't bother - and the next question can be asked immediately after the current question has been answered. Everyone is happy. That's the proper way of handling a system like this - when the interrupt triggers you remember "Ok, I'll come to that interrupt signal in a moment when I'm ready". Then in your loop, when you have the time, you act on the interrupt that you remembered earlier. You get to respond at your speed to a signal that you may otherwise have missed.

So to sum up: using an interrupt to remember that something is pending and then act on that remembered state is how you should use interrupts to manage communication.

# Answer
> 4 votes
I started writing this as a comment, but the more I wrote the more I needed space to complete my thoughts, so here it is as answer.

In my opinion, reacting to a user interaction should NOT be put in ISR; consequently the best thing to do is to avoid the interrupt and poll that wire.

IMHO interrupts need to be used in very few cases, and only when the reactivity to a trigger is needed within (tenths of) microseconds. Whenever the latency can become greater than one millisecond it is much better to avoid the interrupt and all its problems, which are (not limited to)

1. the need for the microcontroller to save the context
2. interrupting other "tasks", which can be time critical (see for instance the timing in a software serial)
3. interrupts can happen any time (maybe in the middle of a write to a int variable)
4. variables shared between an interrupt and "normal" program cannot be optimized (should always be declared `volatile`)
5. ISRs must be as short as possible
6. usually you can't have multiple interrupts (you become blind to other interrupts, or they get delayed until your ISR is completed)

Point 1 delays your actions uselessly.

Point 2 will be a problem when trying to debug some strange problem in your communication or acquisition or software PWM or anything based on precise timing.

Point 4 implies that shared variables will always be read from memory rather than saved in register (and this will slow down your code)

Point 5 and 6 state that you cannot use long communication routines (serial, I2C, SPI, anything) inside the ISR.

These are common to all microcontrollers generally speaking, so my advice is don't use the interrupt, at least not in this case, since reacting to a user interaction is slow (even 50-100ms will not be noticeable). Poll the wire, then when you detect it ask the controller the position.

# Answer
> 3 votes
The better way to do it would be to set a `volatile` flag in the ISR and handle that in the main loop.

This relies on you making sure the main loop never blocks so the flag can be check often.

```
volatile bool isr_happened;

void isr(){
    isr_happened = true;
}

void loop(){
    if(isr_happened){
        //do i2c

        isr_happened = false;
    }

}

```

---
Tags: arduino-nano, i2c, interrupt, esp32
---


# Question
Title: How to rotate 3 servo motors when 6 led lights are lit using EMG signals
I am completely new to arduino and trying to do a school project where i will be able to more 3 fingers with the help of a servo motor using EMG signals. Right now i am able to read the signals. I just want to modify the code in such a way that when all 6 lights are lit on my emg reading device the servo with rotate by 90 degree. And when all leds are off the servo motor will go back to its initial position, that is will rotate back by 90 degree. I badly need help over here. Here is the code:

```
 #define NUM_LED 6  //sets the maximum numbers of LEDs
#define MAX 45     //maximum posible reading. TWEAK THIS VALUE!!
int reading[10];
int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};

void setup(){
  Serial.begin(9600); //begin serial communications
  for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
    pinMode(leds[i], OUTPUT);
  }
}

void loop(){
  for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
    reading[i] = analogRead(A0) * multiplier;
    delay(2);
  }
  for(int i = 0; i < 10; i++){   //average the ten readings
    finalReading += reading[i];
  }
  finalReading /= 10;
  for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
    digitalWrite(leds[j], LOW);
  }
  Serial.print(finalReading);
  Serial.print("\t");
  finalReading = constrain(finalReading, 0, MAX);
  litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
  Serial.println(litLeds);
  for(int k = 0; k < litLeds; k++){
    digitalWrite(leds[k], HIGH);
  }
  //for serial debugging, uncomment the next two lines.
  //Serial.println(finalReading);
  //delay(100);
}

```

Thanks :)

# Answer
> 1 votes
Apart the problem you have (that the constants are not defined), what you are asking can be easily solved by looking at the servo library.

The servo library tells you that

1. You have to include the servo library header: `#include <Servo.h>`
2. You have to add a variable to hold the object: `Servo myservo;`
3. You have to attach the object to a pin: `myservo.attach(SERVO_PIN);`
4. Finally you can move the motor to any position (0 \<= x \<= 180) with the syntax `myservo.write(val);`

In your code, then, you have the variable `litLeds` which tells you how many leds are there. Particularly if you have 6 (or more) leds light you will move to 90°, while with 0 (or less - even if this is meaningless) you reset to 0. So the complete code is

```
#include <Servo.h>

int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};
Servo myservo;

void setup(){
    Serial.begin(9600); //begin serial communications
    for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
        pinMode(leds[i], OUTPUT);
    }
    myservo.attach(SERVO_PIN);
    myservo.write(0);
}

void loop(){
    for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
        reading[i] = analogRead(A0) * multiplier;
        delay(2);
    }
    for(int i = 0; i < 10; i++){   //average the ten readings
        finalReading += reading[i];
    }
    finalReading /= 10;
    for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
        digitalWrite(leds[j], LOW);
    }
    Serial.print(finalReading);
    Serial.print("\t");
    finalReading = constrain(finalReading, 0, MAX);
    litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
    Serial.println(litLeds);
    for(int k = 0; k < litLeds; k++){
        digitalWrite(leds[k], HIGH);
    }
    if (litLeds >= 6)
        myservo.write(90);
    else if (litLeds <= 0)
        myservo.write(0);

    //for serial debugging, uncomment the next two lines.
    //Serial.println(finalReading);
    //delay(100);
}

```

Please note that some `define`s are missing (e.g. the `MAX`, `NUM_LED` and `SERVO_PIN`)

---
Tags: programming, arduino-ide, servo, robotics
---


# Question
Title: Arduino Nano + RC522 + w5500 Ethernet Module
has anyone had any experience wiring up an arduino nano with an RC522 RFID module and a W5500 ethernet module? i can get each of them to work individually, but i cannot get them to work together. i am not super experienced, but this seems to be some sort of SPI collision

The RobotDyn Ethernet Module i am using:

The RFID Module i am using:

# Answer
If both modules use SPI then they should each have a separate pin connected to the slave select.

This lets you select which module you are talking to every time you start a communication. If the modules are well behaved then its MISO pin will be in high impedance when it is not selected instead of pulling it low or high trying to send data.

If it is not well behaved then you will need to add a buffer.
> 0 votes

---
Tags: arduino-nano, ethernet, spi, rfid
---


# Question
Title: Arduino and MatLab with OWI Robotic Arm Edge -- Issue with I2C
I'm working on a project where I want to be able to program a robotic arm in Arduino using MatLab. I've used the Arduino Uno with an Adafruit Motor Shield V2.3 and the OWI Robotic Arm Edge kit. The arm is perfectly assembled and works just fine with the standard remote it comes with. All of the connections with the Adafruit Motor Shield are correctly placed, and the shield has been soldered onto pins that connect to the Uno.

I am absolutely positive that the physical and electronic setup is correct. However, whenever I try to move the motors attached to the shield, none of them register. Below is my code:

```
a = arduino('COM3', 'Uno', 'Libraries', 'Adafruit\MotorShieldV2')
shield = addon(a, 'Adafruit\MotorShieldV2')
addrs = scanI2CBus(a,0);

dcm = dcmotor(shield, 1);
dcm.Speed = 0.01;
start(dcm)

dcm2 = dcmotor(shield, 2);
dcm2.Speed = 0.2;
start(dcm2)

dcm3 = dcmotor(shield, 3);
dcm3.Speed = 0.2;
start(dcm3)

dcm4 = dcmotor(shield, 4);
dcm4.Speed = 0.2;
start(dcm4)

```

I believe the issue is with the third line:

```
addrs = scanI2CBus(a,0);

```

When I run the code, the shield has the following properties:

```
shield =

motorshieldv2 with properties:

          Pins: A4(SDA), A5(SCL)
    I2CAddress: 96 (0x60)
  PWMFrequency: 1600 (Hz)

```

So while the I2C address should be 0x60, the actual value of the `addrs` variable is a 2x1 cell instead of 0x60, as the project demands/specifies as seen in the workspace:

I'm almost certain that this is the reason behind why none of the motors are being registered, but how can I fix it?

Thanks in advance for any assistance! Please let me know if I need to supply more information.

# Answer
> 1 votes
The documentation in MATLAB for `scanI2CBus()` notes that the return is a cell array of character vectors

They even give the example:

```
a = arduino('COM9');
scanI2CBus(a,1)

```

with result:

```
ans =
            '0x48'

```

It appears you will need to parse the cell array into the numeric value or otherwise convert it to a number, perhaps using the MATLAB function `hex2dec('hex_value')`

---
Tags: arduino-uno, arduino-motor-shield, robotics, matlab
---


title: Download and print data from Thingspeak

text:
# Question
Title: Download and print data from Thingspeak
I opted to try doing this with Thingspeak Library instead, which @gre\_gor suggested early on. Worked much easier!

Here's working code for anyone else trying to do this. I used the MKR1000.

```
#include "ThingSpeak.h"
#include <SPI.h>
#include <WiFi101.h>
#include "DHT.h"

char ssid[] = "XXXXXX";    //  your network SSID (name)
    char pass[] = "XXXXXXX";   // your network password
    int status = WL_IDLE_STATUS;
    WiFiClient  client;

unsigned long myChannel = CHANNEL;
const char * myReadAPIKey = "READKEY";
const char * myWriteAPIKey = "WRITEKEY";

#define DHTPIN 1
#define DHTTYPE DHT11
DHT dht(DHTPIN,DHTTYPE);

void setup() {
  // put your setup code here, to run once:
 Serial.begin(9600);
WiFi.begin(ssid, pass);
 ThingSpeak.begin(client);
  delay(10000);

}

void loop() {
 printWifiStatus();
    Serial.println("Reading Sensor Data... ");

  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
    float water = ThingSpeak.readFloatField(myChannel, 4);

   delay(100);

    Serial.print("Writing to ThingSpeak... ");
    ThingSpeak.setField(1, (float)h);
    ThingSpeak.setField(2, (float)t);
    ThingSpeak.setField(3, (float)f);
    Serial.print("... ");
    ThingSpeak.writeFields(myChannel, myWriteAPIKey);
     delay(5000);

  Serial.print("Current temp is: ");
  Serial.print(f);
  Serial.print(" *F and ");
  Serial.print(t);
  Serial.println(" *C");
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.println("% ");
  Serial.print("Water Signal: ");
  Serial.print(water);
  Serial.println(" seconds");

  Serial.println("Function complete, time to rest.");
  delay(10000); // Hibernate [To Do]

}

void printWifiStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

------------ ORIGINAL MESSAGE ------------------------------------------------

I've been banging my head against this for a week now and I have made no progress.

I'm trying to convert this code to also read a field on Thingspeak and print to serial (as well as run a pump based on the output). I've tried a handful of guides and recreating it from other projects to no avail. Is there a straightforward method?

```
#include <SPI.h> //you don't need this as we arn't using the shiled just chip
#include <WiFi101.h>
#include "DHT.h"

#define DHTPIN 1    // what pin we're connected to, pin1 is 5th pin from end
#define floatswitch 7 // float switch
// soil moisture sensor
int soilPin = 2;
int soilPower = 6; //Variable for Soil moisture Power

// light sensor

// Uncomment whatever DHT sensor type you're using!
#define DHTTYPE DHT11  // DHT 11
//#define DHTTYPE DHT21  // DHT 21
//#define DHTTYPE DHT22  // DHT 22

DHT dht(DHTPIN,DHTTYPE);

String apiKey ="XXXXXXX"; // api from ThingSpeak

char ssid[] = "XXXXX"; //  your network SSID (name)
char pass[] = "XXXXX";    //your network password
int keyIndex = 0;     // your network key Index number (needed only for WEP)

//#define WEBSITE "api.thingspeak.com"

//int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "api.thingspeak.com";    // name address for Google (using DNS)

// this function powers and reads the moisture sensor to avoid sensor corrosion.
//int readSoil()
//{
  //  digitalWrite(soilPower, HIGH);//turn D7 "On"
    //int val = analogRead(soilPin);//Read the SIG value form sensor
   // return val;//send current moisture value
   // digitalWrite(soilPower, LOW);//turn D7 "Off"
//}

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  pinMode(floatswitch,INPUT_PULLUP);

  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }

}

void loop() {

pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT
 // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);
//Connect to WPA/WPA2 network.Change this line if using open/WEP network
WiFi.begin(ssid, pass);
digitalWrite(soilPower, HIGH);//turn D7 "On"
    // wait 5 seconds for connection:
    delay(5000);
  Serial.println("Connected to wifi");
  printWifiStatus();

// READ STUFF

String url = "/channels/358435/field/6/last.txt";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + server + "\r\n" +
        "Connection: close\r\n\r\n");
    String channelData = client.readStringUntil('\n');
// READ STUFF

  int h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  int t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  int f = dht.readTemperature(true);
  int x = digitalRead(floatswitch);
//This is a function used to get the soil moisture content
  int s = analogRead(soilPin);
  int w = 5;

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Soil Moisture: ");
  Serial.print(s);
  Serial.print(" *F ");
  Serial.print("Float Switch: ");
  Serial.print(x);
  Serial.print("channelData");
  Serial.println();

Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {

    Serial.println("connected to server");

          client.print(F("POST "));
          client.print("/update?key=apiKey&field1="
          +               (String) h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
                                   );

          String tsData = "field1="   //need the length to give to ThingSpeak
          +             (String)  h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
        ;

          client.print("POST /update HTTP/1.1\n");
          client.print("Host: api.thingspeak.com\n");
          client.print("Connection: close\n");
          client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
          client.print("Content-Type: application/x-www-form-urlencoded\n");
          client.print("Content-Length: ");
          client.print(tsData.length());  //send out data string legth to ts
          client.print("\n\n");
          client.print(tsData);
          client.stop();
          digitalWrite(soilPower, LOW);//turn D7 "Off"
          delay(200);
          Serial.println("Function complete, time to rest");
          WiFi.disconnect();

//This is where to put the sleep and hibernate stuff

          delay(20000);

//hibernate stuff ^^^^
    }

}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

# Answer
You need to construct a client object and pass in a URL. Then, wait for a response and read data in from the client. Here is the main concept.

```
const char host[] = "api.thingspeak.com";

WiFiClient client;

const int httpPort = 80;

if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
}

String url = "/channels/1417/field/1/last.txt";

client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + host + "\r\n" +
        "Connection: close\r\n\r\n");

while(client.available()) {
    String channelData = client.readStringUntil('\n');
    // do something with the data

```

}

Make sure to include a Read API key if your channel is not public. Also, check out CheerLights project examples for more ideas on how to do this. Many CheerLights projects read data from a a ThingSpeak channel.
> 1 votes

---
Tags: esp8266, datalogging
---


# Question
Title: Strange issue with FHT library for sound-reactive LED project
I have been playing with the FHT library and have run into an interesting issue with `fht_mag_octave()` disrupting the output of my ADC actions. Running on a MEGA ADK.

The idea is that I'm using FHT to read in the microphone input into A0, but also occasionally checking A2 pot to adjust the volume/brightness of the of the overall FastLED strip.

Here is the code in question... it's barebones. Just the standard FHT loop and then, every 100 loops, it checks A2 for the brightness setting.

```
#include <FastLED.h>

#define LED_PIN     6
#define BRIGHTNESS  200
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
#define NUM_LEDS 16
CRGB* const leds(NUM_LEDS);

#define LOG_OUT 1 // use the log output function
#define OCTAVE 1 //   // Group buckets into octaves  (use the log output function LOG_OUT 1)
#define OCT_NORM 0 // Don't normalise octave intensities by number of bins
#define FHT_N 128 // set to 128 point fht
#include <FHT.h> //

void setup() {
  Serial.begin(9600);
  delay(1000);
  FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
  FastLED.setBrightness (BRIGHTNESS);

  // TIMSK0 = 0; // turn off timer0 for lower jitter (commented this out b/c I think this interferes with FastLED)
  ADCSRA = 0xe5; // set the adc to free running mode (0b11100101), prescalar=32 for higher ADC clock freq
  ADMUX = 0x40 | (0 & 0x07); // use adc0 (0b1000000)
  DIDR0 = 0x01; // turn off the digital input for adc0

}

int counter = 0;

void loop() {

  while (1) { // reduces jitter

    cli();  // UDRE interrupt slows this way down on arduino1.0

    for (int i = 0 ; i < FHT_N ; i++) { // save 128 samples
      while (!(ADCSRA & 0x10)); // wait for adc to be ready  in binary 0010000 (look for ADC Interrupt flag to be set to 1)
      ADCSRA = 0xf5; // restart adc (in binary 11110101...http://www.robotplatform.com/knowledge/ADC/adc_tutorial_2.html)
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fht_input[i] = k; // put real data into bins

    }

    fht_window(); // window the data for better frequency response
    fht_reorder(); // reorder the data before doing the fht
    fht_run(); // process the data in the fht
    fht_mag_octave();
 //   fht_mag_log();

    // every 100th loop, adjust the volume accourding to the value on A2 (Pot)
    if (counter > 10) {

      ADMUX = 0x40 | (2 & 0x07); // set admux to look at Analogpin A2

      while (!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int brightness = (j << 8) | m; // form into an int

//      brightness = map(brightness, 0, 1023, 0, 255);
      Serial.print("b: ");
      Serial.println(brightness);

      FastLED.setBrightness (brightness);

      ADMUX = 0x40 | (0 & 0x07); // set admux back to look at A0 analog pin (to read the microphone input
      counter = 0;
    }

    counter++;
    sei();

  }
}

```

Here's the output as shown (basically, it's outputting nonsense, non-`int` values):

```
b: ⸮
b: ⸮
b:
b:
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b:

b: ⸮
b: ⸮
b:

```

If I comment OUT the `fht_mag_octave` line and uncomment `fht_mag_log()`, here is the output (which looks right as I turn the Pot pin):

```
b: 0
b: 0
b: 0
b: 0
b: 0
b: 9
b: 35
b: 38
b: 48
b: 85
b: 143
b: 171
b: 188
b: 204
b: 224
b: 245
b: 280
b: 332

```

The issue is that the A2 value "brightness" does not read properly if I use `fht_mag_octave()`. If I comment out only the `fht_mag_octave()` line, it works perfectly. I can also use `fht_mag_log` instead, and it works fine.

This makes me think that there is something that `fht_mag_octave()` does something that interferes with the ADC registers.

Any ideas?

# Answer
Thanks to @TonyStewart for suggesting that I just do a successive A2 read.

I modified the code by just repeating the A2 read. b1 is the first read, and b2 is the 2nd read.

```
  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
  byte m = ADCL; // fetch adc data
  byte j = ADCH;
  int brightness = (j << 8) | m; // form into an int

  Serial.print("b1: ");
  Serial.print(brightness);

  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
   m = ADCL; // fetch adc data
   j = ADCH;
   brightness = (j << 8) | m; // form into an int

  Serial.print("   b2: ");
  Serial.println(brightness);

```

And the readout looks good. B1 is now legible, but incorrect/low. B2 looks accurate and scales all the way to 1024 as I wanted.

```
b1: 0   b2: 688
b1: 0   b2: 739
b1: 0   b2: 816
b1: 20   b2: 915
b1: 118   b2: 1016
b1: 152   b2: 1023
b1: 172   b2: 1023
b1: 165   b2: 1023
b1: 180   b2: 1023
b1: 188   b2: 1022
b1: 184   b2: 931
b1: 127   b2: 713
b1: 0   b2: 615
b1: 0   b2: 532
b1: 0   b2: 436
b1: 0   b2: 327
b1: 0   b2: 304
b1: 0   b2: 452

```

I'm still curious about the reasoning behind this...but I'm glad that there is a solution, and not one that is too painful.
> 1 votes

---
Tags: programming, audio
---


title: Arduino pins LCD and motor controller

text:
# Question
Title: Arduino pins LCD and motor controller
I am using an L298N motor control. I want to use my 2\*16 LCD. Can I use the code like this?

```
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(12, 9, 4, 5, 6, 7);

// Motor Control
#define enableA  3
#define enableB  11
#define in1 4
#define in2 5
#define in3 6
#define in4 7

```

# Answer
> 1 votes
Using that pin configuration you'll have several problems despite you'll use enable pin.

I would use a I2C module for 16x2 lcd like this https://www.amazon.com/SainSmart-Serial-Module-Display-Arduino/dp/B00813HBEQ

Control 16x2 lcd with I2C.

# Answer
> 0 votes
You cannot use same pins for LCD and motor. Data transfer through pins 4,5,6,7(being data pins for LCD) will effect your motor state. You should use different pins and if you does not have sufficient digital pins so you can use analog pins as digital pins (0-LOW,255-HIGH).

# Answer
> 0 votes
You can use the same pins for both the motor and the LCD.

A condition is that the **enable** pin decides when the LCD or the motor is accepting inputs from the data pins. This is a normal bus configuration, several devices share data pins and have a **enable** pin to tell the device when they owns the data bus.

---
Tags: lcd, l298n
---


# Question
Title: HTTP post request in JSON Format using SIM900 module
I tried to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data. While posting the data I'm getting the error response while initializing the server using the command:

```
{("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path")}

```

I don't know what the error is and how to fix it. Please help me to fix this.

```
#include<SoftwareSerial.h>

SoftwareSerial client(2,3);

String testReading="{  \"testID\" : 1,  \"testLevel\" : 1, }";

void setup() {
  Serial.begin(9600);
  client.begin(9600);
  delay(1000);
  if(client.available()) {
    Serial.print("Connected");
  } else {
    Serial.print("Not Connected");
  }
  checkSignal();
  connectGPRS();
  postData();
  delay(1000);
}

void loop() {
  if(client.available()) {
    checkSignal();
    connectGPRS();
    postData();
    delay(1000);
  }
}

void connectGPRS() {
  client.println("AT+CGATT?");
  delay(1000);
  ShowSerialData();
  client.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(1000);
  ShowSerialData();
  client.println("AT+SAPBR=3,1,\"APN\",\"www\"");
  //Using Indian Standard Vodafone Sim and so APN is www
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=1,1");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=2,1");
  delay(1000);
  ShowSerialData();
}

void checkSignal() {
  client.println("AT+CSQ");
  delay(1000);
  ShowSerialData();
}

void ShowSerialData() {
  while(client.available()!=0)
    Serial.write(client.read());
}

void postData() {
  client.println("AT+HTTPINIT");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CONTENT\",\"application/json");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPDATA=99,10000");
  delay(1000);
  ShowSerialData;

  client.println(testReading);
  delay(1000);
  ShowSerialData;

  client.println("AT+HTTPACTION=1");
  delay(10000);
  while(!client.available());
  ShowSerialData();
}

```

# Answer
> 2 votes
Hi all use this code below for establishing HTTP connection with the server. And to neglect the 601 or 504 error use proper posting format. Here I'm using JSON format. I just gave manual data. Ignore those errors in HTTPINIT, AT+SAPBR=2,1. The data will be posted to the server

```
 #include<SoftwareSerial.h>

SoftwareSerial client(2,3);

String reading="{  \" : 1,  \"latitude\" : 12.983027,  \"longitude\" : 80.2594,  \"timestamp\" : 100,  }";

void setup()
{
  Serial.begin(9600);
  client.begin(9600);
  delay(500);

  if(client.available())
  {
    Serial.print("Connected");
  }
  else
  {
    Serial.print("NotConnected");
  }

  //initSIM();
  connectGPRS();
  connectHTTP();
}

void loop()
{

}

void connectGPRS()
{
  client.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=3,1,\"APN\",\"www\"");//APN
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=1,1");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=2,1");
  delay(1000);
  ShowSerialData();
}

void connectHTTP()
{
  client.println("AT+HTTPINIT");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"URL\",\"http://xxx.xxx.xx/Listener/\"");//Public server IP address
  client.println("AT+HTTPPARA=\"URL\",\"http://testServer/Listener/\"");//Public server address
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  delay(1000);
  ShowSerialData();

  client.println(reading);
  delay(1000);
  ShowSerialData;

  client.println("AT+HTTPACTION=1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPREAD");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPTERM");
  delay(1000);
  ShowSerialData;
}

void ShowSerialData()
{
  while(client.available()!=0)
  {
  Serial.write(client.read());
  delay(100);
  }
}

```

# Answer
> 1 votes
```
client.println(reading);
delay(1000);
ShowSerialData;

```

The above line of code would result in an error.

---
Tags: arduino-uno, http
---


# Question
Title: How to read data from client ESP8266-01?
I need help: my Arduino is not receiving or reading from an ESP8266-01 as a client.

Actually, the ESP01-server and ESP01-client are successfully talking each other but if I attach the Arduino Uno to read the data from the server, nothing happens. It's not receiving at all.

Any help is very much appreciated.

Lua server:

```
-- GMKSoft
--*************************
--    ESP8266 Server
--*************************

--*************************
--  Static Configuration
--*************************
cfg =
{
    ip="192.168.255.101",
    netmask="255.255.255.0",
    gateway="192.168.0.1"
}
wifi.ap.setip(cfg)

wifi.setmode(wifi.STATIONAP);
wifi.ap.config({ssid="GMKSoft",pwd="GMKSoftESP"});
print("Server IP Address:",wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(8080, function(conn)
    conn:on("receive", function(conn, receivedData)
        print("Received Data: " .. receivedData)
    end)
    conn:on("sent", function(conn)
      collectgarbage()
    end)
end)

```

Client lua:

```
-- GMKSoft
--*************************
--    ESP8266 Client
--*************************

--*************************
--  Static Configuration
--*************************
client_ip="192.168.255.102"
client_netmask="255.255.255.0"
client_gateway="192.168.0.1"

wifi.setmode(wifi.STATION)
wifi.setphymode(wifi.PHYMODE_N)
wifi.sta.config("GMKSoft","GMKSoftESP") -- connecting to server
wifi.sta.connect()
if client_ip ~= "" then
    wifi.sta.setip({ip=client_ip,netmask=client_netmask,gateway=client_gateway})
end

tmr.alarm(1, 2000, 1, function()

     if(wifi.sta.getip()~=nil) then
          tmr.stop(1)
          print("Connected!")
          print("Client IP Address:",wifi.sta.getip())
          cl=net.createConnection(net.TCP, 0)
          cl:connect(8080,"192.168.255.101")

          tmr.alarm(2, 5000, 1, function()
            cl:send("Hello World!")
          end)

         tmr.stop(2)
         print("Going to sleep")
         wifi.sta.sleeptype(wifi.MODEM_SLEEP)
      else
         print("Connecting...")
      end
end)

```

Arduino Code:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
}

void loop() {
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

```

# Answer
> 1 votes
I successfully communicate with two esp01 module as a AP and STATION.

The esp01 as a server, please flash it using NodeMCU-PyFlasher-2.1, and used this bin file nodemcu-master-7-modules-2017-11-23-15-58-17-integer.bin

I build it from here

Here is the code of the server, I'm using ESPPlorer IDE lua script:

```
cfg={}
cfg.ssid="GMKWiFi"
cfg.pwd="GMKSoft2627"

dhcp_config ={}
dhcp_config.start = "192.168.1.100"
wifi.ap.dhcp.config(dhcp_config)

print("ESP8266 Server")
wifi.setmode(wifi.STATIONAP);
wifi.ap.config(cfg);
print("Server IP Address:",wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(80, function(conn)
    conn:on("receive", function(conn, receivedData)
        print(receivedData)
    end)
    conn:on("sent", function(conn)
      collectgarbage()
    end)
end)

```

Here is the Client Code, Im using Arduino IDE

```
#include <ESP8266WiFi.h>
const char* ssid     = "yourSSID";         // SSID
const char* password = "yourpassword";     // Password
const char* host = "192.168.4.1";         // Server IP
const int   port = 80;                    // Server Port
const int   watchdog = 5000;              // Watchdog frequency
unsigned long previousMillis = millis();

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  unsigned long currentMillis = millis();

  if ( currentMillis - previousMillis > watchdog ) {
    previousMillis = currentMillis;
    WiFiClient client;

    if (!client.connect(host, port)) {
      Serial.println("connection failed");
      return;
    }

    String url;
    url += "R1";

    client.print(url);
  }
}

```

---
Tags: esp8266
---


title: U8glib funny problem

text:
# Question
Title: U8glib funny problem
I have strange problem with u8glib library. I have code:

```
void void_Menu_draw_func_men()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_func_men();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}

void Menu_draw_func_men()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(30, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

  Serial.println("func md");//just for check...

}

```

And oled display shows only cursor and I can move that cursor as I change menu\_pos value. **But no letters or values are printed on screen.** Only cursor...

If I copy and paste only code from void Menu\_draw\_func\_men(); to other part of my program:

```
void void_Menu_draw_test_man()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_test_man();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_test_man()
{

  u8g.setFont(u8g_font_6x13);   //replace this dwo lines
  u8g.drawStr(0, 0, "wykonywanie tefsdfs man...");

}

```

Everything works perfect... I was trying to change void name, and I don't know where is problem... This is on Arduino Uno; I have 66% used of program memory, and 60% used of dynamic memory. Maybe you have some idea?...

# Answer
Your `void_Menu_draw_test_man()` function checks `menu_redraw_required`

Does your other part of the program update that variable? Do you call `void_Menu_draw_test_man()` from the `loop()` function?

It may help if you show the complete code, rather than small segments, since there are variables, such as `menu_redraw_required`, which are not changed anywhere in what is visible.

Note also that u8glib is no longer updated in favor of u8g2
> 1 votes

# Answer
`menu_redraw_required` is in every code segment, but all segments are in while loop, there is no chance to update `menu_redraw_required` in different part code... My code is quite big now... but, when I enter to `Menu_draw_func_men()`, cursor is turned on, I can move it. I also add `Serial.print();` to be sure that I enter to this `void Menu_draw_func_men();`. And I have always receive in console, a confirmation.

This is how I enter to selected screen from main menu:

```
if (digitalRead(KEY_SELECT) == LOW)
  {
    in_mmenu = false;

    switch(menu_current)
    {
      case 0:
        menu_redraw_required = 1;
        key_choose();
        break;
      case 1:
        menu_redraw_required = 1;
        test_auto();
        break;
      case 2:
        menu_redraw_required = 1;
        test_man();
        break;
      case 3:
        menu_redraw_required = 1;
        pot_read_menu();
        break;
      case 4:
        menu_redraw_required = 1;
        other_options(); **//previously i was function_menu**
        break;
    }

```

All screen works properly on almost the same code, only last screen on menu have problem...

See pictures how it looks. I also add code to "wybor klucza" menu. Just print part.

How I enter to void\_Menu\_draw... works fine in others screens. Just small part for entering methode.

```
 if(digitalRead(KEY_NEXT) == LOW)
{unit++; if(unit >= UNIT_ITEMS + 1)
{unit = 1;}
menu_redraw_required = 1; void_Menu_draw_keyMenu(); delay(200);}

```

and

```
void void_Menu_draw_keyMenu()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_keyMenu();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_keyMenu()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(30, 0, "Wybor klucza");
  u8g.drawStr(15, 15, "Zespol:  "); u8g.drawStr(60, 15, menu_unit_num[unit - 1]);
  u8g.drawStr(15, 30, "Numer mod:  ");  u8g.drawStr(78, 30, menu_mod_num[module - 1]);
  u8g.drawStr(8, 50, "Modul to 2 silniki!");
  if(menu_pos == 0 && in == false){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1 && in == false){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  if(menu_pos == 0 && in == true){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(148); u8g.enableCursor(); u8g.setCursorPos(110,20);}
  if(menu_pos == 1 && in == true){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(148); u8g.enableCursor(); u8g.setCursorPos(110,35);}

}

```

I show you 2 more codes. There are the same, this one void\_Menu\_draw\_test\_man works, this one Menu\_other\_options not. Notice that I change name from functions\_men to other\_option, just to be sure that name don't cause this issue. I aleso update u8glib to last version. I try use u8g2 library but i will have to change almost everything...

```
void test_man()
{
  menu_redraw_required = 1; void_Menu_draw_test_man();
  while(digitalRead(KEY_BACK) == HIGH)
  {
    if(digitalRead(KEY_PREV) == LOW){menu_pos = 1; menu_redraw_required = 1; void_Menu_draw_test_man(); delay(200);}
    if(digitalRead(KEY_NEXT) == LOW){menu_pos = 0; menu_redraw_required = 1; void_Menu_draw_test_man(); delay(200);}
  }
  menu_redraw_required = 1;
  u8g.disableCursor();
  in_mmenu = true;
}

void void_Menu_draw_test_man()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_test_man();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_test_man()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(40, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

}

```

and second

```
void other_options()
{
  menu_redraw_required = 1; void_Menu_other_options();
  while(digitalRead(KEY_BACK) == HIGH)
  {
    if(digitalRead(KEY_PREV) == LOW){menu_pos = 1; menu_redraw_required = 1; void_Menu_other_options(); delay(200);}
    if(digitalRead(KEY_NEXT) == LOW){menu_pos = 0; menu_redraw_required = 1; void_Menu_other_options(); delay(200);}
  }
  menu_redraw_required = 1;
  u8g.disableCursor();
  in_mmenu = true;
}

void void_Menu_other_options()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_other_options();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_other_options()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(40, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

}

```
> 0 votes

---
Tags: arduino-uno, u8glib, print
---


# Question
Title: Timer interrupt library for new Arduino based on MCU SAMD21
I'm looking for a timer interrupt library for the new Arduinos based on MCU SAMD21.

I want to wake up periodically the MCU form sleep state, do some task and go sleep again. Using one timer interrupt Arduino wakes up. For new Arduino MKR family.

Do you know a library to do this?

# Answer
> Do you know a library to do this?

it is generally very difficult to find a library that does precisely what your application wants. in fact, the purpose of a library is so that it is generic enough for you to tailor it for your specific application.

in this particular case, what you wanted to do is quite simple:

1) read through the datasheet;

2) figure out how the timer works;

3) figure out how the power management works;

4) configure timer isr to wake up the mcu periodically; an overflow isr is typically all you need;

5) run the task directly in the isr if is it short or set a flag for its execution in the loop;

6) upon completion, put the mcu to sleep.

all you need is to tackle the little steps above and you will get it done in no time, and learn a ton about your device.

device datasheet is the best friend of any embedded engineer, not the worst enemy.
> -1 votes

---
Tags: samd21g
---


# Question
Title: Which GSM-shield is most efficient for GPRS communication?
I tried Google, I tried a bunch of forums and I searched here. This question needs a final answer:

**Which GSM-shield is most efficient for GPRS communication?**

Since Arduino is the amateurs best friend for home automation and IoT, an "efficient" shield has a very low power consumption.

I am currently developing a system that collects some data from different sensors at a place far, far away, with limited access to power (e.g. it has a very small solar panel and a battery). It is also in pocket-size which makes a car battery a bad option.

Anyway, this specific device reads these sensors every 20 minutes, and if there's a deviation since the previous reading it starts the GSM module to send the new data to my API.

**SMS and call features are of absolutely no interest at all.**

Since these GSM-power-absorbing-current-eating-devils really like power I must think outside the box and compare different alternatives. So besides the primary question in this post, is there any way you can limit the power consumed, for example by limit the connection speed or anything like that? I'm using a M590 module at the moment, and that beast can eat around 2A if it's hungry.

Thanks in advance :)

# Answer
Three main things come to mind here...

**Overall hardware power consumption**: if you can make the arduino sleep for those 19ish minutes and are willing to do some of the things below/linked. Adding a RTC module using the alarms to trigger a GPIO to wake the arduino might be something depending on your hardware options as well.

**Software / clock speed / timing**: having the perfect code will make all the difference here as well. if your test code takes say 30 seconds to wake up, read the sensors, arrange the data, wake up gprs and transmit then fall asleep again. that might be pretty good. But say for example FONA shields have a 7second wake up.. This time can be used to sample sensors and arrange the data. Then transmit straight away when it wakes up.. could save a few seconds. also switch it off asap before any other code n so on.

**GPS/GPRS Reception**: If you can establish a connection quickly, you will be able to put it all back to sleep quicker and draw less power. Also possibly pre-select your providers baud rate to stop it trying and waiting.

As for point 1 above,

If you are powering it via the DC jack, then it is simply using a regulator (at least on the arduino side) that is not efficient (7805)...

So one suggestion is to get a 5v switching power supply and power it via the header pins or cut/splice a usb cable. this could gain you about 20% give or take.

Finding power hacks and running mini arduino's and alternatives can get you down even lower on power consumption.

I'm not going to give references from these listings, there just a quick few results. but basically from memory and glance its a case of removing resistors/regulators/redirecting/modifying/all that stuff and then also some software hacks along with changing the clock rate as well.

https://playground.arduino.cc/Learning/ArduinoSleepCode

http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/

https://learn.sparkfun.com/tutorials/reducing-arduino-power-consumption

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

https://www.hackster.io/techduino/reducing-arduino-power-consumption-9bcaf1

**Atmega328 with minimal circuit schematics**
> 1 votes

# Answer
GSM, by its very nature, is power hungry. Even the most "efficient" one will blow your power budget many times over. Since everything on GSM goes down the same digital transmission channel there would be no real difference between one with call and SMS and one without. It's all just data at the end of the day.

That said, the most efficient GSM module is one that consumes absolutely now power. And that is, at least for most of the time, perfectly possible. By making the Arduino control the power supply to the GSM modem it can be literally turned off until an update is needed to be sent. Worst case that is on for maybe a minute (give it time to register on the network and what have you) and then off for 19 minutes. That's only on for 5% of the time - less if there isn't a change since the last time, of course.
> 1 votes

---
Tags: power, gsm
---


# Question
Title: Loop one specific case inside of a switch
I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?

Code:

```
const int ledrood = 9;
const int ledgroen = 10;
const int ledblauw = 11;
const int buttonPreset = 2;
const int buttonMix = 4;
float sensorWaarde = 0;
int switchtel = 1;

int roodval;
int groenval;
int blauwval;
int buttonState = LOW;

void setup() {
Serial.begin(9600);
pinMode(ledrood, OUTPUT);
pinMode(ledgroen, OUTPUT);
pinMode(ledrood, OUTPUT);
pinMode(sensorWaarde, INPUT);
pinMode(buttonPreset, INPUT);
pinMode(buttonMix, INPUT);

}

void loop() {
int sensorWaarde = analogRead(A0);
buttonState = digitalRead(buttonMix);
if (buttonState == HIGH) {

delay(200);
switch (switchtel) {
  case 1:
  roodval = 255;
  roodval = sensorWaarde / 4;

    groenval = 0;
    blauwval = 0;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println(roodval);
    switchtel = switchtel + 1;
    break;

  case 2:

    roodval = 0; // cyaan
    groenval = 255;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("2");
    switchtel = switchtel + 1;
    break;

  case 3:

    roodval = 255; // magenta
    groenval = 0;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("3");
    switchtel = switchtel + 1;
    break;
    switch (switchtel) {

    }
   }
 }
}

```

# Answer
> 1 votes
You need to split your cases into multiple parts.

For example, you have a case which sets up a mode, and a case that runs a mode, and if needed a case that finishes a mode.

For example:

```
switch (mode) {
    case 0: // Idle
        break;
    case 1: // Start - do whatever to set up the mode here
        redValue = 100;
        greenvalue = 200;
        mode = 2; // Switch to the next case
        break;
    case 2: // Run - this is the bit that repeats
        if (digitalRead(3) == HIGH) {
            mode = 3; // Finish it
        }
        // Do whatever for each loop here.
        break;
    case 3: // It is finished.
        redValue = 0;
        greenValue = 0;
        // etc.
        mode = 0; // Or whatever you want to do next
        break;
}

```

The key thing here is that case 1 is equivalent to a mini `setup()` and case 2 is equivalent to a mini `loop()`. You switch to case 1, which does the setup, and that case then switches to case 2, which it stays at until you tell it otherwise. That case will keep getting executed until you tell it to move to another case.

# Answer
> 0 votes
> I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?

not sure why it needs to be anything more complicated than this:

```
  if (isPressed2x(btn)) do_something(); //if button is pressed twich, execute do_someting()

```

there are lots of ways to implement isPressed2x(). the simplest would be to use a static variable to keep track of it:

```
char isPressed2x(uint8_t btn) {
  static char cnt=0; //button press counter
  if (isPressed(btn)) {  //button is pressed
    cnt+=1; //increment counter
    if ((cnt&0x01) == 0) return 1; //button has been pressed twich
  }
  return 0; //button not pressed, or not pressed twice
}

```

similarly, isPressed(btn) can be implemented, with or without debouncing.

the key is to break down any task into small, simple and well defined blocks so when re-assembled together, those small, simple and well defined blocks can perform tasks as complicated as you wish them to be.

the alternative is to jumbo all of them into one routine, making it hard to understand, hard to debug and hard to port.

---
Tags: switch
---


title: Pointers, libraries, and arrays:

text:
# Question
Title: Pointers, libraries, and arrays:
I'm trying to pass variable addresses to functions/methods within a custom library that should change the values at the specified addresses. However, I think I'm missing something as it's taking me ages to tweak things just to get it to compile, let alone gather some useful information from it.

Note: I've not tested the code as I'm focused on understanding (1.) through to (5.) and is just a quick example of the current pipeline:

Main.ino

```
#include <customLibrary.h>

CustomLibrary cLib();

byte someByte[6];
unsigned int theAddress;

setup(){};

loop(){

    // (1.)
    theAddress = &someByte; // normally need this here, or before setup(), for it to work.

    cLib.setValues(theAddress);

    // because:
    // cLib.setValues(&someByte);
    // doesn't seem to work
};

```

customLibrary.h

```
#ifndef CustomLib
#define CustomLib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class CustomLibrary {
    public:
        CustomLibrary();
        void setValues(unsigned int theAddress); // (2.)
    private:
};
#endif

```

customLibrary.cpp

```
#include <customLibrary.h>

CustomLibrary::CustomLibrary(){
};

void CustomLibrary::setValues(unsigned int theAddress){ // (3.)

    byte _someNewValues[6] = {a,b,c,d,e,f};

    // Assign the variable from _someNewValues[_x] to (theAddress + _x)
    int _x = 0;
    for(unsigned int i = theAddress;i < (theAddress + 6);i++){ // (4.)
        // (5.)
        _x++;
    };

};

```

(1.) - Feels like it should be simpler.

(2-3-4-5.) - I have left out any "\*" and "&" hoping that someone can provide the preferred way of doing this, or provide a better solution as it's taking far too long to get this working with everything else leading me to think I'm missing something basic.

There are some excellent tutorials out there which I have been following with great success, but, only when all the pointers are within the same file. Once I try and use them in a library it's a constant headache at the moment and I don't understand it enough to know what's wrong.

Need to go before I can proof-read and check it, but I think it's all there. I'll be back later/tomorrow if there's anything that needs clearing up.

Edit: I didn't know who to mark for the answer as both @dannyf and @KIIV answered perfectly. I considered marking the answer based on the time it was posted, but decided instead to let @dannyf have it as his reputation was only 1.

Thank you both! Much appreciated!

# Answer
> 1 votes
somebyte itself is a pointer. so "&somebyte" doesn't make sense.

instead, use "&somebyte\[0\]" (or "&somebyte\[5\]" if you want an offset), or "somebyte" (or "somebyte + 5" if you want an offset).

arrays are actually pointers.

# Answer
> 0 votes
I'm not sure how it could ever work for you in both variants. There is simple example how to work with arrays:

```
class CustomLibrary {
    public:
        CustomLibrary() {;}

        void setValues(byte * address);

        template <class T, int SIZE>
        void setValuesTemplate(T(&bytes)[SIZE])
        {
          for (int8_t i=0; i<SIZE; ++i)
          {
            ++bytes[i]; // just increment the value
          };
        }
 };

void CustomLibrary::setValues(byte * address){
    byte somethingNew[] = {'a','b','c','d','e','f'};

    for (int8_t i=0; i<6; ++i)
    {
      address[i] = somethingNew[i];
    }

};

CustomLibrary lib;

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

void loop(){
  byte someByte[6] = {'z','y','x','w','v','u'};

  Serial.println("Values before:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  lib.setValuesTemplate(someByte);

  Serial.println("Values after templated method:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  lib.setValues(someByte);

  Serial.println("Values after method:");
  for (byte b : someByte) Serial.print(b, HEX);
  Serial.println();

  delay(5000);
};

```

It's in single .ino file for testing purposes. If you want to use templates, you have to place template method definition into the header file (it doesn't have to be inside class definition, it just have to be in header file).

Range based for loop was introduced by C++11 standard (suported by Arduino IDE for a while - since about version 1.6.5?). It's realy handy on static arrays (like int arr\[\] = {......}), so you don't have to care about it size. But it's basically everything it can do on `avr-g++`, as there are no containers, no iterators and so on.

Templates are quite huge topic on C++, in this case it's working with T as array element type and SIZE as its size (it won't work on pointers, it only works on static arrays).

I could've use range based for loop in int too:

```
    template <class T, int SIZE>
    void setValuesTemplate(T(&arr)[SIZE])
    {
      for (T& item : arr) // it must be a reference type, if you don't want to change local value only
      {
        ++item; // just increment the value
      };
    }

```

And I didn't even needed that class T part. If you need byte array only:

```
    template <int SIZE>
    void setValuesTemplate(byte(&arr)[SIZE])
    {
      for (byte& item : arr)
      {
        ++item;
      };
    }

```

But there is a downside for using templates -\> there will one instance of that method for each type/size. But it's possible to use it as a "proxy" and pass it to function that expects just pointer and the size.

---
Tags: arduino-ide
---


title: A clarification needed about the HC-05

text:
# Question
Title: A clarification needed about the HC-05
I have just got a new pair of HC-05 Bluetooth modules. I am working on a simple project. I'm trying to move two servo motors using two potentiometers. I followed a simple tutorial to move one servo, and it worked successfully.

How to make the same thing with 2 potentiometers and two servos?

UPDATE:

I have successfully managed to write down something that get to read values from two potentiometers, but I'am still facing problems with the slave part. Can't figure out the problem.

(Master)

```
//Master
int potValuePins[] = { A0, A1 };
void setup() {
  Serial.begin(9600); // Default communication rate of the Bluetooth module
   for (auto pin : potValuePins) {
     pinMode(pin, INPUT);
   }
}

void loop() {
 for (auto pin : potValuePins) {
   Serial.write(pin); // Send the pin number
   Serial.write(analogRead(pin)); // Send the pin value with a trailing
 newline as a delimiter
   int value=analogRead(pin);
   Serial.print(" Pin is: ");
   Serial.print(pin);
   Serial.print("\t");
   Serial.print("Value is: ");
   Serial.println(value);
   }
 }

```

(Slave)

```
//Slave
#include <Servo.h>
Servo myServo1;
Servo myServo2;

void setup() {
Serial.begin(9600);
myServo1.attach(9);
myServo2.attach(10);
}

void loop() {
if (Serial.available()) {
 char input[3];
 Serial.readBytes(input, 2);
 int pin = input[0];
 int angle = input[1];
 Serial.print("the pin:");
 Serial.print(pin);
 Serial.print("\t");
 Serial.print("the angle:");
 Serial.println( angle);

 switch (pin) {
  case A0:
    myServo1.write(angle);
    break;
  case A1:
    myServo2.write(angle);
    break;
  default:
    Serial.println("Unknown value");
    break;
   }
  }
 }

```

# Answer
Looking at the example you linked to, the "communication" between the two ends is just writing a (byte) value between `0` and `255`, and reading that on the other end.

One simple (out of many possibilities) to extend this to handle a set of two is just to send 2 bytes in sequence, with the first byte being an identifier of which servo you are denoting.

Where the example master code shows:

```
// Reading the potentiometer
potValue = analogRead(A0);
int potValueMapped = map(potValue, 0, 1023, 0, 255);
Serial.write(potValueMapped); // Sends potValue to servo motor

```

You instead write:

```
// Reading the potentiometer 1
pot1Value = analogRead(A1);
int pot1ValueMapped = map(pot1Value, 0, 1023, 0, 255);
Serial.write(1);
Serial.write(pot1ValueMapped); // Sends pot1Value to servo motor

// Reading the potentiometer 2
pot2Value = analogRead(A0);
int pot2ValueMapped = map(pot2Value, 0, 1023, 0, 255);
Serial.write(2);
Serial.write(pot2ValueMapped); // Sends pot2Value to servo motor

```

And on the slave side, where the example has:

```
if (Serial.available() > 0) { // Checks whether data is comming from the serial port
  state = Serial.read(); // Reads the data from the serial port
}
// Controlling the servo motor
myServo.write(state);

```

You have to separate out the two possible choices:

```
if (Serial.available() > 0) {
  servo_num = Serial.read();
}
if (Serial.available() > 0) {
  state = Serial.read();
}

switch (servo_num) {
  case 1:
    myServo1.write(state);
    break;
  case 2:
    myServo2.write(state);
    break;
}

```

Note that you'll also have to declare the servo\_num variable, and instantiate two of the Servo objects. The code above is just a guide.

The simple expansion above is *not* robust, as it's possible that the 2nd byte is not received by the time the 2nd `Serial.read()` is called, and then that byte would be caught next time around the `loop()` by the first `Serial.read()` call and you'd be out of sync. But hopefully, this shows the general concept of how to start developing a protocol that is more complex than just single values.

**Edit:** What's probably happening is the system is getting out of sync. As I noted, it's not a robust protocol, but I think you may now understand the idea.

You can re-map the servo values to go from 2-255, rather than 0-255, and set the `servo_num` to either `0` or `1`. In the slave, if you get a number `<2`, then it's a servo selector, otherwise it's a servo value. but then you lose the ability to set the servo to 0 or 1.

Also, you may want to space out the master sending the values, as you are likely sending data faster than the servo could respond. You could put a `delay(100)` or something in the `loop()` function, or change your code to use a `millis()`-based state machine (see the "BlinkWithoutDelay" Arduino example).
> 1 votes

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


title: OV7670 Camera Module - wrong pins?

text:
# Question
Title: OV7670 Camera Module - wrong pins?
I would like to ask you some helpful informations.

Recently I bought an OV7670 Camera Module. Unfortunately, this item is not compatible with any tutorial I found in dozens and dozens of sites.

It has 18 pins with these signs:

```
3.3v   GND
SCL    SDA
VS     HS
PCLK   MCLK
D7     D6
D5     D4
D3     D2
D1     D0
RESET  PWDN

```

I aint noticed these pins on any OV7670 Camera in any site of tutorial, like youtube or arduino.cc or many others at google searching. The most comon OV7670 Cameras I found in tutorials have SIOC SIOD instead of SCL SDA, HREF instead of HS and XCLK instead of MCLK. Did I bought a fake or what do you think? Please, if any of you, knows how to make it conect or have any useful link, I will apreciate to inform me. Thank you all for your time.

# Answer
> 3 votes
They are actually named in a different manner.

Your camera module has i2c interface.

SIOC is nothing but Serial Input Clock , same as SCL - i2c clock

Similarly , SDA and SIOD are the same - i2c data

HREF and HS are the same too - Hsync signal

MCLK and XCLK are the same too - system clock

Here is a useful link:

https://www.google.co.in/amp/www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/%3famp\_page=true

Cheers !

---
Tags: i2c
---


title: Arduino FM transmitter

text:
# Question
Title: Arduino FM transmitter
I am wondering if it's possible to transmit on all frequencies at once using this module.

I know it's illegal to take over regular stations when others are trying to listen but I'm only planning to use it for short range (less than the length of my house).

# Answer
> 2 votes
No, this is a receiver only, not a transmitter.

# Answer
> 0 votes
> I am wondering if it's possible to transmit on all frequencies at once using this module.

it is definitely possible to transmit on all frequencies at once ***NOT*** using that module: square waves are a combination of all sorts of frequencies and your arduino is good at producing that.

---
Tags: sensors
---


title: Uploading Lua code to Arduino

text:
# Question
Title: Uploading Lua code to Arduino
I have Arduino UNO board. Can I upload programs written in Lua? I wrote a code for simple home automation using relays to control lights and tried to upload it to my Arduino board, I get error code of "Error compiling for board Arduino/Genuino Uno"? What does this mean?

This is the code I used:

```
var("Switch", "ME.BI21")
var("Relay", "ME.BO21")
var("RelayState", "ME.BO41")

RelayState = 1

Relay = Switch

if (Relay == 1 then){
  print("The Relay is ON")
}
else{
  print("The Relay is OFF")
}
end

```

# Answer
The Uno can’t run Lua code. The ESP8266 modules like the Wemos D1 or NodeMCU can, with the right firmware.
> 4 votes

---
Tags: arduino-uno
---


# Question
Title: Uploading Arduino code, OTA, via connected ESP8266-12E running Esp-Link
# 1. A short preliminary introduction

I'm deploying a small network of three MEGAs connected trough an RS-485 bus. Each MEGA is connected to up to 16 push-buttons (wall-mounted) and two relay-module (2 x 8-SSR; located close to the MEGA). The objective is to manage the lighting of the whole house (aka: "switching 'ON' the relay 'R1' when the push-button 'PB1' is pressed").

At the moment, everything runs fine: MEGAs are able to 'broadcast' events along the BUS and each node is able to properly react to both locally-generated events, as well as events coming from the BUS.

Above system is running from a couple of weeks and... I'm starting struggling about "updating" the code: having around 40 push-buttons and 35 relay distributed on the three nodes, chances are "high" that some "tuning" (aka: "trial-and-error") is required.

Things get even worse when... you start enjoying the powerfullness of the system (aka: "Hai! What about turning-OFF *ALL* the lights of the main-floor by long-clicking PB1?"). This, obviously, requires a "patch" to the code and a related "upload" the the MEGAs. And so on: *LOTS* of uploads :-(

Having some ESP8266-12E modules sitting around, I decided to investigate the possibility to use them, as a sort of "WiFi gateway": reaching them via WiFi; sending them the new code; asking them to kindly "upload" the code to its own MEGA that is phisically connected via USART.

As mentioned in lots of places (including a comment on this other question) I decided to test the ESP-Link firmware.

As I'm having problems interconneting the MEGA with the ESP, here I'm, asking this community :-)

# 2. Hardware involved

As for the Arduino side, I'm using a common MEGA (a Chinese one, BTW), so I don't get into details, here, 'cause there is nothing special.

As for the ESP8266, strictly speaking I'm **NOT** using a straight ESP8266-12E, but a Development Board. Actually, I'm using a **Lolin NodeMCU v3**, this, that you can see here below:

My plan is to connect *DIRECTLY* the USART of the ESP to the USART of the MEGA. This raises some problems, described below.

# 3. GPIO voltage issues

One of the very first issues that I addressed relates to GPIO voltage. While it's **crystal clear** that:

* GPIO PINs, on MEGA, are 5V based and, as such:

+ the TX on the MEGA side will send out a 5V current;
    + the RX on the MEGA side expect to receive a 5V current;
* GPIO PINs, on ESP8266-12E, are 3.3V based and, as such:

+ the TX on the ESP side will send out a 3.3V current;
    + the RX on the ESP side expect to receive a 3.3V current;

I still am **NOT** able to understand if this is --in my case-- a real problem. I'm saying this, 'cause:

1 - Transmission from ESP to MEGA should **NOT** be an issue, as the HIGH/3.3V signal coming in into MEGA should still be recognized as HIGH, from the MEGA, as it's higher than 2.5V;

2 - Transmission from MEGA to ESP **COULD** be a problem, if PINs on the ESP are **NOT** 5V tolerant

As for point 2) I deeply searched all-around and found plenty of contradictory assertions. In the end, I would like to "trust" the Hackaday article: "Ask Hackaday: Is The ESP8266 5V Tolerant?" as, in several comments, reports various semi-official statements (like a message from Expressif CTO sent from a Facebook account or a message from an "internal" of Espressif) asserting that: "*Yes! GPIO PINs on the ESP8266-12E are 5V tolerant*"). So, again, I decided: "Ok! Let me go! Let's connect the two, **straight**, without a level-shifter". And yes: I know that with such a decision, I'm taking some risks and... can "burn" something, especially on the ESP side.

So, here's my:

> **Question 1: How much I'm "brave" in connecting straight-away the TX/RX of the ESP8266 to the RX/TX of the MEGA? Would you suggest it? And why?**

# 4. Ground issues

While working on my RS-485 bus, I learnt that it's critically important to have a "common ground" among my MEGAs. That sounds understandable... as otherwise there is **NOT** a common reference to evaluate the same signal among different devices.

So, now that I've **TWO** equipment and I'm giving them POWER via two distinct sources (MEGA directly connected to my PC; ESP connected to another PC), I'm wondering if:

> **Question 2: Do I need to connect a GND PIN on the MEGA to a GND PIN on the ESP? Do the two boards, to properly operate, need a shared/common GND?**

# 5. RESET line on the MEGA

In order to trigger the flashing of the new sketch on the Arduino side, the ESP need to RESET it. To do this, the ESP need to be connected to the RESET line of the MEGA. The RESET PIN is clearly shown on the MEGA so the connection is really easy.

Nevertheless, after some preliminary test... it looks to me that the ESP is **UNABLE** to reset the MEGA.

This lead to:

> **Question 3: Is, an ESP8266-12E OUTPUT PIN (operating at 3.3V), able to properly handle the RESET PIN of the Arduino?**

I'm asking also 'cause based on the official documentation of the MEGA I read:

```
Reset PIN: Bring this line LOW to reset the microcontroller.
Typically used to add a reset button to shields which block
the one on the board.

```

# 6. Physical connections

In the official documentation of ESP-Link I read about potential problems generated (to Arduino) by the ESP as, right after a reboot of the ESP, it send out on TX some debug messages. Due to the USART connections, such characters transmitted by the ESP to the MEGA are received by the MEGA. It's not clear, to me, WHY this could be a problem. Anyway, the same documenation say: "*...If you need to avoid this, you can configure esp-link to swap the uart pins...*"

So, in the end, I connected the two devices following the official doc, with USART PINs swapped:

* GPIO13: connect to TX of microcontroller
* GPIO15: connect to RX of microcontroller and use a pull-down to ensure proper booting
* GPIO12: connect to RESET of microcontroller
* GPIO14: connect to ISP of LPC/ARM microcontroller (not used with Arduino/AVR)
* GPIO0: either a 1k-10k pull-up resistor to 3.3v or a green "conn" LED via a 1k-2.2k resistor to 3.3V (indicates wifi status)
* GPIO2: either a 1k-10k pull-up resistor to 3.3v or a yellow "ser" LED via a 1k-2.2k resistor to 3.3V (indicates serial activity)

As I don't need (currently) any LED feedback, I haven't used GPIO0 and GPIO2. Also, as I don't have an ARM, I haven't used GPIO14.

With help of this mapping I ended with following connection:

# 7. Results (...and problems)

To test what's going on, I've uploaded to Arduino a simple sketch that turn ON/OFF the internal LED every second and dump an increasing counter on the console. Here it is:

```
unsigned long counter;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  counter = 0;
}

void loop() {
  Serial.print("[");Serial.print(counter);Serial.print("] ");
  Serial.println("on");
  digitalWrite(13, HIGH);
  delay(1000);
  Serial.print("[");Serial.print(counter);Serial.print("] ");
  Serial.println("off");
  digitalWrite(13, LOW);
  delay(1000);
  counter++;
}

```

so, from the console output, I can see if Arduino is correctly operating and if it's restart.

On the ESP-Link side, I've configured the PIN as shown below:

With all the above in place, up to know, I've been experimenting the following:

* If I connect ONLY the RESET line and the TX/MEGA to the D7/GPIO13/ESP, I can succesfully reset the Arduino from the ESP-Link web interface and I can see the "console" of the MEGA (I can be sure of succesfully reset, as the counter in the Arduino console, restart);
* Above apply:

+ when the MEGA is powered via a full-USB connection from a PC;
    + when the MEGA is connected via a power-only USB cable from the PC;
    + when the MEGA is powered via a USB-power-bank, but in this case *ONLY* if thereis a shared-GND between ESP and MEGA
* As soon as I connect the D8/GPIO15/ESP to the RX/MEGA, everything still work, but up to next reset. If I "reset" the Arduino via the ESP-Link web-interface, it reset but.... never boot (I'm sure, as the "blinking" never start).

So, the last question:

> **Question 4: What's wrong with above testbed? Why the D8/GPIO15/ESP disrupt the boot process on the MEGA? I've swapped the UART PINs exactly to avoid this... as far as I understood...**

Sorry to be so long but... I think that details matter :-)

# Answer
I have successfully used ESP-link firmware with esp-01 and Arduino Pro Mini.

For the ESP-01 and Pro Mini, you can find out more on my blog post. I have connected GPIO 0 of ESP-01 to reset pin of Pro Mini and the Pro Mini can be reset using ESP-Link the web interface. I try to use the same voltage level for both micro-controllers and a single power source. For my example, the Pro Mini is driving the ESP-01 and of-course sharing the common ground.

To answer your questions.

1. I try not do that as ESP has stated that all the GPIO pins are only 3.3v compatible.
2. Yes, both controller must share a ground.
3. My understanding is RESET is an output pin. If connected to ESP8266, there is a possibility that the ESP will be damaged.
4. Not sure if your wiring is correct. You may reference my diagram on how the ESP and Arduino Pro Mini is wired up. For your case, I will recommend a level shifter to prevent damaged to your ESP.
> 1 votes

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


# Question
Title: How to connect Arduino 5v pin with multiple things?
I am trying to connect a Bluetooth module and a gas sensor to Arduino.

I read the guides for the HM-10 and MQ-2 and they both need to use the Arduino's 5v pin. I did a lot of searching but I could not find a proper example.

I would like you to give me a link to an example that uses the 5v pin for multiple modules. It would be nice if the circuit configuration was included.

# Answer
5V is just 5V. It's not a signal, it's just a voltage level. If you need to connect multiple things to it then just connect multiple things to it. If that means connecting wires together then so be it.

Yes, you can use breadboards for it, but that's pretty wasteful if all you want to do is connect a few 5V wires together. It's simpler just to strip the ends and twist them together. Maybe add some tape to insulate them so you don't get accidental short circuits.
> 5 votes

# Answer
The simplest way is to just use a breadboard to connect your devices to your Arduino:

---

I can't read Chinese, so I can't check the specifications of these particular devices, but you need to be aware of the power limitations on your Arduino.

The maximum total current you can draw when the device is powered via external power supply is 1A for the Arduino Uno, 800mA for the Due and 500mA for the Nano. Check the specs for your board on the Arduino site.

Arduino-compatible devices may vary - check the specs for the device you're usiing.

---

Note: If you're not powering your board via USB, the total 5V current limit coming out of the Arduino is limited by the voltage regulator on your particular board, and/or your input power supply (whichever provides less power).
> 4 votes

---
Tags: arduino-uno, arduino-due
---


title: Arduino Micro vs. Pro Micro

text:
# Question
Title: Arduino Micro vs. Pro Micro
What are the differences between the Arduino Micro and Pro Micro?

# Answer
I actually think you are meaning what is the difference between the Arduino Mini and the Arduino Pro Mini, since there is no such board as the *Arduino Pro Micro*. However there is a board called the Arduino Micro and also the Sparkfun Pro Micro, so this answer will look at all four.

Arduino Mini

Arduino Pro Mini

Arduino Micro

(Sparkfun) Pro Micro

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

**Memory**
All four have 32KB of Flash and 1KB of EEPROM
Both Minis have 2KB of SRAM where as both Micro boards have 2.5KB

**Digital I/O**
Both Minis have 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
The Pro Micro has 12 (5 PWM pins)

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

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

**Clock**
All 16 MHz
(Some 3V3 variants run at 8MHz)

**Power**
Arduino Mini: 7-9 V
Arduino Pro Mini: There are two version of the Pro Mini. One runs at 3.3V and 8 MHz, the other at 5V and 16 MHz. 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)
Pro Micro: can accept voltage up to 12VDC

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

# Answer
sa\_leinad gave a detailed answer.

a simplified version would be on the chips used: 328 vs. 32u4.

the 32u4 is a superb chip if you are into mixed signal mcu. the ability to put a programmable gain and differential analog input into the adc module at such a low price point is simply superb.

unfortunately, not many boards route out AIN0/AIN1 pins.
> 0 votes

---
Tags: arduino-micro
---


# Question
Title: ESP8266 only executes Sketch after switching on/off CH_PD pin
I started a new project with an ESP8266-01 module. I want to use it as stand-alone circuit to send an Email at the press of a button.

The wiring is:

* VCC - 3.3v VCC
* CH\_PD - 3.3v VCC
* GND - GND
* GPIO\_2 - Push down button (internal pullup)

I've the sketch (Arduino IDE), I've upload it and it essentially works. However:

* If I call the `sendEmail();` method inside the `void setup(){}`, it works like a charm.
* If I add an push down button on Pin #2 (GPIO\_2) it only works if I previously have removed VCC from the CH\_PD pin and reattached it again shortly after.

Now, I would bet I read something regarding (or similar) this situation a couple of days back, but I am unable to find it again, now that I need it.

Is there a solution for this or am I missing something?

Any help will be greatly appreciate it!

Thanks in advance!

# Answer
> 0 votes
Well, after literally spending hours trying to figure out what the heck is going on, I decided to test the setup with a ESP8266-12 NodeMcu, which is essentially the same but more resembling to an Arduino in that it has more in/out pins and it's better for testing.

On this platform I got a different behavior. I was able to send an Email by the push of the button but... only once. So apparently, contrary to what I believed, something was wrong with the code.

In the code there is this method, which essentially initiates the WiFi connection:

```
void initializeWifi(){

  WiFi.begin(WIFI, PASSWORD);

  // allow time to make connection
 while (WiFi.status() != WL_CONNECTED)  delay(5000);

  }

```

Somehow the `delay(5000);` didn't seem right as delay usually freezes the whole thing. When I commented out the line, everything worked as expected. With the NodeMcu as well as with the ESP8266-01.

However, I still have to figure out how to give time to the WiFi to connect without freezing out all together. Probably it's the time for `millis()`;

I hope this becomes useful to somebody else in the future.

---
Tags: esp8266, arduino-ide, wifi, sketch, wires
---