message:
How to keep a 24 hour maximum and minimum temperature

I am keeping a simple weather station to monitor humidity and temperature in my greenhouse. I have a ds18b20 and dht probes.  everything works great and I even used a little trick to hold my maximum and minimum values, but I would like them to reset every 24 hours. Is there anyway i can code the arduino to reset itself. i tried several examples of connecting digital pins to the reset pin and i couldn't get any of those to work.  i tried to reset the values of my max and min to 0 and 99 respectively after my millis() reached the equivalent of a day, but they just stuck at 0 and 999. I understand fully why it does this i just don't know how to fix it. all i want to do is reset my minimum and maximum temperatures after 24 hours.

    //       Green HAUS Version 1 by Kent Scipione 9/3/2017
    //       Monitors temperature and humidity
    long timenow;
    long day = 86400000; // 86400000 milliseconds in a day
    long hour = 3600000; // 3600000 milliseconds in an hour
    long minute = 60000; // 60000 milliseconds in a minute
    long second =  1000; // 1000 milliseconds in a second

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <SPI.h>
    #include <Adafruit_SSD1306.h>
    #define OLED_RESET 4
    #define ONE_WIRE_BUS 10
    double temp;  // sensor is precise to .1 degree.
    //Double gives smoother serial graph, byte doesn't overflow oled screen
    Adafruit_SSD1306 display(OLED_RESET);
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    #include <Adafruit_Sensor.h>
    #include "DHT.h"
    #define DHTPIN 2
    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);

    int maxtemp=0;
    int mintemp=999;

    void setup() {

      Serial.begin(9600);
      Serial.println("green HAUS Version 1 by Kent Scipione 9/3/2017");
      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
      display.display();
      display.setTextColor(WHITE);
      sensors.begin();
      dht.begin();

    }

    void loop() {
      timenow = millis();
      sensors.requestTemperatures();
      temp = sensors.getTempFByIndex(0);
      int humid = dht.readHumidity();
      float dtemp = dht.readTemperature(true);
      if (temp > maxtemp) {
        maxtemp=temp; }
      if (temp < mintemp) {
        mintemp=temp; }

      if (timenow >= day){
          digitalWrite(4, HIGH);
          pinMode(4, OUTPUT);       //*************************this is the part where I'm trying to reset the mintemp and maxtemp**********

        }

      Serial.print("Probe Temperature: ");
      Serial.println(temp); Serial.println("*F");
      display.setCursor(0,0);  //refreshes display
      display.clearDisplay();
      display.setTextSize(1); display.print("Probe "); display.println(temp);  //line 1 of text
      display.print("DHT  "); display.print(dtemp); display.print("  "); display.print(humid); display.println(" %");  //line 2 of text
      display.print("HIGH "); display.println(maxtemp);           //line 3 of text
      display.print("LOW  "); display.println(mintemp);   //line 4 of text
      display.display();

    }
Thank you so much for your help this is driving me mad haha

body:
You should also keep a timestamp of the last time you reset the min and max otherwise the arduino will keep thinking it's a new day:

    //add to globals
    unsigned long lastDay = 0;

and inside loop()

      if (timenow-lastday >= day){

          maxtemp=0;
          mintemp=999;
          lastDay = timenow;
      }


sender: user

message:
Allocation, initialization and scope

I realized I don't fully understand how Arduino code handles variable lifetime. My tendency is to keep variables in the narrowest scope (which I realize isn't as important in Arduino code, but, habits...). But how inefficient is this?

Given these possible variations:

     const int c1 = 2, c2 = 7, c3 = 9;

     void functy();

     int foo[3] = {c1 | c2, c3, c2 | c3};

     static int foo[3] = {c1 | c2, c3, c2 | c3};

     const int foo[3] = {c1 | c2, c3, c2 | c3};

      ....

In case 1, foo is both allocated and initialized each call.

In case 2, foo is allocated only once, but is it initialized on each call?

In case 3 I assume that allocation and initialization are done only once? Is that true?

sender: assistant

body:
Here's a pretty definitive list for you:

    // Allocated once in the global area and assigned during
    // program startup
    int foo = 1;

    // May not even be allocated - the compiler will most likely
    // optimise it out.
    const int foo = 1;

    // Allocated once and assigned during program startup. Cannot be
    // accessed from outside the file.
    static int foo = 1;

    // The static here has no real effect.
    static const int foo = 1;

    void function() {
        // Allocated in the stack each call and initialised each call.
        // Only accessible from inside this function.
        int foo = 1;

        // Allocated in the global area and initialized on the first call
        // of the function. Only accessible from inside this function.
        static int foo = 1;

        // May not be allocated at all. Only accessible from inside
        // this function.
        const int foo = 1;
    }

