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

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

Version 1, 15114 Bytes for complete program:

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

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

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

Version 2, 15234 Bytes for complete program:

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

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

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

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

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

title: Storage usage of methods compared to copied code

Answers: 2

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

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

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

body:
It.... depends

A call to function involves a few things

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

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

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

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

What is best? It depends on your application.

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

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

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

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

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

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


body:
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.

[![NodeMCUPyFlasher][2]][2]
[2]: https://i.stack.imgur.com/OvCWt.png
[![im using ESplorer IDE][1]][1]
[1]: https://i.stack.imgur.com/pOCAE.png

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());
      }
    }

title: How to read data from client ESP8266-01?

Answers: 1

body:
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][1]

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);
      }
    }

  [1]: https://nodemcu-build.com/


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

title: Reset Arduino Uno R3

Answers: 2

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

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

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

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

If you want a blank code, just upload:

    void setup() {
    }

    void loop() {
    }


body:
I have a small problem with conversion from bool array to int. It is working fine until it comes to the 12th cycle of while. I don't know why but this is really weird.

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

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

And this is where I am using this function:

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

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

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

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

title: Conversion between boolean and int went wrong

Answers: 2

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

Like this.

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

You get the idea.

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

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


body:
How program Arduino with a FTDI cable/breakout_board via pins 0 (Rx) and 1 (Tx)?

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

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

title: Programming Arduino with FTDI via Tx and Rx pins

Answers: 1

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


body:
Beginner here.

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

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

Help is appreciated.

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

 1. On startup the Arduino is ready to recieve a button push.
    The relay is off (HIGH).
 2. Once the button is pushed:

    • The relay state is changed to LOW in order to turn it on

    • A green LED switches on.

    • A millis() based timer is switched on.
 3. If the user presses the button while the switch is on, the timer is reset to 0 and continues counting.
 4. If the on-time is going to end, a red LED starts blinking. Say in the last minute.
 5. As soon as the timer reaches the specified on-time:

    • The green LED switches off

    • The relay switches off
    • The system returns to step 1. and is awaiting a push.

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

    //CONSTANTS

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

    //VARIABLES

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

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

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

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

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

    }

    void loop(){

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

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

            buttonState = digitalRead(BUTTON_PIN);

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

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

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

            // Reset buttonState:
            lastButtonState = buttonState;
       }
    }

title: Button with switch timer and reset time function + LED feedback. What am I doing wrong?

Answers: 1

body:
Written and tested. I also included the red blinking led.

<!-- language: c++ -->

    //CONSTANTS

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

    //VARIABLES

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

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

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

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

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

    }

    void loop(){

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

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

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

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

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


body:
I'm trying to create a setup with which an Arduino UNO sends out a tweet (one random quote) every time a button is pressed. I want to use it as a Mailbox Watcher.

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

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

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

    #define DEBUG true

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

    #define BUTTON_PIN 8

    #define RX_PIN 10
    #define TX_PIN 11

    SoftwareSerial esp8266(RX_PIN,TX_PIN);

    Bounce button=Bounce(BUTTON_PIN, 5);

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

        pinMode(BUTTON_PIN, INPUT);

        initializeModem();

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

    void initializeModem(){

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

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

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

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

      }

    boolean buttonState(){

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

          return true;

        }else {
          return false;
          }
      }

    void loop() {

    if (buttonState()) {

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

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

        // Create HTTP POST Data

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

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

         //// envia   comando AT + cantidad de caracteres

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

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

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

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

    }

     //// rutina de depuracion via puerto serial

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

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

        long int time = millis();

        while( (time+timeout) > millis()) {
          while(esp8266.available()) {
            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
          }
        }

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

        return response;
    }

The setup works more or less as expected. It connects ok to the WiFi and so on, but it is only able to publish a tweet if it is not very long. As example, the quote on this example code will no be published whereas if it is half as long, it will be no problem.

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

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

Thanks in advance

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

AT+CIPSEND=302

  [1]: https://github.com/JhonControl/Arduino-IoT/blob/master/Esp8266_IoT_twiter.ino

title: Not long tweets published using ESP8266-01 with Arduino UNO

Answers: 1

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

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

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

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

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

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


body:
I see many ESP8266HTTPClient examples, pasting in a fingerprint from an outside website, but I want to _host_ an html page from the ESP8266 in AP mode using HTTPS.

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

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

title: HTTPS with ESP8266WebServer?

Answers: 1