Note that non-simple `const` values, things like arrays and strings, depending on the architecture (i.e., if it's a Harvard architecture or not) may be copied into a block of global RAM for simpler access. See [`PROGMEM` in the Arduino Reference Manual](https://www.arduino.cc/en/Reference/PROGMEM) for more information.


message:
Efficiency of a cast vs a shift

I'm using a supplied library which uses a number of (non-sequential) outputs to latch a multiplexer. The code looks (in part) like this:

     digitalWrite(_S0, (chan & 1));
     digitalWrite(_S1, (chan & 3)>>1);
     digitalWrite(_S2, (chan & 7)>>2);
     digitalWrite(_S3, (chan & 15)>>3);

Those masks seem a little odd, but it would work. More natural to me would be:

     digitalWrite(_S0, (chan & 1));
     digitalWrite(_S1, (chan & 2)>>1);
     digitalWrite(_S2, (chan & 4)>>2);
     digitalWrite(_S3, (chan & 8)>>3);

But overall, would it be more efficient to do this?

     digitalWrite(_S0,       (chan & 1));
     digitalWrite(_S1, (bool)(chan & 2));
     digitalWrite(_S2, (bool)(chan & 4));
     digitalWrite(_S3, (bool)(chan & 8));

...or is shifting already pretty efficient?

I've actually re-written the code to build a mask and use PORTx to latch it all at once, so this is really an academic question, but I'm still curious.

body:
If you look at the assembly code the compiler produces, you can see it compiles to the exact same thing - when using a constant.:

    void setup() {
      ....
      digitalWrite(_S1, (chan & 2)>>1);
     282: 84 e0        ldi r24, 0x04 ; 4
     284: 0e 94 6b 00  call 0xd6 ; 0xd6 <digitalWrite.constprop.0>
     ....
      digitalWrite(_S1, (bool)(chan & 2));
     29a: 84 e0        ldi r24, 0x04 ; 4
     29c: 0e 94 6b 00  call 0xd6 ; 0xd6 <digitalWrite.constprop.0>

However, using a variable produces different results:

    void loop() {
      digitalWrite(_S0, (chan & 1));
     2a2: c0 91 00 01  lds r28, 0x0100 ; 0x800100 <__data_start>
     2a6: d0 91 01 01  lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
     2aa: 6c 2f        mov r22, r28
     2ac: 61 70        andi r22, 0x01 ; 1
     2ae: 83 e0        ldi r24, 0x03 ; 3
     2b0: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>
      digitalWrite(_S1, (chan & 2)>>1);
     2b4: 6c 2f        mov r22, r28
     2b6: 66 95        lsr r22
     2b8: 61 70        andi r22, 0x01 ; 1
     2ba: 84 e0        ldi r24, 0x04 ; 4
     2bc: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>
      digitalWrite(_S2, (chan & 4)>>2);
     2c0: c2 fb        bst r28, 2
     2c2: 66 27        eor r22, r22
     2c4: 60 f9        bld r22, 0
     2c6: 85 e0        ldi r24, 0x05 ; 5
     2c8: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>
      digitalWrite(_S3, (chan & 8)>>3);
     2cc: c3 fb        bst r28, 3
     2ce: 66 27        eor r22, r22
     2d0: 60 f9        bld r22, 0
     2d2: 86 e0        ldi r24, 0x06 ; 6
     2d4: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>

     ....

      digitalWrite(_S0,       (chan & 1));
     2a2: c0 91 00 01  lds r28, 0x0100 ; 0x800100 <__data_start>
     2a6: d0 91 01 01  lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
     2aa: 6c 2f        mov r22, r28
     2ac: 61 70        andi r22, 0x01 ; 1
     2ae: 83 e0        ldi r24, 0x03 ; 3
     2b0: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>
      digitalWrite(_S1, (bool)(chan & 2));
     2b4: be 01        movw r22, r28
     2b6: 76 95        lsr r23
     2b8: 67 95        ror r22
     2ba: 61 70        andi r22, 0x01 ; 1
     2bc: 84 e0        ldi r24, 0x04 ; 4
     2be: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>
      digitalWrite(_S2, (bool)(chan & 4));
     2c2: be 01        movw r22, r28
     2c4: 76 95        lsr r23
     2c6: 67 95        ror r22
     2c8: 76 95        lsr r23
     2ca: 67 95        ror r22
     2cc: 61 70        andi r22, 0x01 ; 1
     2ce: 85 e0        ldi r24, 0x05 ; 5
     2d0: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>
      digitalWrite(_S3, (bool)(chan & 8));
     2d4: be 01        movw r22, r28
     2d6: 23 e0        ldi r18, 0x03 ; 3
     2d8: 76 95        lsr r23
     2da: 67 95        ror r22
     2dc: 2a 95        dec r18
     2de: e1 f7        brne .-8       ; 0x2d8 <main+0xc0>
     2e0: 61 70        andi r22, 0x01 ; 1
     2e2: 86 e0        ldi r24, 0x06 ; 6
     2e4: 0e 94 76 00  call 0xec ; 0xec <digitalWrite>


body:
I tried compiling your three snippets with avr-gcc 4.9.2 at the `-Os`
optimization level (standard with Arduino) but _without_ `-flto`. The
results were:

* The first snippet generated inefficient code: the ands and shifts were
  translated in assembly quite literally, the shifts were done on
  16 bits even though `chan` was declared `uint8_t`, and the last
  shift was even implemented as a loop roughly equivalent to
  `uint16_t tmp1 = chan & 15; uint8_t tmp2 = 3; while (--tmp2) tmp1 <<= 1;`

* The second and third snippets were translated identically and
  efficiently, using the `bst` (bit store) and `bld` (bit load)
  instructions to copy the relevant bit of `chan` into the second
  argument of the `digitalWrite()` call.

Personally I would just write

    digitalWrite(_S0, chan & 1);
    digitalWrite(_S1, chan & 2);
    digitalWrite(_S2, chan & 4);
    digitalWrite(_S3, chan & 8);

as `digitalWrite()` expects an integer as its second argument, and it
interprets it just like the `(bool)` cast does. If you want to be sure
to always call `digitalWrite()` with either 0 (`LOW`) or 1 (`HIGH`),
then use either your second of third form. The first form seems formally
equivalent to the second, but since it is _not_ an usual C idiom, the
compiler could not catch the optimization opportunity.


message:
Building mocoLUFA under OSX & Linux

I am attempting to build mocoLUFA under OS X el Capitan 10.11.6.

[Editor: [mocoLUFA (MIDI firmware for Arduino Uno)\]
][1]
[![enter image description here][2]][2]

I am using the specified LUFA version (LUFA101122) and I have tried building with both brew avr-gcc and also Crosspack-AVR.

The problem I am facing isn't with the build or the install. It's just that as soon as I install the hex file, I get no midi messages at all.

What does work - the OSX machine recognises the MIDI device and the MIDI device appears in DAW's, however MIDI Monitor registers no messages at all.

I have tried downloading [a custom-built mocoLUFA][3] and I am able to install this and it works fine. I see midi messages coming across from my sketch.

Crosspack-AVR installs avr-gcc 4.8.1.

My question is - what is the correct build environment in order to achieve a working mocoLUFA under OSX? I have tried both mocoLUFA and dualMoco and I get the same result with each.

My purpose for this is to modify mocoLUFA so that it can support sending MTC over USB. At present, it appears that mocoLUFA does not support System Common messages.

UPDATE: Built fresh Ubuntu VM. Installed avr-gcc, avr-libc, LUFA-100807 and mocoulfa. Same result. hex builds fine, no response from the atmega16u2. TX light flashing, sketch on the 2560 running, but no midi messages down the usb cable.

  [1]: https://github.com/kuwatay/mocolufa
  [2]: https://i.stack.imgur.com/eFF2f.jpg
  [3]: https://moco-lufa-web-client.herokuapp.com/

body:
This is Franco, from Yaeltex, the guys who put up that site for custom MocoLUFA compiling.

Our site works on an Ubuntu server, and the build environment can be seen at the bottom of the site, which is as follows:

 1. Ubuntu Server Setup
 - avr-gcc: avr-gcc (GCC) 4.9.2
 - avrdude: Version 6.3, compiled on Mar 15 2016 at 21:26:45
 - LUFA: 100807
 - dualMocoLUFA: custom Yaeltex based on 2013/09/22

On the other hand, I use Windows 10 to build locally in my computer, and I have a similar setup with sligthly older versions of avr-gcc and avrdude:

 2. Windows 10 Server Setup
 - avr-gcc: avr-gcc (GCC) 4.3.3
 - avrdude: Version 5.10, compiled on Mar 15 2016 at 21:26:45
 - LUFA: 100807
 - dualMocoLUFA: custom Yaeltex based on 2013/09/22

Here is a link to the [fork we made to mocoLUFA][1], it has minor changes, that were very useful to us and our hardware.

Regarding your problem, I am really lost on the cause of it, but we can start with some questions to get closer to a solution.

 - What kind of MIDI messages are you trying to send/receive?
 - Can you share the code you are using?
 - Are you using Arduino MIDI Library (Last version is v4.3.1)?
 - If not, are you sure you are using 31.250 bps as baud rate?
 - Do you have something else connected to TX or RX lines in your circuit?

Let's start with these. Cheers!

  [1]: https://github.com/Yaeltex/mocolufa-ytx


body:
I see that you are reading the MIDI messages from your iPad. If so, it is to be noted that LUFA reports 500mA for power requirements. So you could try self powering your USB-HUB.

Source: http://morecatlab.akiba.coocan.jp/morecat_lab/MocoLUFA.html


message:
Cannot mount NodeMCU with MicroPython on Mac OS X

I've recently bought a NodeMCU board and flashed MicroPython in it. I've read about the `boot.py` and `main.py` scripts, but I can't understand how to access them...

I have succesfully connected to the Python REPL with the screen command and everything works fine. Is there a way to mount it as an external drive on Mac OS X? Because I haven't found a way till now.

Thanks in advance!

body:
You have a NodeMCU; not a pyboard. I'm not sure that the USB Drive option is available in the NodeMCU.

I flashed microPython in a NodeMCU and Linux doesn't recognize it as a external drive or any other media type, but REPL thru serial monitor works fine.


body:
The typical NodeMCU board uses a fixed function CP-210x USB-Serial chip.  This cannot appear to a host operating system as any ordinary sort of storage device, so it is not "mountable" via conventional storage drivers.

Access would need to be through some client program - or else, at a bit of a stretch, some highly specialized driver that created something fitting the host operating system's idea of filesystem, but proxying the actions through operatings the CP-210x and software running in the ESP8266 can support.


message:
I2C Temperature Sensor Communication Issue

I'm currently learning I2C and having some issues displaying the correct temperature in the serial monitor.

I am using an Arduino Uno and an SI7021 temperature sensor from Sparkfun; here's [the datasheet][1] I'm looking at.

The datasheet says that its device address is `0x40` and the temperature register is `0xF3` (maybe I am looking at this wrong?). However when I print the result to the screen it reads -1 degrees F.

Here's my code:

    // SparkFun Si7021 Humidity and Temperature Sensor
    #include <SparkFun_Si7021_Breakout_Library.h>
    #include <Wire.h>

    //Weather sensor slave address
    int WeatherAddress = 0x40;

    #define Temperature_Register_DATA 0xF3

    //initialize humidity and temperature variables
    float humidity = 0;
    float tempf = 0;

    //create a sensor from the Weather library
    Weather temp_rh_sensor;

    void setup() {
      Serial.begin(9600);
      //create wire object
      Wire.begin();
      //begin weather sensor
      temp_rh_sensor.begin();
    }

    void loop() {
      //begin transmission to weather sensor
      Wire.beginTransmission(WeatherAddress);
      //ask particular register for data (temperature register)
      Wire.write(Temperature_Register_DATA);
      Wire.endTransmission();
      //request the transmitted single byte from the register
      Wire.requestFrom(Temperature_Register_DATA, 1);
      if(Wire.available() <= 1) {
        tempf = Wire.read();
      }
      Serial.print("Temp: ");
      Serial.print(tempf);
      Serial.println("F, ");
      delay(1000);
    }

  [1]: https://cdn.sparkfun.com/datasheets/Sensors/Weather/Si7021.pdf

body:
    Wire.requestFrom(Temperature_Register_DATA, 1);

This should have the WeatherAddress as parameter instead of the register.

    Wire.requestFrom(WeatherAddress, 1);


body:
Reading this sensor is a little more involved. You don't just select a register and then read the value from it. Instead you send it a command to begin a read of a parameter (e.g., temperature) and then you need to wait for it to perform that command before you can read the result.

You need to use command 0xF3 for read with *no hold master mode* which will return NACK from a read request if the command isn't completed (which you are doing) - you then need to keep retrying the read until you don't get a NACK.

Also you need to read *two* bytes, not one:

    //begin transmission to weather sensor
    Wire.beginTransmission(WeatherAddress);

    //ask particular register for data (temperature register)
    Wire.write(Temperature_Register_DATA);

    Wire.endTransmission();

    // Keep retrying the read until it succeeds, or times out
    uint32_t start = millis();
    while (Wire.requestFrom(WeatherAddress, 2) < 2) {
        if (millis() - start > 2000) { // 2 second timeout
            break;
        }
    }

    if (Wire.available() < 2) { // It timed out
        Serial.println("Timeout");
    } else {
        // Read the two bytes
        uint8_t hi = Wire.read();
        uint8_t lo = Wire.read();

        // and combine them into a 16 bit value
        uint16_t temp = (hi << 8) | lo;

        // Now convert the returned value into a real temperature:
        tempf = ((175.25 * temp) / 65536.0) - 46.85
        Serial.print("Temperature: ");
        Serial.println(tempf);
    }


body:
> The datasheet says that its device address is: 0x40

there is no standard notation on how to code i2c addresses - it all depends on how the particular library is coded. In this case, try 0x80 and 0x40 and see which one works.


message:
Arduino & NodeMCU, one server and multiple clients

I have seen another similar question and I followed the answer, but I cannot get my code to work for a single client properly.

In short, one NodeMCU provides AP and a WiFi server to multiple clients. The clients are supposed to stay connected. I am testing just a single client and it succeeds to connect and server reads just the first message, whereas all the subsequent messages are not received.

The server code:

    #include <ESP8266WiFi.h>

    #define MAX_CLIENTS 10

    IPAddress    apIP(42, 42, 42, 42);
    const char *ssid = "ESP8266";
    const char *password = "ESP8266Test";
    WiFiServer server(80);
    WiFiClient *clients[MAX_CLIENTS] = { NULL };

    void setup() {
      Serial.begin(115200);
      WiFi.mode(WIFI_AP_STA);
      WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
      WiFi.softAP(ssid, password);
      IPAddress myIP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.println(myIP);
      server.begin();
    }

    void loop () {
      WiFiClient newClient = server.available();
      if (newClient) {
        Serial.println("new client");
        // Find the first unused space
        for (int i=0 ; i<MAX_CLIENTS ; ++i) {
          if (NULL == clients[i]) {
            clients[i] = new WiFiClient(newClient);
            break;
          }
        }
      } else {
        // Check whether each client has some data
        for (int i=0 ; i<MAX_CLIENTS ; ++i) {
          if (NULL != clients[i]) //ako ima taj client {
            if (clients[i]->available()) {
              Serial.print("client "); Serial.print(i);
              Serial.println("data received");
              digitalWrite(ledPin, LOW);
              String request = clients[i]->readStringUntil('\r');
              Serial.println(request);
            }
          }
        }
      }
    }

As one can see, I'm checking incoming connections with `server.available()`, whereas I check if there is some data over the existing connection with `clients[i]->available`.

What happens is that I get only the first message from the client. The client code follows:

    #include <ESP8266WiFi.h>

    char ssid[] = "ESP8266";
    char pass[] = "ESP8266Test";
    WiFiClient client;

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, pass);
      while (WiFi.status() != WL_CONNECTED) {
        Serial.println("W");
        delay(500);
      }
      client.connect(WiFi.gatewayIP(), 80); // Connection to the server
    }

    void loop () {
      client.println("0.00"");
      Serial.println("0.00"");
      delay(3000);
    }

I suspect that I do not understand well the Server and Client classes from ESP8266WiFi Library, but it seems poorly documented.

Please advise.

body: I presume you are not flushing the first data that's why only the first time your communication is happening but not after the subsequent time


message:
How to send data from an Arduino GPRS module to a Django application hosted on Heroku?

I have a Django web application hosted on a Heroku server. Currently I am using the free package for hosting. I want to send data from an Arduino using a SIM900L GPRS module to the web application. I want to know if it is possible. I have searched for a solution but couldn't find a proper guide or example for it. My web application accepts get requests and updates values in the database when url is entered. However if the Arduino sends data using the same url I get the following error:

>
AT+CIPSTART="TipCP","https://<appname>.herokuapp.com",80
ERROR

Any tested example or suggestions about what I am doing wrong or what I should be doing instead?

         void gprs(float *value1, float *value2, float *value3, float *AFR, float *value5, float *value6)
    {

      String APN = "";
      String UNAME = "";
      String PWD = "";
      char fid[] = "";
      char nid[] = "";
      char s_ip[] = "https://<appname>.herokuapp.com";
      char apikey[] = "";

      wdt_reset();
      digitalWrite(A4, HIGH);
      Serial.println(F("GPRS-1 Function"));
      delay(5000);
      wdt_reset();
      delay(5000);
      wdt_reset();

      char buffer1[10];

      uint8_t GSMTries = 0;
      String res;

      //wdt_reset();
      // the below code establishes connection and if not successful
      // tries three times in total
      do {
        sendData(F("AT\r\n"), 1000, DEBUG);
        sendData(F("AT+CIPSHUT\r\n"), 2000, DEBUG);
        sendData(F("AT+CIPMUX=0\r\n"), 2000, DEBUG);

        sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
        sendData("AT+CSTT= \"" + APN + "\", \"" + UNAME + "\", \"" + PWD + "\"\r\n", 2000, DEBUG);

        sendData(F("AT+CIICR\r\n"), 2000, DEBUG);
        sendData(F("AT+CIFSR\r\n"), 2000, DEBUG);

        sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
        String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
        scnt += s_ip ;
        scnt += "\",80\r\n" ;

        res = sendData(scnt, 10000, DEBUG);
        GSMTries++;

        wdt_reset();

      } while (((res.indexOf("ERROR") != -1) || (res.indexOf("CONNECT") == -1)) && (GSMTries < 3));
      /*
        if(res.indexOf("ERROR") != -1){
        delay(200);
        sendData(scnt, 10000, DEBUG);
        }
      */

      String api = "GET /value?apkey=" ;
      api += apikey;
      api += "&&fid=";
      api += fid;
      api += "&&nid=";
      api += nid;

      Serial.println(F("API......."));
      Serial.flush();
      Serial.println(F("here-1"));

      String Data1 = "";

      //wdt_reset();
      //Co ordinator data is compiled along with html commands
      //and sent through GPRS
      String sensor = dtostrf(*value1, 4, 2, buffer1);
      Data1.concat(api);
      Data1.concat(F("&field1="));
      Data1.concat(sensor);

      sensor = dtostrf(*value2, 4, 2, buffer1);
      Data1.concat(F("&field2="));
      Data1.concat(sensor);

      sensor = dtostrf(*value3, 4, 2, buffer1);
      Data1.concat(F("&field3="));
      Data1.concat(sensor);

      sensor = dtostrf(*AFR, 4, 2, buffer1);
      Data1.concat(F("&field4="));
      Data1.concat(sensor);

      sensor = dtostrf(*value4, 4, 2, buffer1);
      Data1.concat(F("&field5="));
      Data1.concat(sensor);

      sensor = dtostrf(*value6, 4, 2, buffer1);
      Data1.concat(F("&field6="));
      Data1.concat(sensor);

      Data1.concat(F("\r\n"));

      delay(1000);

      String cipSend = "AT+CIPSEND=";
      cipSend.concat(Data1.length());
      cipSend.concat("\r\n");
      sendData(cipSend, 8000, DEBUG);
      sendData(Data1, 8000, DEBUG);
      sendData(F("AT+CIPCLOSE\r\n"), 5000, DEBUG);
      digitalWrite(A4, LOW);

      wdt_reset();

    }
The above is a part of code used in arduino to upload data to website. This code was being used before to upload data to thingspeak through its IP address and worked fine.

body:
There's a number of errors in your program regarding your understanding of basic networking:

Let's start with this bit:

    String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
    scnt += s_ip ;
    scnt += "\",80\r\n" ;

That constructs a string:

    AT+CIPSTART="TipCP","https://<appname>.herokuapp.com",80

and sends it to the modem.  Now:

1. There is no such protocol as "TipCP" - I think you meant "TCP"
2. You need to provide an FQDN (Fully Qualified Domain Name), *not* a URL.  FQDNs don't start with "https://".  I think you meant to use "foobar.herokuapp.com" where "foobar" is the name of your application.

You then go on to form a GET request and send it.

Now: the URL you used instead of an FQDN starts with https:// - that tells me you want to be using SSL for your communications. I don't know if that is required for Heroku or not, but if it is then you cannot use `AT+CIPSTART` with it unless you feel like trying to implement the entirety of SSL in your program. Also you would be connecting to port 443 not port 80.

Assuming you don't need SSL fixing your protocol and FQDN may be enough. However using the `AT+HTTP...` commands instead of manual manipulation of a raw TCP socket may be an easier option.

If you *do* need SSL (and it is advisable that you do if you can) then you will have to use the SIM900's `AT+HTTPS...` command set (detailed [here](http://simcom.ee/documents/SIM900/SIM900_HTTPS AT Command Set_V1 00.pdf)).


message:
What good designs are available for Geiger counters using an Arduino?

Are there any good circuit designs for Geiger-counter projects using an Arduino?

If so, what Geiger-Muller tubes should I choose to detect different types of radiation?

body:
There are a few good, open-source, designs for Geiger counters using cheap G-M tubes and Arduino boards out there. Which one is best for you depends on what you want to achieve, so let's start by taking a look at what you might want to detect.

What are these "types" of radiation?
------------------------------------

![Types of radiation][1]
(*source: Wikipedia*)

**Alpha radiation**: basically consists of helium-4 nuclei (i.e. two protons and two neutrons). These interact with matter strongly because they are relatively heavy and carry a positive charge. However, because of their mass they will normally only penetrate a few centimetres of air. Alpha particles can be stopped in their tracks by a single sheet of paper.

You may not realise it, but the sensor in most smoke detectors uses a very small amount (~0.2μg) of Americium -  241Am.

![ion chamber][2]

**Beta radiation**: consists of highly energetic electrons. Because these particles are relatively light, they can penetrate somewhat further than Alpha particles. Even so, beta radiation can be stopped by a thin sheet of aluminium.

The big risk to human health from alpha- and beta-emitters is when they are ingested or inhaled. In these cases, the particles are brought into close contact with sensitive live tissue where the ionising radiation has the potential to cause various types of cancers.

**Gamma radiation:** is electromagnetic radiation having a higher frequency and shorter wavelength than X-rays.

![e-m spectrum][3]

One way to think of gamma-radiation is like a kind of "super X-ray". Gamma rays can pass through virtually anything. To build an effective shield, you need to have either *very* thick walls or a shield made from something with a high atomic weight, such as lead.

Gamma rays are produced naturally by the sun and stars - this is the source of what we call "cosmic radiation".

So which tubes should you choose?
---------------------------------

Once you have decided what types of radiation you want your Geiger counter to detect the next step is choosing the tube. In general, they are all high-voltage tubes, typically operating at ~ 400V.

At the moment, the cheapest available tubes are probably the Russian [SI-3BG][4] Geiger Muller tubes, which can be picked up on eBay for about £5 GB. These are not very sensitive, but I've found they do work OK for beta and gamma radiation. However, it doesn't detect alpha radiation (which, as mentioned earlier, is what is emitted by the source in the sensor in many smoke detectors!)

One thing to watch out for is that these tubes are all different sizes, ranging from about 20mm long to more than 200mm. This matters. If you are going to design or buy a PCB for your project, just check that it has been designed to fit the sensor that you intend to use.

The following table lists the most popular G-M tubes, together with their main characteristics:

![G-M tubes][5]

Follow the links below for further data on each tube:

 - [SBM-20][6]
 - [SBM-21][7]
 - [SI-1G][8]
 - [SBT-9][9]
 - [SI-3BG][4]
 - [LND-712][10]
 - [LND-7124][11]
 - [LND-7224][12]
 - [J408γ][13]
 - [J305β][14]
 - [J306β][15]

Your choice of tube is going to be determined by your budget, the types of radiation you want to detect and the sensitivity you want to achieve with your G-M counter.

Circuit designs
---------------

OK, so now we understand the radiation types, and we've chosen our tube, what Geiger counter designs are out there that use the Arduino.

(***disclaimer***: I have no connection with any of the companies mentioned in this answer)

Well, it turns out there are a few good designs out there (Google is your friend here), but one that does stand out from the pack (IMHO) is the [Geiger Counter - Radiation Sensor Board for Arduino and Raspberry Pi][16] from Cooking Hacks.

This is an open hardware design, and the code can be downloaded on a GPL licence.

It's a relatively [simple design][17], and has a kit available pretty much off-the-shelf. Software can be downloaded for the Arduino and/or the Raspberry Pi. If you decide to buy the kit, they assure us that the shield/hat has been tested with the Arduino Uno and all models of the R-Pi.

Alternatively, you can just download the circuit diagram on the link above and design your own PCB (I don't think they offer the Gerber or Eagle files to download).

It is worth mentioning that the tutorial page also includes all the lovely useful background theory you'll need to understand how Geiger counters work, and how to get the most out of it.

**Final thoughts**. If you were thinking of building a Geiger counter without using an Arduino (Yes, yes, I know. But there may be some strange people out there who want to go this route!), there are still some nice designs out there you can play with.

The [Geiger counter][18] from MightyOhm is also open-source and uses the SBM-20 Geiger-Muller tube. Again, it is available as a kit, but if you prefer the DIY route, the [design files][19] are available to download.

Having looked at it, adapting this design to interface with an Arduino would probably also be relatively straightforward ...

If you are on a really tight budget there is a [$15 Geiger counter][20] on Hackaday. This uses the Russian SI-3BG G-M tube (discussed above) and a modified power-supply from a disposable camera.

I built one of these with a friend who was just starting out studying electronics and wanted to have a go at this project. I can confirm that it works, but that $15 price-tag is very optimistic.

(Having built this one, my friend decided that her next project would be to design a better one with greater sensitivity and which could detect alpha-, beta- and gamma-radiation and which incorporated an Arduino Uno. In hindsight, I should probably have mentioned the design from Cooking Hacks ..!).

  [1]: https://i.stack.imgur.com/SYZdn.png
  [2]: https://i.stack.imgur.com/RU0Bw.jpg
  [3]: https://i.stack.imgur.com/ujVHu.png
  [4]: https://www.pocketmagic.net/tube-si-3bg-cи-3бг-small-geiger-muller/
  [5]: https://i.stack.imgur.com/9mJuw.png
  [6]: http://www.gstube.com/data/2398/
  [7]: https://www.pocketmagic.net/tube-sbm-21-сбм-21-miniature-geiger-muller/
  [8]: http://gstube.com/data/2480
  [9]: https://www.pocketmagic.net/tube-sbt-9-end-window-geiger-tube/
  [10]: http://www.lndinc.com/products/711/
  [11]: http://www.lndinc.com/products/350/
  [12]: http://www.lndinc.com/products/368/
  [13]: http://sell.lulusoso.com/selling-leads/1738145/Geiger-Muller-counter-GM-counter-j408-GM-J408.html
  [14]: http://1169585.en.makepolo.com/products/Geiger-tube-J305-for-High-doses-p104457261.html
  [15]: http://en.ofweek.com/Product/Geiger-Muller-Counter-Tube-J306-High-Sensitivity-Beta-Gamma-Radiation-Detection-prod-92360-1087385.html
  [16]: https://www.cooking-hacks.com/documentation/tutorials/geiger-counter-radiation-sensor-board-arduino-raspberry-pi-tutorial/
  [17]: https://www.cooking-hacks.com/media/cooking/images/documentation/geiger_counter_arduino_radiation_sensor_board/radiation_board_v5.pdf
  [18]: http://mightyohm.com/blog/products/geiger-counter/
  [19]: http://mightyohm.com/blog/products/geiger-counter/design-files/
  [20]: https://hackaday.io/project/19479-15-geiger-muller-counter-for-betagammaxray


message:
Force Sensitive Resistor OverLoad

I've got just a simple question. What happens when I overload Force Sensitive Resistor (FSR). [Example Here][1].

[![FSR][2]][2]

Let's say that it's got force sensitive range between 100g and 10 000g. What would happen if I'd create pressure about 100kg? I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance? If so, can this FSR survive this overload? Has somebody test that?

Thank you for any answer.

  [1]: https://www.sparkfun.com/products/9375
  [2]: https://i.stack.imgur.com/lTdEg.jpg

body:
> I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance?

The harder the force, the lower the resistance. Sparkfun has a datasheet attached that shows the following graph:
[![FSR Graph][1]][1]
Notice how both axis of the graph are logrithmic. This means that the resistance will never reach 0 ohms. However it will get close. At 10 Kg (22 lb) the resistance is about 250 ohms.

> What would happen if I'd create pressure about 100kg?

The datasheet has the following to say for weight above the 10 Kg mark:

> At the high force end of the dynamic range, the response deviates from the power-law behavior, and eventually saturates to a point where increases in force yield little or no decrease in resistance. Under these conditions of Figure 2 [ie. the graph above], this saturation force is beyond 10 kg. The saturation point is more a function of pressure than force. The saturation pressure of a typical FSR is on the order of 100 to 200 psi. For the data shown in Figures 2, 3 and 4, the actual measured pressure range is 0 to 175 psi (0 to 22 lbs applied over 0.125 in^2). Forces higher than the saturation force can be measured by spreading the force over a greater area; the overall pressure is then kept below the saturation point, and dynamic response is maintained. However, the converse of this effect is also true, smaller actuators will saturate FSRs earlier in the dynamic range, since the saturation point is reached at a lower force.

In summary, the weight applied can go over 10 Kg providing that weight is spread over the sensing area. The larger FSRs ([such as this one][2]) are better suited for this purpose as they have a larger area for which to spread the pressure.

Note: It is quite possible that with 100 Kg you could irreversibly damage the FSR, particularly if the weight isn't spread over the sensor area.

Measuring an analog voltage from the sensor is possible so that it can be fed into one of the analog pins of the Arduino. [This Adafruit page][3] has a nice table at the bottom showing the analog voltage that you get when you put the sensor in a [voltage divider network][4] (ie. in series) with a 10K ohm resistor.

  [1]: https://i.stack.imgur.com/dHfY5.png
  [2]: https://www.sparkfun.com/products/9376
  [3]: https://www.adafruit.com/product/166
  [4]: https://learn.sparkfun.com/tutorials/voltage-dividers


message:
Arduino ESP8266 direct/fast control of the digital pins

How does one control a digital pin directly avoiding the slow digitalWrite or digitalRead?

body:
After a weekend of searching and trying, here is what I was looking for:

It is slightly different than for the AVR chips. There is one register for setting the pins to HIGH and another one to set the pins to low.

Setting the pin HIGH:

    GPOS = (1 << PIN_OUT);

Setting the pin LOW:

    GPOC = (1 << PIN_OUT);

using this, I managed to speed up my code by a factor of three. It is not as dramatic as for the AVR chips, since the digitalWrite function is much more simple for the ESP8266.

**Edit Further experiments show it is 10x faster**: 910nsec for `digitalWrite` vs. 88nsec using `GPOC` or `GPOS`!


body:
Unfortunately, Ratchet Freak's answer is specific to AVR, and isn't how the ESP8266 works.

It looks like the ESP8266 does indeed have registers for doing exactly this, which would let you set all 16 GPIO pins (GPIO0 through GPIO15, 16 is a different thing entirely) with a single operation. There's also a SET register, which sets the pins corresponding to 1 bits, and ignores pins corresponding to 0 bits, and a CLEAR register, which is the other way around.

Something I found on a forum said a user went from ~800KHz to ~5.7MHz toggling pins using these direct registers, that sounds about right.

One version of this is found in `eagle_soc.h`. The relevant bits from the header to get you started:

    #define GPIO_REG_READ(reg)                         READ_PERI_REG(PERIPHS_GPIO_BASEADDR + reg)
    #define GPIO_REG_WRITE(reg, val)                 WRITE_PERI_REG(PERIPHS_GPIO_BASEADDR + reg, val)
    #define GPIO_OUT_ADDRESS                         0x00
    #define GPIO_OUT_W1TS_ADDRESS             0x04
    #define GPIO_OUT_W1TC_ADDRESS             0x08

So, if I've understood this correctly (and I haven't done any real testing, just going off the spec sheet and the header and posts elsewhere):

    GPIO_REG_WRITE(GPIO_OUT_ADDRESS, 0xF0F0);

would set GPIO 4-7 and 12-15 to high, and 0-3 and 8-11 to low. In one operation. But there's more! Look at those `W1TS` and `W1TC` names. Those are set and clear registers. Which means you *don't* have to mask things. Instead of grabbing the current value, masking a bit in or out, and then writing it back, you can use those:

    GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, 0x1);

This will set GPIO0 high, and not affect any other bits.

This is also offered in a cleaner/simpler (??) form in `esp8266_peri.h`, which simplifies it to:

    GPOS = 0x1;

for setting a bit. This is what's actually called by the arduino library's digitalWrite (for pins other than GPIO16):

    extern void ICACHE_RAM_ATTR __digitalWrite(uint8_t pin, uint8_t val) {
      pwm_stop_pin(pin);
      if(pin < 16){
        if(val) GPOS = (1 << pin);
        else GPOC = (1 << pin);
    [...]

But definitely be aware of this if you're doing anything fast, because writing multiple pins with a single operation is going to be *way* faster than multiple function calls. Without this, this chip can't even toggle bits as fast as a 16MHz Arduino.


message:
What are these wires called?

I'm currently developing a quad copter for my school project and I am coming to the part where I am collecting all the parts before I assemble everything.

I have recently encountered a roadblock. I am going to solder an Arduino nano onto a strip board, but the problem is I cannot seem to find cables/wires to connect the nano to the module.

Excuse my ignorance, but where can I find these cables for soldering and what are they called?

[![][1]][1]

  [1]: https://i.stack.imgur.com/DSshL.jpg

body:
If they are an intentional part of the design they are *jumper wires*. If they are to correct a mistake in the design they are *bodge wires*.

They aren't anything special, just wire. They look to be in the range of 24 to 30 AWG and PVC jacketed.

You can buy it in any electronic store.

You can also salvage it from things like old SCART cables and similar things.


body:
Read this [tutorial][1] about working with wires.

Sorry for the link-only answer, but I can't copy the article in full.

  [1]: https://learn.sparkfun.com/tutorials/working-with-wire


body:
>  but where can I find these cables for soldering and what are they called?

hook-up wires.

pretty much any hardware stores should have it.


body:
If you want to wire your board with stranded wire, you can ask for ***NYAF*** and solder the edges with the tip. Otherwise you can ask for ***hook-up wires***.

But if you are using breadboard, which i recommend you to use solid wire, you can ask it as ***wire wrap***.

You can find them at an electronic store.


message:
Atmega328p screen + midi, possible?

I'm trying to build this Midi2CV (control voltage for analog synths) using a Arduino Nano:

https://photos.app.goo.gl/3IhhFL3PrLELLODB3

I was hoping to use this Nokia screen too for settings and debugging purposes, but I just realized there's only one hardware serial port on 328p and software serial seemed to be doomed for MIDI:

https://arduino.stackexchange.com/questions/38567/softwareserial-too-slow-for-midi

So I have three peripherals:

* DAC (MCP4822)
* Nokia 5110 screen
* MIDI

I've gotten both the DAC and screen to work fine on normal pins so I'm thinking I'm good with just using the hardware serial for MIDI and the DAC and screen can use software. Or am I in for a world of pain without getting a more powerful chip with more hardware serial ports? And if so, what's the recommendation? (shoestring budget)

body:
Of your three functions (DAC, screen and MIDI) only one (MIDI) actually uses UART.

The other two devices are SPI devices which, while it is a *serial* protocol isn't UART (serial is a *concept* not a protocol).

Connect the DAC and screen to the SPI port (you can share SCK, MOSI and MISO, but select different CS pins) and you have the UART pins (0/1) available for MIDI use - as long as you don't want to use the USB connection which is linked directly to those pins.


message:
LCD is not showing any text

I'm using LCD QC1602A with a 10k potentiometer and changing contrast. It works well but the problem is that no text is appearing.

I'm using the LCD hello world examples and a few other examples. I tried reconnecting wires at least 5 times but every time it's the same problem. I connected it [like this][1] but the screen is not displaying any text at any contrast.

  [1]: https://www.arduino.cc/en/uploads/Tutorial/LCD_Base_bb_Fritz.png

PS: It was showing white squares only in the top row, and now it's in both rows.

body:
> It works well but the problem is that no text is appearing.

it works well and yet no text is appearing?

so there is or there isn't a problem?

> PS: It was showing white squares only in the top row, and now it's in both rows.

when correctly initialized, it should one row of blocks in the first row.

if it shows two rows of blocks, either it is not correctly initialized or the contrast is too much.


body:
Two rows of white squares means that the driver chip has been successfully initialised to run in a 2x16 mode (it defaults to 1x16 which was the 1 row of squares you had originally).

So that means that you are configuring the display at least partially correctly.

You should adjust the pot so that you can just about see the squares. The squares are the background and the text would appear over them. If they are too bright you won't see the text. So adjust the contrast until you can just see that there are squares there.

If the wiring is correct and the code is correct then you should be able to see the text.


message:
Fade sketch stuck in mathematical loop

I tried to edit the Fade sketch such that the max intensity the PWM reaches is controlled by a potentiometer. I used analogRead() on the potentiometer and converted the 10bit value to 8bit equivalent(by dividing by 4 and rounding) to feed into analogWrite. I am new to arduino and I dont know a more elegant way to do this, sorry!

It worked generally but **sometimes** while turning the potentiometer, the **LED would be stuck at a fixed level of brightness**. I have to reset the Arduino or turn the pot to the extremes to remove this "loop". I set up serial monitor to look at the values of brightness. It does not always happen at the same position of the potentiometer.

I deduce that it is a mathematical error causing this loop, likely due to my poor use of the if() function. Can anyone offer me a reason for this?

*I tested with both the Uno and Nano, as well as TinkerCad simulator with similar results.

[![Basically like this but with positive lead on pin 11 instead of 13][1]][1]
[![Brightness stuck at specific values][2]][2]

-----------------------------Fade sketch edited by me----------------------

    /*
     Fade, edited with maximum intensity controlled by potentiometer reading
     */

    int led = 11;           // the PWM pin the LED is attached to
    int brightness = 0;    // how bright the LED is
    int fadeAmount = 5;    // how many points to fade the LED by
    int potPin = A0;    // set the pin that reads the potentiometer voltage
    int potValue = 0;   // declare and initialize potValue
    int potValueConverted = 0; // 10bit potValue converted to 8bit equivalent

    // the setup routine runs once when you press reset:
    void setup() {
      // declare pin 9 to be an output:
      pinMode(led, OUTPUT);
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      //read the voltage at the pot
      potValue = analogRead(potPin);

      //convert 10bit input into 8bit output by dividing by 4, rounding to avoid need for float variable
      potValueConverted = round(potValue/4);

      // set the brightness of pin 11:
      analogWrite(led, brightness);

      // change the brightness for next time through the loop:
      brightness = brightness + fadeAmount;

    Serial.println(brightness);

      // reverse the direction of the fading at the ends of the fade:
      if (brightness <= 0 || brightness >= potValueConverted) {
        fadeAmount = -fadeAmount;
      }

      // wait for 30 milliseconds to see the dimming effect
      delay(30);
    }

----------------------------------------------------------------------------

  [1]: https://i.stack.imgur.com/IovL8.jpg
  [2]: https://i.stack.imgur.com/5YXPZ.png

body:
> the LED would be stuck at a fixed level of brightness.

that's by design: think about what happens when potValueConverted is very small.

edit:

to change the brighness, I would do this:

      brightness += fading; //change brightness;
      if ((brightness < BRIGHTNESS_MIN) || (brightness > BRIGHTNESS_MAX)) {fading = -fading; brightness += fading;} //bound brightness to _MIN and _MAX


body:
It seems like the problem occurs when brightness is a lot higher than potValueConverted.

For example, lets say our brightness=100, potValueConverted=50, this triggers the latter "if" condition, i.e.
> brightness >= potValueConverted

and at the next iteration, brightness = 105 (or 95), both of which will satisfy the condition for fadeAmount to flip its polarity, thus resulting in the brightness value oscillating between 105 and 100 (or 100 and 95).
This results in the LED getting stuck at the same level of brightness.

a quick hack fixes this problem (as far as I can tell)

     if (brightness <= 0 ) {
        fadeAmount = 5;
      }
     if (brightness >= potValueConverted +5 ) {
        fadeAmount = -5;
      }

**note the +5 for the second if statement is to ensure that the brightness value does not become negative.


message:
Can you use an input pin instead of ground in Arduino circuitry?

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

  [1]: https://i.stack.imgur.com/7IXYd.jpg

Beginner here: Would the circuit in the picture work or do input pins not absorb the energy as ground does? I know setting the pin as an input makes the direct 5V connection safe but maybe I'm mistaken. I'm trying to understand the nature of how these connections are made. Thank you in advance!

body:
If you remove the ground wire, digital pin 2 will be left "floating" until the button is pressed, and this is not a good thing to do:

https://electronics.stackexchange.com/questions/83133/arduino-digitalread-reading-wrong

There is a way to eliminate the pull-down resistor and simplify the wiring by using pinMode(BUTTON_PIN, INPUT_PULLUP); in setup(). You would connect one "leg" of the N.O. momentary push button switch to ground and the other "leg" to Pin 2. You will still need to "debounce" the switch, and for that I recommend a library.

There is a link to a good library here: https://playground.arduino.cc/Code/Bounce.

The example sketch called bounce.ino is a good place to start.


body:
An input pin can only sense the voltage that is applied to it - whether it is above or below a pair of thresholds.

In your existing circuit when the button is not pressed the voltage sensed by the pin is 0V because it is connected to 0V (also known as Ground) through the resistor. When you press the button the input pin is connected directly to +5V, so the pin senses 5V.

If you remove the resistor or the connection to ground the pin can still sense 5V on it when the button connects it to 5V, but when you release the button the input pin then isn't connected to anything at all. It's not connected to 0V, so it can't sense what voltage is there - there simply isn't any voltage connected to it (no voltage isn't the same as 0V).

In this case the pin is said to be "floating". It's neither HIGH (5V) nor LOW (0V), it's just dangling around not knowing what it's doing.

If you want to get more technical and look at the mechanics of it, it's helpful to know that the gate of a MOSFET (which is what the input pin actually is) looks to all intents and purposes like a small capacitor.  When you connect the input pin to +5V the capacitor is charged up (current flows into it from 5V to charge it). When you connect the input pin to 0V it discharges (current flows out of the capacitor down to 0V). When charged you have a HIGH and when discharged you have a LOW.

However when a charged capacitor has no connection it (for a certain amount of time, due to *self discharge*) keeps hold of its charge. So if you charge it with +5V and then disconnect it you will still get +5V on the capacitor. That is until it discharges through internal leakage currents.

Those leakage currents though are so small and the capacitor is so sensitive that the input pin acts like a radio antenna. It picks up *noise* from the surrounding area (electromagnetic waves) which can charge and discharge the capacitor pretty much at random. So at times you may see the input as HIGH and at other times as LOW, purely depending on chance. And the longer your wires the more noise it will pick up.

The worst source of noise is the 50/60Hz mains hum that is all around you. You can see this in reality if you graph the voltage on a disconnected ADC pin and bring your hand close to it - you act like a capacitively coupled antenna and you can see the mains waveform on your graph.

It's the same on a digital input pin, except that it converts it to a square wave as it passes the thresholds (you might like to look at *schmitt triggers* for more detail about how it does that).

So adding the pull down (or pull up if you prefer) resistor is critical to making the input pin see what you want it to see, and not just random noise.

Since the input is like a capacitor selecting the right value of resistor can be quite important in some situations. For a simple button like this there's nothing to worry about, but for something like a rotary encoder where the input signal may change more rapidly the resistor value does become more of a concern.  Have too high a value and the gate will take too long to discharge (or charge if it's a pull up resistor). Too low and too much current could be wasted through the resistor when the button (or encoder) is active (potentially damaging the button if it's a low current sensitive device).


message:
How do I make the HC-05 bluetooth module take data from the HC-SRO4, and then send it to my Android app?

Currently, I have an Arduino Uno set up, with a HC-SRO4 ultrasonic sensor printing distances of objects in front of it on a scale from 1-15 to the serial monitor. I want to attach the HC-05 bluetooth module and do the following:
First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

I understand the Android part may be out of scope of this forum, but please try to help me with taking data from the serial monitor and have it transmit the data.

Here is the code I have for the ultrasonic sensor:

    const int trigPin = 9;
    const int echoPin = 10;
    // defines variables
    long duration;
    int distance;
    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600); // Starts the serial communication
    }
    void loop() {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance = duration * 0.034 / 2;
      // Prints the distance on the Serial Monitor
      Serial.print("Distance: ");
      Serial.println(distance);
    }

body:
> First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

No. What you do is you connect your Bluetooth module to two digital pins, which you'll use, along with the `SoftwareSerial` library, just the way you are using currently the `Serial` object. Look at the `SoftwareSerial` examples in the IDE.

Before you use the HC-05 module, and transmit data, you'll have to make sure it is set up properly (baud rate, name, PIN code, etc). Plenty of code and tutorials on Google about that.


body: Use software serial library and connect your HC-05 TX RX pins accordingly, to transmit/recieve the ultrasonic data using bluetooth. From playstore you will get bluetooth terminal software. Install it in your smart phone. Now connect your phone's bluetooth to HC-05 using that software. Now you can see in that app, all data you are receiving via bluetooth. you can also transmit data using that app. If you want to develop your own app, maybe you can check out MIT app inventor. Simple and fast.


message:
Can you connect more sensors of the same type to a single board while not using up more pins than if you were to use a single sensor?

I'm as new as you can be at Arduino programming and specific electronics, so I don't even know if I'm asking the correct question.

I've ordered an Arduino a breadboard and some PCBs and now I'm looking for a few parts that I should buy in order to get some basic projects done.

I'd like to start with a garden automation project, a fairly simple one.
Humidity sensors, temperature sensors and a water pump.

Can I connect all (4) of the humidity sensors to a single local circuit and then connect that to the board so I can limit the number of input pins used? I'd still need to get independent readings from the sensors. Or would I need to use another board incorporating RF/Wireless/Bluetooth modules to receive the information and then send it to the board for further processing?

I'm sorry if what I just said makes no sense and I thank you for your time.
All I have is low-mid level electronic related experience. Battery checkers, Power supplies, basic light sensors, PCB making ETC.

body:
If the connection is a digital sense pin then you can use a parallel-in serial-out IC to read them all simultaneously and then shift it in. Takes up 3 pins on the arduino a latch a clock and a data pin.

If the connection is SPI then you can connect the clocks and MISO pins together and then need a slave select for each. you can control many of them with a serial in parallel out IC or a decoder.

If the connection is with the I2C protocol and each device has a different address then you can simply connect them all in parallel.

If the sensor has an analog output then you can use an analog to digital converter (ADC) which can have multiple inputs and often have a serial interface.


body:
If you do not need them to run simultaneously, you can use a multiplexer such as this one from Sparkfun:

https://www.sparkfun.com/products/9056


body:
It all depends on the interface between the Arduino and the sensor.

For example the DS18B20 uses the 1-Wire bus. That requires one digital pin and a number of DS18B20 can be connected to the same 1-Wire bus. Every DS18B20 has an unique identifier that makes that possible.

Humidity sensors like DHT11 or DHT22 require a pin for each sensors. They are not accurate anyway.

Sensors like the BME280 use the I2C bus. The I2C bus allows that many sensors can be connected. Each I2C sensor has an I2C address. Sometimes a sensor can have just one I2C address and therefor only one of such a sensor can be connected to the I2C bus. But sometimes a trick is possible to have more.

This list goes on and on and on. A lot is possible without extra hardware.

Because you are going to use sensors and many sensors are 3.3V, did you buy a 3.3V Arduino board ?


message:
Cannot create a PWM with 20% duty cycle using micro() timer

I have been working with Arduino for almost a year, because I found it easy for beginners in electronics. But now, I have a major problem, I'm trying to get rid of my delay() function because I want my Arduino Nano to handle to tasks at once:

1-Read MIDI data and transfert it into a pwm signal, as well as monitoring the on and off of the signal (which are bytes). This part works correctly, but i'm not using the mirco(), i'm using a library called Timer1.

2-Generate a PWM signal of 20% dutycycle with a frequency ranging from 1 to 103 Hz using a potentiometer to adjust the frequency.

So, what happens is that the signal I measure on my oscilloscope is a PWM at 50% duty cycle and with frequencies that don't match my calculations at all. Also, It doesn't change smoothly, the frequency goes from 159Hz to let's say 180Hz only at one particular point on the potentiometer, just like if all the rest of it was useless. I decided to monitor all my values with Serial and everything was good, the values were OK and nothing was wrong. Then I decided to change all my variables to floats so I could maybe get more precision... Didn't work as well. So now I'm kind of desesperate.

    //MANUAL MODE TEST WITH MICROS()
    //VARIABLES ASSIGNEMENT
    unsigned long current=0.0;
    unsigned long previous=0.0;

    float TimeOn = 0.0;
    float TimeOff = 0.0;
    float manuelF = 0.0;
    float sensor = 0.0;

    int pin = 11;

    byte state = LOW;

    //SETUP AND PIN ASSIGNEMENT
    void setup() {
      pinMode(9, OUTPUT);//MUSIC SIGNAL OUTPUT
      pinMode(11, OUTPUT);//MANUAL SIGNAL OUTPUT
      pinMode(A5, INPUT);//POTENTIOMETER MANUAL
      pinMode(A6, INPUT);//POTENTIOMETER MUSIC
      Serial.begin(9600);
    }

    void loop() {

      sensor = analogRead(A5);
      manuelF=((sensor+10.0)/10.0); //Capture la fréquence sur A5
      TimeOn=1000000.0*(0.2*(1.0/manuelF));
      TimeOff=1000000.0*(0.8*(1.0/manuelF));
      current = micros();

      Serial.println(TimeOn);

      //Serial.print("A5 read:");
      //Serial.println(analogRead(A5),8);
      //Serial.println("-----------");
      //Serial.print("Fréquence: ");
      //Serial.println(manuelF,8);
      //Serial.print("timeon:");
      //Serial.println(TimeOn,8);
      //Serial.print("timeoff:");
      //Serial.println(TimeOff,8);

      if ((state == LOW)&&(current - previous >= TimeOff)){
          state = HIGH;
          digitalWrite(pin,state);
          previous = current;
        }
      else{
        if (current - previous >= TimeOn){
          state = LOW;
          digitalWrite(pin,state);
          previous =current;
        }

      }
     }

As you can see I'm still monitoring the TimeOn variable. Well, It shows exactly (to 4 micro seconds precise) the time that it is supposed to be ON.

My output at that moment is a 50% duty cycle with a frequency of 53Hz when I pass the 7k on the potentiometer (it is a 10k). Before that, it doesn't even outputs a signal.

What is going on?

EDIT#1:
I have done the modifications that @Edgar Bonet suggested me. It partially worked. What i'm left with now is a PWM that can go from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

body:
You wrote:

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

    if ((state == LOW)&&(current - previous >= TimeOff)){
        state = HIGH;
        digitalWrite(pin,state);
        previous = current;
      }
    else{
      if (current - previous >= TimeOn){
        state = LOW;
        digitalWrite(pin,state);
        previous =current;
      }

While you probably mean:

    if (state == LOW && current - previous >= TimeOff) {
        state = HIGH;
        digitalWrite(pin, state);
        previous = current;
    }
    else if (state == HIGH && current - previous >= TimeOn) {
        state = LOW;
        digitalWrite(pin, state);
        previous =current;
    }


body:
I have found the problem. Part of it was the code, thank you @Edgar Bonet. The other part was the pin I was using to generate the PWM signal. Throughout my reasearch, I found that on the arduino nano, the timer pins are the same than those on the arduino Uno. Thus:

Timer0 :pins 5-6

Timer1 :pins 9-10

Timer2 :pins 3-11

Since I was using the function micros() which uses the timer0, I had to send the signal to the right pin. I cannot describe why it did send a certain PWM to discrete frequencies, but the important is that it now works.

In parallel, because the other part of my program is using timer1, the two data transmission won't interfere with each other!

Time inversted in researches: 4hours

Hope this helps someone! Thanks.


message:
Trying to flash ESP8266 with Arduino UNO

This is my first project other than some of the starter projects. I am trying to flash the firmware onto an ESP8266 wifi module using and arduino uno. It would be nice to know if anything is wrong/redundant in the picture below (I was looking at a few different diagrams to try and figure out what was right). I have found some tutorials saying that TX should go to RX instead of TX to TX so that is what I am doing. I am trying to use the level shifter to go from 5v to 3.3v because I wasn't sure if I had enough current going to the ESP8266 when just directly hooked up to 3.3v on arduino (I read in a few places that the arduino doesn't have a strong enough current to operate the wifi module). I found some tutorials which use a voltage regulator, I tried doing that but had the same results I am getting now. I have also read that you don't need a level shifter or voltage regulator but it might harm the components so I haven't tried that way yet.

I am the point where I plug it into my computer via USB, open the Arduino IDE > Tools > Serial Monitor.

I type the command 'AT' and there is no response - I tried every baud setting. Sometimes it randomly outputs a question mark or two.

Other things of note: When I plug it in, the ESP8266 blue light flashes once. When I was modding the header pins of the ESP8266 I kind of fumbled it a lot - could that have broken some aspect of the chip? Also while modding the header pins, I pushed them all in to make them longer and bent them on the other side, so it would work with the breadboard - I'm wondering if the soldering connections need to be stronger (you can kind of see in the picture).

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

This is the schematic for what I was trying to achieve basically, while also using the level shifter:

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

Any advice with regards to anything you see here would be great, I am new to the world of circuits.

Note: there is a ground wire that is not in the frame of the picture connecting one side of the breadboard to the other, that part of this is one thing I was wondering about.

  [1]: https://i.stack.imgur.com/Dbeyn.jpg
  [2]: https://i.stack.imgur.com/bOvxB.jpg

body:
You do not need the level shifter. The input pins of the ESP8266 contain over-voltage (though not over-current) protection. All you need to do is limit the current that can flow through the over-voltage protection circuit, and all that needs is a series resistor in the region of 100Ω or so.

And the Arduino already has that protection between the ATMega16U2 and the TX/RX pins anyway in the form of 100Ω resistors that it uses to prevent short circuits between the two MCUs on the board, so you don't need to add it in this instance (you do if you want to communicate between the ATMega328P and the ESP8266, but only between the Arduino's TX and the ESP8266's RX pins).

When it comes to actively running the ESP8266 it can be beneficial to power it from a more powerful 3.3V regulator than the 150mA one on the Arduino since when transmitting the ESP8266 wants more than that, but for simple flashing of it the Arduino's 150mA regulator should do the job fine.

One thing to note though: I don't like the look of the soldering on your ESP8266 pins. I would be inclined to re-solder those joints. Add a bit of flux to help the solder flow properly.


body:
What I have done was connecting ESP8266 and UNO as the schematic described.

But instead of using the default program in ESP8266, I programmed ESP8266 via UNO using the ESP8266 Library on Arduino IDE

If your way still did not work you can maybe try this method.


body:
I think I may be able to help clarify things a bit here:

You are not trying to "flash" the ESP01 (the kind you have) board, but you are trying to talk to the AT command firmware it came installed with.

Also, there's a sort of pingback sketch (I forget the name and can't find it, but it basically uses a SoftwareSerial and copies characters from one to the other and vice versa) that is used to configure the ESP01 that's *normally* used, but you don't seem to be using it here (it may not be worth the effort, either, since it's tricky to get working sometimes).

In this case, it seems that you are trying to do one of two things:

If you are trying to talk to the ESP01 module **from the computer** connect the TX to the TX pin and the RX to the RX pin. This is because the Arduino board's serial adapter is *already* connected in the mirrored direction, and you are using that to talk to the ESP01. Do note that you should, **before** connecting the ESP01, upload the Blink sketch or similar to the Arduino so that it's not trying to use the Serial connection too.
See http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/ for more information on that use case.

On the other hand, if you are trying to talk to the device from the Arduino itself (as in, the Arduino has a program that needs WiFi access), you'd want to connect it RX to TX and TX to RX. Of course, when doing this, the Arduino should already have its program uploaded since the ESP01 would cause issues uploading firmware via Serial afterward (they both talk at once).

Lastly, these things are REALLY finicky, so make sure you set the baud rate and use NLCR end-of-line signaling.


message:
Stability issue with webserver and smartmeter logging

In the past few months I have successfully logged the data from the power and gas meter in my house to a remote web server.

Now I try to add the ability to enable and disable my doorbell over the internet.

Although it seems to work, I experience 2 problems.

**Problems**

 - Arduino freezes after a few hours

 - When the meter reading is transmitted, the doorbell can not be
   switched.

**Questions**
> *Is there a way to give priority to control the doorbell?*

and ..

> *is there a way to find out why the Arduino freezes after a while?*

**Setup:**

 - Arduino Mega 2560 board
 - Ethernet shield
 - LCD display
 - Relay
 - light sensor(for backlight control)
 - serial connection to smart power/gas meter

    //V1.1: Cleaned up messy code
    #include <LiquidCrystal_I2C.h>
    #include <Wire.h>  // Comes with Arduino IDE
    LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    #include <AltSoftSerial.h>
    #include <SPI.h>
    #include <Ethernet.h>

    //setup ethernet server
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //assign arduino mac address
    byte ip[] = { 192, 168,  178, 95}; // ip in lan assigned to arduino
    byte gateway[] = { 192,  168, 178,  1}; // internet access via router
    byte subnet[] = {  255,  255,  255,  0}; //subnet mask
    EthernetServer server(84); //server port arduino server will use
    char thingSpeakAddress[] = "";
    IPAddress myDns(8, 8, 8, 8);
    EthernetClient client;
    String writeAPIKey = "XXXMX2WYYR0EVZZZ";
    String tsData = "hello"; //dummy data
    String readString; //used by server to capture POST request
    const int updateThingSpeakInterval = 20 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
    // Variable Setup
    long lastConnectionTime = 0;
    boolean lastConnected = false;
    int failedCounter = 0;
    unsigned long int updateCounter = 0; //set refresh counter to 0
    //////////////////////
    //slimme meter////////
    /////////////////////
    char c;
    AltSoftSerial altSerial;
    const int requestPin = 48; //data pin connected to smartmeter
    char input; // incoming serial data (byte)
    bool readnextLine = false;
    #define BUFSIZE 75
    char buffer[BUFSIZE]; //Buffer for serial data to find \n .
    int bufpos = 0;
    long mEVLT = 0; //Meter reading Electrics - consumption low tariff
    long mEVHT = 0; //Meter reading Electrics - consumption low tariff
    long mEAV = 0; //Meter reading Electrics - Actual consumption
    long mG = 0; //Meter reading Gas
    //unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
    // the "L" is needed to use long type numbers

    //const unsigned long postingInterval = 10 L * 1000 L; // delay between updates, in milliseconds, the "L" is needed to use long type numbers
    /////////////////////////////////////////
    //photcel////////controls lcd backlight//
    ////////////////////////////////////////
    int photocellPin = 5; // the cell and 10K pulldown are connected to a0
    int photocellReading; // the analog reading from the analog resistor divider
    //boolean doorbell = true;

    int creset = 43; //Telling arduino that you are connecting pin 43 with reset

    //////////
    //setup///
    //////////
    void setup() {
      Wire.begin();
      digitalWrite(22, LOW);
      digitalWrite(creset, HIGH);
      pinMode(creset, OUTPUT);
      pinMode(22, OUTPUT); //pin selected to control
      pinMode(6, OUTPUT); //pin selected to control
      pinMode(7, OUTPUT); //pin selected to control
      pinMode(8, OUTPUT); //pin selected to control
      //pinMode(5, OUTPUT); //pin 5 selected to control
      Ethernet.begin(mac, ip, myDns, gateway, subnet);
      server.begin();
      Serial.begin(9600);
      altSerial.begin(9600);
      Serial.println(F("Smarthome controller")); // keep track of what is loaded
      Serial.println(F("Send a g in serial monitor to test client")); // what to do to test client
      lcd.begin(20, 4); // initialize the lcd for 16 chars 2 lines, turn on backlight
      // sensorValue = analogRead(sensorPin);
      lcd.backlight(); // finish with backlight on
      //-------- Write characters on the display ------------------
      // NOTE: Cursor Position: Lines and Characters start at 0
      lcd.setCursor(0, 0); //Start at character 4 on line 0
      lcd.print("Smarthome controller");
      delay(1000);
      lcd.setCursor(0, 1);
      lcd.print("powerd by arduino");
      delay(1000);
      lcd.print("                  ");
      lcd.setCursor(0, 2);
      lcd.print("");
      lcd.setCursor(0, 3);
      delay(1000);
      lcd.print("Slimmemeter:     ");
      //lcd.backlight(); // turn on backlight.
      lcd.setCursor(0, 2);
      lcd.print("Doorbell: onn      ");
    }
    void loop() {
      if (updateCounter > 400) {
        digitalWrite(creset, LOW);  // Reset arduino
      }
      // Update ThingSpeak
      if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {
        decodeTelegram();
      }
      // Check if Arduino Ethernet needs to be restarted
      if (failedCounter > 3) {
        startEthernet();
      }
      lastConnected = client.connected();
      EthernetClient client = server.available();
      if (client) {
        while (client.connected()) {
          if (client.available()) {
            char cl = client.read();
            //read char by char HTTP request
            if (readString.length() < 100) {
              //store characters to string
              readString += cl;
              //Serial.print(c);
            }
            //if HTTP request has ended
            if (cl == '\n') {
              ///////////////
              Serial.print(readString); //print to serial monitor for debuging
              //now output HTML data header
              if (readString.indexOf('?') >= 0) { //don't send new page
                client.println("HTTP/1.1 204 Zoomkat");
                client.println();
                client.println();
              } else {
                client.println(F("HTTP/1.1 200 OK")); //send new page on browser request
                client.println(F("Content-Type: text/html"));
                client.println();
                client.println(F(""));
                client.println(F(""));
                client.println(F("<TITLE>Smarthome</TITLE>"));
                client.println(F(""));
                client.println(F(""));
                client.println(F("
Smarthome control page
"));
                // DIY buttons
                client.println(F("Deurbel"));
                client.println(F("ON"));
                client.println(F("OFF

"));

                client.println(F("Pins"));
                client.println(F(" ALL ON"));
                client.println(F(" ALL OFF"));
                client.println(F(""));
                client.println(F(""));
                client.println(F(""));
                client.println(F(""));
              }
              delay(1);
              //stopping client
              client.stop();
              if (readString.indexOf("**secretcode**") > 0) //checks for secretkey
              {
                ///////////////////// control arduino pin
                if (readString.indexOf("on2") > 0) //checks for 2
                {
                  digitalWrite(22, LOW); // set pin 5 high
                  //Serial.println(F("Led 5 On"));
                  //Serial.println();
                  lcd.setCursor(0, 2);
                  lcd.print("Doorbell: on      ");
                  //doorbell = true;
                }
                if (readString.indexOf("off3") > 0) //checks for 3
                {
                  digitalWrite(22, HIGH); // set pin 5 low
                  //Serial.println(F("Led 5 Off"));
                  //Serial.println();
                  lcd.setCursor(0, 2);
                  lcd.print("Doorbell: off      ");
                  //doorbell = false;
                }

                //clearing string for next read
                readString = "";
              }
            }
          }
        }
      }

      //lcd.setCursor(0, 0); //Start at character 4 on line 0
      //lcd.print("SMARTHOME CONTROLLER;.");
      //String analogValue = String(analogRead(A5), DEC);
      photocellReading = analogRead(photocellPin);

      //lcd.setCursor(0, 1);
      //lcd.print(photocellReading);
      if (photocellReading < 800) {
        lcd.backlight(); // turn on backlight.
      } else {
        lcd.noBacklight(); // turn on backlight.
      }

    }

    ////////////////////////////////////////////////////////////////////////////
    //////////////////////////FUNCTIONS/////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    void updateThingSpeak(String tsData)
    //void sendGET() //client function to send and receive GET data from external server.
    {
      //lcd.setCursor(0, 2);
      // lcd.print("                   ");
      lcd.setCursor(13, 3);
      lcd.print("verstur");
      // delay(1000);
      if (client.connect(thingSpeakAddress, 80)) {
        client.print("GET /smarthome/log.php?stroomLaag=");
        client.print(mEVLT);
        client.print("&stroomHoog=");
        client.print(mEVHT);
        client.print("&stroomVerbruik=");
        client.print(mEAV);
        client.print("&gasStand=");
        client.print(mG);
        client.println(" HTTP/1.1");
        client.println("Host: .nl");
        client.println("User-Agent: arduino-ethernet");
        client.println("Connection: close");
        client.println();
        lastConnectionTime = millis();
        updateCounter++;
        Serial.print("Connecting to log server...");
        Serial.println(updateCounter);
        //x=x+1; //page upload counter
        // lcd.setCursor(0,3);
        // lcd.print("Data send           ");
        //delay(1000);
        lcd.setCursor(13, 3);
        //lcd.print("                    ");
        lcd.print("ok        ");
        lcd.setCursor(16, 3);
        lcd.print(updateCounter);
        if (client.connected()) {
          Serial.println("Connecting to suscesfull...");
          //Serial.println();
          failedCounter = 0;
        } else {
          failedCounter++;
          Serial.println("Connection to failed (" + String(failedCounter, DEC) + ")");
          Serial.println("connection failed");
          Serial.println();
          lcd.setCursor(13, 3);
          lcd.print("fout");
          lcd.setCursor(16, 3);
          lcd.print(String(failedCounter, DEC));
        }
      } else {
        failedCounter++;
        Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
        Serial.println();
        lastConnectionTime = millis();
      }
      while (client.connected() && !client.available()) delay(1); //waits for data
      while (client.connected() || client.available()) { //connected or data available
        char cl = client.read(); //gets byte from ethernet buffer
        //readString += c; //places captured byte in readString
        //Serial.print(c); //print raw data
      }
      client.stop(); //stop client
      readString = ""; //clear readString variable
    }

    ////////////////////////////////////////////////////

    void startEthernet() {
      client.stop();
      Serial.println("Connecting Arduino to network...");
      Serial.println();
      delay(1000);
      // Connect to network amd obtain an IP address using DHCP
      if (Ethernet.begin(mac) == 0) {
        Serial.println("DHCP Failed, reset Arduino to try again");
        Serial.println();
      } else {
        Ethernet.begin(mac, ip, gateway, gateway, subnet);
        server.begin();
        Serial.println("Arduino connected to network using DHCP");
        Serial.println();
      }
      delay(1000);
    }

    ////////////////////////////////////////////////////

    void decodeTelegram() {
      long tl = 0;
      long tld = 0;
      if (altSerial.available()) {
        //input = altSerial.read();
        c = altSerial.read();
        // --- 7 bits instelling ---
        c &= ~(1 << 7);
        char inChar = (char) c;
        //Serial.print(c);
        input = c;
        //Serial.println(input);
        //char inChar = (char)input;
        // Fill buffer up to and including a new line (\n)
        buffer[bufpos] = input & 127;
        bufpos++;
        if (input == '\n') { // We received a new line (data up to \n)
          if (sscanf(buffer, "1-0:1.8.1(%ld.%ld", & tl, & tld) == 2) {
            tl *= 1000;
            tl += tld;
            mEVLT = tl;
          }
          // 1-0:1.8.2 = Elektra verbruik hoog tarief (DSMR v4.0)
          if (sscanf(buffer, "1-0:1.8.2(%ld.%ld", & tl, & tld) == 2) {
            tl *= 1000;
            tl += tld;
            mEVHT = tl;
          }
          // 1-0:1.7.0 = Electricity consumption actual usage (DSMR v4.0)
          if (sscanf(buffer, "1-0:1.7.0(%ld.%ld", & tl, & tld) == 2) {
            mEAV = tl + tld;
          }
          // 0-1:24.2.1 = Gas (DSMR v4.0) on Kaifa MA105 meter
          //if (strncmp(buffer, "0-1:24.2.0", strlen("0-1:24.2.1")) == 0) {
          if (sscanf(strrchr(buffer, '(') + 1, "%d.%d", & tl, & tld) == 2) {
            mG = (tl * 1000) + tld;
          }
          //}
          // Empty buffer again (whole array)
          for (int i = 0; i < 75; i++) {
            buffer[i] = 0;
          }
          bufpos = 0;
        }
        if (input == '!') { //uitroepteken geeft einde van telegram aan, dus we gaan data versturen
          // if (millis() - lastConnectionTime > postingInterval) {
          // httpRequest();
          updateThingSpeak("field1=0");
          // httpRequest();
          mEVLT = 0;
          mEVHT = 0;
          mEAV = 0;
          mG = 0;
          client.stop();
          //}
        } //Einde vraagteken detectie
        //Serial.print(c);
      } //Einde 'if AltSerial.available'
    } //Einde 'decodeTelegram()' functie

body:
Please see some comments that can help you.

Why do you use a software serial port?
This ATmega has 4 real serial ports!

`delay()` is dangerous in the main loop runtime. Try to use it only in setup.

Every time you call a task, be sure you will not stay there forever.
Get out of the task, if something seems to be too long time. Use `millis()` stamp time differences to measure time spent.
Print it if necessary on debug compiler option.
Printing on failure case do not spend MCU time if there are no errors.


body:
<!-- language-all: cpp -->

    buffer[bufpos] = input & 127;
    bufpos++;

Never use a buffer without a length protection.
Flag if max buffer is reached, force to never write after last position.

Like this:

    if ( bufpos > MaxBuff )
    {
        Serial.print("errornumber");
        bufpos = MaxBuff;
        //And force \n to finish errored message
    }


message:
What is causing this 'narrowing conversion' warning?

Because I'm still figuring out 'Arduino C' I leave all warnings on.

Recently I got this one:

`narrowing conversion of '(int)(((unsigned char)bx_0) | ((unsigned char)bx_1))' from 'int' to 'const byte...` etc.

...referring to this line:

    const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

...pointing to the `or` symbol.

The code in question (much simplified to recreate this):

    const int latch[2] = {2, 4};

    const byte bx_0 = 1 << latch[0];
    const byte bx_1 = 1 << latch[1];

    const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

(This happens whether I use `byte`, `uint8_t`, or `unsigned char` everywhere.)

Without the `or` operator, no warning. If `bx_0` and `bx_1` are simple bytes, not shifted into existence, no warning. If I do this:

    const byte pinMask[3] = {bx_0, bx_1, (byte)(bx_0 | bx_1)};

...again, no warning.

However, I get no complaints about this:

    const byte notMask = !(bx_1 | bx_0);

...so a further condition is that the problem `or` has to be in an initializer list. Yikes.

I don't get it. There's no way an `or` of two bytes can force widening, so where did the `(int)` cast come from? It apparently has something to do with the `1 << latch[0]` code, but the result of that is still a byte, by definition.

I have a solution -- the `(byte)` cast -- but in the real code it's ugly and feels unnecessary. Everything is already just bytes.

body:
That warning message arises when a compiler complies with [C/C++ specifications](http://www.iso-9899.info/wiki/The_Standard).

According to ISO/IEC 9899:2011 part 6.5.12.2 (“Bitwise inclusive OR operator”),
>Each of the operands shall have integer type

Thus, in the evaluation of `bx_0 | bx_1` within the statement `const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};`, the operands `bx_0` and `bx_1` are converted to `int` type before being OR'd together.  This produces an `int` result, which then must be narrowed to `byte` before it can be stored in the  `byte` array.

Knowing that the `(byte)` cast is necessary because of C/C++ specifications should convert your view of the cast from “ugly” and “unnecessary” to “necessary” and either “ok” or “oh well”.  :)