body:
The ESP8266 just doesn't have sufficient CPU power to do this reliably.

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

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

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

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

  [1]: http://wiki.ai-thinker.com/_media/esp8266/docs/5a-esp8266_sdk_ssl_user_manual_en_v1.4.pdf


body:
I'm trying to implement a full-duplex communication between my ESP8266 and a socketserver running on my laptop. In concrete I need each of the devices to initiate communication whenever it needs to. The ESP is measuring temperature all the time and when the temperature changes, I want the ESP to transmit the new temperature to my laptop.
On the other side I want to transmit a command from my laptop whenever I want to know the actual temperature (even if the temperature has not changed).

Therefore I have a python server-script and a python client-script both running on my laptop (see scipts below).

In the loop function on my ESP I'm also running a server and a client (script below).

Sending commands from laptop-client to ESP-server works perfectly. Even at high rates and **for days** without any problem.

Communicating the other way around (that is sending from ESP-client to laptop-server) seems to work in general, but after numerous packages (usually a few hundreds) have been sent from ESP-client to laptop-server the communication fails and the laptop-server only receives empty byte-strings. After that has happened, also sending commands from laptop-client to ESP-server does not work any more temporarily.
When I shutdown the laptop-server, the ESP needs some time to "calm down" and will then continue working as usual.

Can anyone imagine what causes this behaviour? To me it looks like a buffer overflow or something like that.
I appreciate any help and hints about how to implement the desired functionality (do I actually need to run a server on both my laptop and the ESP?).

**Laptop-Server**:

    import socket
    import time

    # create a socket object
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    host = "0.0.0.0"
    port=1992

    # bind to the port
    serversocket.bind((host, port))

    # queue up to 5 requests
    serversocket.listen(5)

    try:
      while True:
        # establish a connection
        clientsocket,addr = serversocket.accept()
        try:
            data = clientsocket.recv(1024)
            print(str(addr),":  ",data)
            clientsocket.send("hi there, "+str(addr)+"\n")
            clientsocket.close()
        except:
            pass
    except:
      print(" !!! an exception occured !!!")
      serversocket.shutdown(socket.SHUT_RDWR)
      serversocket.close()

**Laptop-Client**:

    import os,sys,re,time,socket,threading,readline

    timeout=2

    HOST, PORT = "ESP-IP", 1991

    response=""
    def s_client(data):
        global response
        try:
            response='Error: received no response'

            # Connect to server and send data
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            sock.connect((HOST, PORT))
            sock.sendall(bytes(data + "\n", "utf-8"))

            # Receive data from the server and shut down
            response=str(sock.recv(1024), "utf-8")
        except ConnectionRefusedError:
            response='Error: connection refused by remote host'
        except socket.timeout:
            response='Error: connection timed out'
        finally:
            sock.close()
        return 1

    while True:
        try:
            print('  -->  '+s_client(input('_$ ')))
        except KeyboardInterrupt:
            break

**ESP-script** (containing server and client):

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

    IPAddress laptop_ip=(0,0,0,0);
    uint16_t TCP_port=1991;
    uint16_t TCP_remote_port=1992;
    WiFiServer TCPserver(TCP_port);
    WiFiClient client;

    void ESP_server(void){
      if (!client.connected()) {
        client=TCPserver.available();
      }
      else {
        laptop_ip=client.remoteIP();
        Serial.println("received request");
        int query_l=client.available();
        if(query_l>0){
          String query="";
          for (int nb = 0; nb < query_l-1; nb++){
            query+=(char) client.read();
          }client.read();
          Serial.print("received from laptop: ");Serial.println(query);
          //  Do something with query and return the result
          //  For simplicity I'm just returning a constant value
          client.write("command transmitted");
        }
      }
    }

    void ESP_client(String message){
      WiFiClient TCPclient;
      if (TCPclient.connect(laptop_ip, TCP_remote_port)){
        TCPclient.print(message);
      }
    }

    void setup() {
      Serial.begin(115200);
      WiFi.begin("MYSSID","MYPASS");
      Serial.print("connecting with WiFi  ");
      while(WiFi.status()!=WL_CONNECTED){
        Serial.print(".");
        delay(500);
      }Serial.println();
      TCPserver.begin();

      // wait until a command has been received from the laptop
      // ESP_server stores the remote (laptop) ip in laptop_ip
      while(laptop_ip==(0,0,0,0)){
        ESP_server();
      }
    }

    int temp=0;
    void loop() {
      // handle commands sent from my laptop
      ESP_server();

      //  here is a temperature meaurement returning the current temperature
      //  I've replaced it with a temperature generator
      if(temp<30){temp++;}
      else{temp=0;}

      // temperature has changed and needs to be transmitted by this function
      ESP_client((String) temp);
    }

The above code differes from the code I'm actually running but it reproduces my problem. I hope that somebody can figure out a misstake or give my some advice about how I could implement things in a better way.
Actually I'm not sure whether the misstake is on laptop- or ESP-side but as the ESP crashes **sometimes** I think it's the ESP...

I'm using the arduino IDE for flashing, btw.

title: Communication with socketserver fails after specific number of packets

Answers: 2

body:
close the disconnected socket before reconnecting

    if (!client.connected()) {
      client.stop();
      client=TCPserver.available();
    }

body:
I found my stupid mistake:
By using `try` without catching **specific** exceptions (I know one shouln't do that) in my Laptop-Server script I didn't recognize that I was trying to send unencoded strings.
So,
`clientsocket.send("hi there, "+str(addr)+"\n")`
has to be
`clientsocket.send(bytes(("hi there, "+str(addr)+"\n").encode('utf-8')))`
instead.


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

    #include <SoftwareSerial.h>

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

    #include <TimerOne.h>

    int RECV_PIN = 13;

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

    int freqStep = 65;
    char incomingByte;

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

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

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

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

      switch(results.value){

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

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

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

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

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

      case 0x10EF807F:

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

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

    }

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

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

       }
         delay(700);
     }

title: Stuck in While loop when case is activated. Arduino

Answers: 3

body:
You shouldn't have while loops in your switch/case like that.

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

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

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

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

body:
Don't use the while loop, set a boolean when the C has been pressed.

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

There are good reasons not to use a while loop:

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

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


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

**This is the code:**

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

    int SENSOR = 2;
    int TEMPERATURE;
    int HUMIDITY;

    DHT dht(SENSOR, DHT11);

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

    void loop() {
    TEMPERATURE = dht.readTemperature();
    HUMIDITY = dht.readHumidity();
    Serial.print("Temperature: ");
    Serial.print(TEMPERATURE);
    Serial.print(" Humidity: ");
    Serial.println(HUMIDITY);
    delay(1000);
    }
**This is the circuit scheme:**

[![enter image description here][1]][1]

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

[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]

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

  [1]: https://i.stack.imgur.com/01uZZ.png
  [2]: https://i.stack.imgur.com/xgUdo.jpg
  [3]: https://i.stack.imgur.com/5h1uT.jpg
  [4]: https://i.stack.imgur.com/icXBK.jpg

title: Problem with a DHT11 Temperature & Humidity sensor

Answers: 1

body:
Finally I was able to solve the problem by **not using the resistor** and connecting it directly, I also had a problem with the sensor pins since some were badly connected, but it was also solved. **Now both sensors are working well** including the melted one. ***Thanks!***.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/hWU87.png


body:
I'm trying to compile FastLED library for my STM32F103C using Arduino 1.8.5 IDE, but getting this error:

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

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

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

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

     #include <avr/io.h>

                        ^

    compilation terminated.

    exit status 1
    Error compiling for board Generic STM32F103C series.

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

title: "avr/io.h: No such file or directory" while compiling for board Generic STM32F103C series

Answers: 2

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

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

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


body:
I am using a Pro Micro as a HID touchpad, connected to a laptop running Ubuntu 17.04. Everything works, except that the board freezes or hangs while the computer boots or resumes from standby, requiring me to disconnect and reconnect it every time.

The board is definitely hanging, not resetting; I have programmed the on-board LEDs to flash in sequence during the `setup` and `loop` stages and have determined that the board hangs at random points in the program and does not reset. This suggests to me that the problem lies with the computer or the connection rather than the Arduino.

The hangs occur at specific points during the computer's boot sequence. If I boot with the Arduino connected, it will hang very early in the boot while the manufacturer's logo is visible on screen. If I connect the board at GRUB, the board will hang during Ubuntu's boot sequence, somewhere among the commands to initialize hard disk buses. Less predictably, the board will hang about 75% of the time just after logging in or when resuming from standby (just before the login manager appears).

I wonder whether the power supply may be dropping by some amount sufficient to halt execution, but not enough to reset the board, but I don't know if that's a realistic hypothesis. I don't know how to investigate further.

What could be causing this issue? What steps could be taken to determine and solve the problem?

**Edit** - February 2018

I have updated my operating system to Ubuntu 17.10, which uses GNOME Display Manager for the login prompt instead of LightDM, and the problem no longer occurs when resuming from suspend. So it appears the communication that froze the Arduino was triggered by LightDM, not the BIOS.

title: Pro Micro HID freezes during computer boot or resume from standby

Answers: 0


body:
I'm a beginner. I bought a new Arduino and I uploaded the basic example button code.

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

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

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

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

Give me some suggestion.

title: Built-in LED turns on when I touch the input port

Answers: 1

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


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

title: Is it right to connect Serial module directly?

Answers: 1

body:
Maybe the serial module has a serial cable attached to it which gives a voltage.

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

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


body:
I have a question about driving a stepper motor back and forward. Basically I want it to do a total of 24 steps (12 forward and 12 back) but I don't want to repeat the same steps when coming back.

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

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

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

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

    const int stepsPerRevolution = 200;

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

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

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

    void loop() {
    }

title: How to drive a stepper motor, by having it go even steps forward and odd steps back?

Answers: 1

body:
Ok, I tried to fix a couple of things from your code.

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

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

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

    #include <Stepper.h>

    const int stepsPerRevolution = 200;

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

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

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

    const uint16_t moveStepMs = 2;
    unsigned long prevMillis;

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

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

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

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

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

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


body:
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 :)

title: How to rotate 3 servo motors when 6 led lights are lit using EMG signals

Answers: 1

body:
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`)


body:
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");
    }

title: Download and print data from Thingspeak

Answers: 1

body:
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.


body:
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?

title: Strange issue with FHT library for sound-reactive LED project

Answers: 1

body:
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.

<pre>
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
</pre>

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.


body:
I'm having a problem extracting the Object/Array from this sample json
<code>
[
   {
     "sensor":"gps1",
     "time":1351824120
   },
   {
     "sensor":"gps1",
     "time":1351824120
   }
]
</code>

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

Thanks

title: Arduino JSON extract using ArduinoJSON Library

Answers: 1

body:
You can use the [ArduinoJson Assistant](https://arduinojson.org/assistant/) on [arduinojson.org](https://arduinojson.org/) to create a skeleton.

Here is what it generates in your case:

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

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

 JsonArray& root = jsonBuffer.parseArray(json);

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

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


body:
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][1], 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?

  [1]: https://forums.adafruit.com/viewtopic.php?f=47&t=66428

title: Calling I2C functions inside an ISR

Answers: 3

body:
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;
        }

    }

body:
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.

body:
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.


body:
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.

title: OV7670 Camera Module - wrong pins?

Answers: 1

body:
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/?amp_page=true

Cheers !


body:
The `arduino-builder` app when invoked directly with parameter `--tools /usr/bin` works, but the IDE fails with the error in the title for any sketch (including the Blink example).

I've tried adding things to `preferences.txt` like

    tools.path=/usr/bin

And variations, but I keep getting the same failure in the IDE.  This is using a fresh distro package install on Fedora 27 (I did not have this problem previously using Fedora 25).

title: Arduino IDE fails on Fedora with arduino-builder error "Parameter 'tools' is mandatory"

Answers: 2

body:
I don't understand why this worked, but I found [this comment](https://bugzilla.redhat.com/show_bug.cgi?id=1435029#c15) in Redhat Bugzilla (it doesn't seem to be a bug report specifically about that...but anyway):

> > Parameter 'tools' is mandatory
> > [...]
>
>However, if I create the packages directory in ~/.arduino15, compilation now works.
>
>     mkdir ~/.arduino15/packages

Seemed like an easy thing to try, and voila -- after an hour of fuss.

I do not understand why this is so (nothing ends up in that directory, either) but I'm leaving this in hopes it may save someone else some time.

body:
The problem occurs because arduino does not have permission to modify directory in /usr/share/arduino to create tools-builder

All you have to do is navigate to usr/share/arduino create 'tool-builder' directory
**`sudo mkdir /usr/share/arduino/tools-builder`**


body:
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?...

title: U8glib funny problem

Answers: 2

body:
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]

  [1]: https://github.com/olikraus/u8g2/wiki

body:
`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.
[![enter image description here][1]][1]

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);}

    }

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/NXaLY.png
  [2]: https://i.stack.imgur.com/4m9mA.png

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);

    }


body:
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:

[![RobotDyn W5500 ethernet module][1]][1]

The RFID Module i am using:

[![RC522 RFID module][2]][2]

  [1]: https://i.stack.imgur.com/L0UIP.jpg
  [2]: https://i.stack.imgur.com/1pCir.jpg

title: Arduino Nano + RC522 + w5500 Ethernet Module

Answers: 1

body:
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.


body:
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:

[![Workspace][1]][1]

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.

  [1]: https://i.stack.imgur.com/KFA8I.png

title: Arduino and MatLab with OWI Robotic Arm Edge -- Issue with I2C

Answers: 1

body:
The documentation in MATLAB for `scanI2CBus()` notes that the return is a [cell array of character vectors][1]

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')`

  [1]: https://www.mathworks.com/help/supportpkg/arduinoio/ref/scani2cbus.html


body:
I am trying to compile GatewaySerial code from MySensors library for my Arduino Leonardo and it gives me EEPROM errors.

Gateway code:

/**
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
* Copyright (C) 2013-2015 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
*******************************
*
* DESCRIPTION
* The ArduinoGateway prints data received from sensors on the serial link.
* The gateway accepts input on seral which will be sent out on radio network.
*
* The GW code is designed for Arduino Nano 328p / 16MHz
*
* Wire connections (OPTIONAL):
* - Inclusion button should be connected between digital pin 3 and GND
* - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series
*
* LEDs (OPTIONAL):
* - To use the feature, uncomment any of the MY_DEFAULT_xx_LED_PINs
* - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved
* - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
* - ERR (red) - fast blink on error during transmission error or recieve crc error
*
*/

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enable and select radio type attached
#define MY_RADIO_NRF24
//#define MY_RADIO_NRF5_ESB
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95

// Set LOW transmit power level as default, if you have an amplified NRF-module and
// power your radio separately with a good regulator you can turn up PA level.
#define MY_RF24_PA_LEVEL RF24_PA_LOW

// Enable serial gateway
#define MY_GATEWAY_SERIAL

// Define a lower baud rate for Arduino's running on 8 MHz (Arduino Pro Mini 3.3V & SenseBender)
#if F_CPU == 8000000L
#define MY_BAUD_RATE 38400
#endif

// Enable inclusion mode
#define MY_INCLUSION_MODE_FEATURE
// Enable Inclusion mode button on gateway
//#define MY_INCLUSION_BUTTON_FEATURE

// Inverses behavior of inclusion button (if using external pullup)
//#define MY_INCLUSION_BUTTON_EXTERNAL_PULLUP

// Set inclusion mode duration (in seconds)
#define MY_INCLUSION_MODE_DURATION 60
// Digital pin used for inclusion mode button
//#define MY_INCLUSION_MODE_BUTTON_PIN  3

// Set blinking period
#define MY_DEFAULT_LED_BLINK_PERIOD 300

// Inverses the behavior of leds
//#define MY_WITH_LEDS_BLINKING_INVERSE

// Flash leds on rx/tx/err
// Uncomment to override default HW configurations
//#define MY_DEFAULT_ERR_LED_PIN 4  // Error led pin
//#define MY_DEFAULT_RX_LED_PIN  6  // Receive led pin
//#define MY_DEFAULT_TX_LED_PIN  5  // the PCB, on board LED

#include <MySensors.h>

void setup()
{
 // Setup locally attached sensors
}

void presentation()
{
 // Present locally attached sensors
}

void loop()
{
 // Send locally attached sensor data here
}

Error:

In file included from /home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.cpp:20:0,
                 from /home/szymex/Arduino/libraries/MySensors/MySensors.h:64,
                 from /home/szymex/Arduino/libraries/MySensors/examples/GatewaySerial/GatewaySerial.ino:86:
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp: In function 'bool transportAssignNodeID(uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp:503:3: note: in expansion of macro 'hwWriteConfig'
   hwWriteConfig(EEPROM_NODE_ID_ADDRESS, newNodeId);
   ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp: In function 'void transportSetRoute(uint8_t, uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp:1065:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_ROUTES_ADDRESS + node, route);
  ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'void _begin()':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:140:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_PARENT_NODE_ID_ADDRESS, MY_PARENT_NODE_ID);
  ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'bool _processInternalMessages()':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:56:114: error: 'eeprom_update_block' was not declared in this scope
 #define hwWriteConfigBlock(__buf, __pos, __length) eeprom_update_block((void*)(__buf), (void*)(__pos), (__length))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:415:4: note: in expansion of macro 'hwWriteConfigBlock'
    hwWriteConfigBlock((void*)&_coreConfig.controllerConfig, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS,
    ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'void saveState(uint8_t, uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:499:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_LOCAL_CONFIG_ADDRESS+pos, value);
  ^
exit status 1

title: MySensors GatewaySerial code not compiling

Answers: 1

body:
Fixed here:
https://github.com/mysensors/MySensors/issues/1007
I needed to update Arduino IDE, reinstall board definitions and MySensors library