body:
I have made a home automation system consisting of a NodeMCU, 4 channel relay board running on Blynk and IFTTT.

At the moment I'm only controlling a string of fairy lights and two LED strips from it, both connected to the relay of course.

The only code running on the NodeMCU is the Blynk ESP8266 Standalone code. Here it is (with the necessary changes of course) -
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>

    // You should get Auth Token in the Blynk App.
    // Go to the Project Settings (nut icon).
    char auth[] = "YourAuthToken";

    // Your WiFi credentials.
    // Set password to "" for open networks.
    char ssid[] = "YourNetworkName";
    char pass[] = "YourPassword";

    void setup()
    {
      // Debug console
      Serial.begin(9600);

      Blynk.begin(auth, ssid, pass);
      // You can also specify server:
      //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
      //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
    }

    void loop()
    {
      Blynk.run();
      // You can inject your own code or combine it with other sketches.
      // Check other examples on how to communicate with Blynk. Remember
      // to avoid delay() function!
    }

Now the thing is, the NodeMCU automatically disconnects from the WiFi randomly. Sometimes it reconnects immediately, sometimes it doesn't reconnect at all and I have to keep hitting the reset button to get it working again.

This is really annoying as everything I got connected to the NodeMCU also comes on all of a sudden and scares the hell out of me.

The code is all fine, the power supply is stable (5v 1A), all the cables are in place and the NodeMCU is tucked away in a corner where nobody touches it.
I can't seem to work out why is this happening.

Any fixes for this?

title: NodeMCU keeps disconnecting

Answers: 1

body:
I had this same issue with an ESP8266 NodeMCU-12E using Cayenne in the past. It would drop connection for no apparent reason, but no matter what, most of the time it'd never reconnect until a reset. Here's what I did:

    CAYENNE_DISCONNECTED(){
      Serial.println(F("Cayenne disconnected, rebooting..."));
      ESP.restart();
    }

I've never used `Blynk` before, but after a quick look, this may do the same thing (untested):

    if (! Blynk.connected){
      Serial.println(F("Blynk disconnected, rebooting..."));
      ESP.restart();
    }

It effectively reboots the ESP unit if the connection to Blynk drops for any reason.


body:
I have a strong urge to replace the framework-provided `loop()` function with my own like so:

    __attribute__((always_inline)) inline void fastLoop()
    {
    }

    void setup()
    {
       // Performing setup here...
       Serial.begin(115200);

       // Now looping
       for(;;)
          fastLoop();
    }

This way, my loop is inlined and I'm saving quite a few cycles - avoiding not only Arduino housekeeping costs, but also the function call cost which even for a void function has to be at least 6 cycles on AVR (>=2 for RCALL and 4 for RET).

This is the framework code for calling `loop()` from `main()`:

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

My question is: what does this `serialEvent` stuff do? What features of the framework will stop working properly with my own loop?

Assuming my loop has observable side effects as required by the C++ standard, of course (otherwise it can be optimized out).

title: What features of the Arduino framework will fail if I use my own infinite loop in favor of the standard loop()?

Answers: 1

body:
It depends on which "Arduino" you are running it on.

On an Arduino Uno, for example, then the only thing that won't work is the SerialEvent system. Everything else that matters is interrupts.

Here is `main()` on the Arduino AVR core:

    int main(void)
    {
     init();

     initVariant();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

As you can see, `loop()` is run just the same way as your `fastLoop()`, just not `inline`, and adding in a call to `serialEventRun()` if it has been defined.

If no serial event handlers have been defined, then it won't do anything there anyway.

To save clock cycles you would get more benefit (as long as you don't want to use `millis()`, `delay()`, serial communication, etc) from disabling interrupts.

However, on an ESP32 or ESP8266 you will find that your watchdog times out and resets the unit. This is because it relies on code being run regularly to manage the WiFi connection that keeps "kicking the dog". Without that being run (which can be called by calling the `yield()` function) the watchdog times out.


body:
I am using ATmega8A standalone but analog pins (Port C) have not been use.

Due to ATmega8A does not have a PRR (Power Reduction Register) to disable ADC and TWI.

I would like to know, is it a work around solution to reduce the power consumption if AVcc is not connected?

title: Can I leave AVcc disconnected?

Answers: 2

body:
No. You must connect AVcc even if you're not using the ADC.  According to the datasheet:

> AVCC is the supply voltage pin for the A/D Converter, Port C (3:0), and ADC (7:6). **It should be externally connected to VCC, even if the ADC is not used.** If the ADC is used, it should be connected to VCC through a low-pass filter. Note that Port C (5:4) use digital supply voltage, VCC.

body:
No, the datasheet says power must be connected to Avcc. This is from the '328P, Atmega8A is similar but with less memory:
(Microchip is taking forever to open the Atmega8A datasheet for me).

>5.2.7  AVCC
>AVCC is the supply voltage pin for the A/D Converter (ADC), PC[3:0], and PE[3:2]. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter.

https://www.microchip.com/wwwproducts/en/ATmega8A


body:
I am trying to modularize the different components in my arduino build by using objects, but am having trouble with the one controlling a wireless transceiver, which uses `SoftwareSerial.h`

I believe I am (generally) setting up the use of these objects correctly because I have other objects that build correctly in other files.

I think my issue is somehow part of `SoftwareSerial.h`, but I am not knowledgeable enough to get in and diagnose it... I think my core issue is that `SoftwareSerial` is not being brought in properly.

**Transciever.cpp**

```c++
/*
   This code controls the HC-12 transciever
*/
#include <Arduino.h>
#include <SoftwareSerial.h>

enum class TransReadStatus {
  RELAY_OFF,
  RELAY_ON,
  NO_DATA
};

class TranscieverHandler {
  public:
    TranscieverHandler(
      int txPinIn,
      int rxPinIn,
      int setPinIn,
      int baudRateIn
    ): txPin(txPinIn),
      rxPin(rxPinIn),
      setPin(setPinIn),
      baudRate(baudRateIn)
    {
      SoftwareSerial hc12(txPin, rxPin);
    }

    void init() {
      hc12.begin(baudRate);
      pinMode(setPin, OUTPUT);
      digitalWrite(setPin, HIGH);  // HC-12 normal, transparent mode
    }

    TransReadStatus checkForSignal() {
      while (hc12.available()) {             // If HC-12 has data
        incomingByte = hc12.read();          // Store each icoming byte from HC-12
        readBuffer += char(incomingByte);    // Add each byte to ReadBuffer string variable
      }
      delay(100);

      if (onBytes.equals(readBuffer)) {
        readBuffer = "";
        return TransReadStatus::RELAY_ON;
      } else if (offBytes.equals(readBuffer)) {
        readBuffer = "";
        return TransReadStatus::RELAY_OFF;
      }
      readBuffer = "";
      return TransReadStatus::NO_DATA;
    }

    TransReadStatus getLastRecievedStatus() {
      TransReadStatus newStatus = checkForSignal();

      if (newStatus == TransReadStatus::NO_DATA) {
        return lastStatus;
      }
      lastStatus = newStatus;
      return lastStatus;
    }

  protected:
    const int txPin;// = 10;
    const int rxPin;// = 11;
    const int setPin;// = 12;
    const int baudRate;// 9600
    /*
       Constants for signals
    */
    const String setOnBytes = String("SET RELAY ON");
    const String setOffBytes = String("SET RELAY OFF");
    const String onBytes = String("STATUS: RELAY IS ON");
    const String offBytes = String("STATUS: RELAY IS OFF");

    SoftwareSerial hc12;

    byte incomingByte;
    String readBuffer = "";
    TransReadStatus lastStatus = TransReadStatus::NO_DATA;
    unsigned long lastSendOnSignal = millis();

};
```

**Output from failed compilation:**

```text
Arduino: 1.8.9 (Linux), Board: "Arduino/Genuino Uno"

/home/greg/other/arduino-1.8.9/arduino-builder -dump-prefs -logger=machine -hardware /home/greg/other/arduino-1.8.9/hardware -tools /home/greg/other/arduino-1.8.9/tools-builder -tools /home/greg/other/arduino-1.8.9/hardware/tools/avr -built-in-libraries /home/greg/other/arduino-1.8.9/libraries -libraries /home/greg/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10809 -build-path /tmp/arduino_build_227628 -warnings=default -build-cache /tmp/arduino_cache_459309 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -verbose /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino
/home/greg/other/arduino-1.8.9/arduino-builder -compile -logger=machine -hardware /home/greg/other/arduino-1.8.9/hardware -tools /home/greg/other/arduino-1.8.9/tools-builder -tools /home/greg/other/arduino-1.8.9/hardware/tools/avr -built-in-libraries /home/greg/other/arduino-1.8.9/libraries -libraries /home/greg/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10809 -build-path /tmp/arduino_build_227628 -warnings=default -build-cache /tmp/arduino_cache_459309 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -verbose /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino
Using board 'uno' from platform in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr
Using core 'arduino' from platform in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr
Detecting libraries used...
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /dev/null
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /dev/null
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/Buttons.cpp
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/LEDs.cpp
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/Switches.cpp
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/Transciever.cpp -o /dev/null
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.cpp -o /dev/null
Generating function prototypes...
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /tmp/arduino_build_227628/preproc/ctags_target_for_gcc_minus_e.cpp
/home/greg/other/arduino-1.8.9/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_227628/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
Using previously compiled file: /tmp/arduino_build_227628/sketch/Buttons.cpp.o
Using previously compiled file: /tmp/arduino_build_227628/sketch/Switches.cpp.o
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp.o
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/Transciever.cpp -o /tmp/arduino_build_227628/sketch/Transciever.cpp.o
Using previously compiled file: /tmp/arduino_build_227628/sketch/LEDs.cpp.o
/tmp/arduino_build_227628/sketch/Transciever.cpp: In constructor 'TranscieverHandler::TranscieverHandler(int, int, int, int)':
Transciever.cpp:23:26: error: no matching function for call to 'SoftwareSerial::SoftwareSerial()'
       baudRate(baudRateIn)
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note: candidate: SoftwareSerial::SoftwareSerial(uint8_t, uint8_t, bool)
   SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

   ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note:   candidate expects 3 arguments, 0 provided
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note: candidate: constexpr SoftwareSerial::SoftwareSerial(const SoftwareSerial&)
 class SoftwareSerial : public Stream

       ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note:   candidate expects 1 argument, 0 provided
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'void TranscieverHandler::init()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:29:26: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       hc12.begin(baudRate);
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:94:8: note:   in call to 'void SoftwareSerial::begin(long int)'
   void begin(long speed);

        ^
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'TransReadStatus TranscieverHandler::checkForSignal()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:36:29: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       while (hc12.available()) {             // If HC-12 has data
                             ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:104:15: note:   in call to 'virtual int SoftwareSerial::available()'
   virtual int available();

               ^
/tmp/arduino_build_227628/sketch/Transciever.cpp:37:34: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
         incomingByte = hc12.read();          // Store each icoming byte from HC-12
                                  ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:103:15: note:   in call to 'virtual int SoftwareSerial::read()'
   virtual int read();

               ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In constructor 'TranscieverHandler::TranscieverHandler(int, int, int, int)':
Transciever.cpp:23:26: error: no matching function for call to 'SoftwareSerial::SoftwareSerial()'
       baudRate(baudRateIn)
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note: candidate: SoftwareSerial::SoftwareSerial(uint8_t, uint8_t, bool)
   SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

   ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note:   candidate expects 3 arguments, 0 provided
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note: candidate: constexpr SoftwareSerial::SoftwareSerial(const SoftwareSerial&)
 class SoftwareSerial : public Stream

       ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note:   candidate expects 1 argument, 0 provided
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'void TranscieverHandler::init()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:29:26: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       hc12.begin(baudRate);
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:94:8: note:   in call to 'void SoftwareSerial::begin(long int)'
   void begin(long speed);

        ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'TransReadStatus TranscieverHandler::checkForSignal()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:36:29: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       while (hc12.available()) {             // If HC-12 has data
                             ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:104:15: note:   in call to 'virtual int SoftwareSerial::available()'
   virtual int available();

               ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp:37:34: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
         incomingByte = hc12.read();          // Store each icoming byte from HC-12
                                  ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:103:15: note:   in call to 'virtual int SoftwareSerial::read()'
   virtual int read();

               ^
Using library SoftwareSerial at version 1.0 in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial
exit status 1
no matching function for call to 'SoftwareSerial::SoftwareSerial()'
```

title: Using SoftwareSerial.h in .cpp file

Answers: 1

body:
The member initialization is intended for objects construction. For ints you can do an assignment in the constructors body

    TranscieverHandler(int txPinIn, int rxPinIn, int setPinIn, int baudRateIn)
        : hc12(txPin, rxPin) {
      txPin = txPinIn;
      rxPin = rxPinIn;
      setPin = setPinIn;
      baudRate = baudRateIn;
    }


body:
I bought a Feather M0 basic from Amazon here. I installed all the board definitions and stuff from here I restarted the IDE and when I plugged it in, the Feather doesn't show up in ports or device manager. I am using a data cable that I verified. Debug is off and USB stack is Arduino.

I also tried following the instructions here but it didn't work.

When I double-clicked the reset button, the red LED didn't pulse.

Is there anything that am I missing?

**Edit**: Feather is supplying 3~ volts. USB is supplying 4.5~ volts.

**Edit 2**: Charing LED lights up when li-poly is plugged in.

title: Adafruit Feather M0 Basic Proto doesn't show up

Answers: 0


body:
Code :

```c++
//FOR AEROPONIC SYSTEM WITH ROOM TEMPERATURE AND HUMIDITY SENSOR
//AND 4 GROW CHAMBERS WITH DIFFERENT SPRAYING TIME

// RELAY CONTROL
#define RELAY1_PIN 2
#define RELAY2_PIN 3
#define RELAY3_PIN 4
#define RELAY4_PIN 5

//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 6
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

//Variables
int chk;
float hum;
float temp;

void setup()
{
    Serial.begin(9600);
    Serial.println("SENSOR RUNNING");
    dht.begin();

    pinMode(RELAY1_PIN, OUTPUT);
    pinMode(RELAY2_PIN, OUTPUT);
    pinMode(RELAY3_PIN, OUTPUT);
    pinMode(RELAY4_PIN, OUTPUT);
}

void loop()
{
    delay(2000);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (isnan(h) || isnan(t))
    {
        Serial.println("CONNECTION ERROR");
        return;
    }
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.println(" ");
    delay(2*1000);
    {
        // FOR RELAY
        digitalWrite(RELAY1_PIN, HIGH);
        delay(2*1000); // wait for 2 second ON
        digitalWrite(RELAY2_PIN, HIGH);
        delay(3*1000); // wait for 3 second ON
        digitalWrite(RELAY3_PIN, HIGH);
        delay(4*1000); // wait for 4 second ON
        digitalWrite(RELAY4_PIN, HIGH);
        delay(5*1000); // wait for 5 second ON

        digitalWrite(RELAY1_PIN, LOW);
        digitalWrite(RELAY2_PIN, LOW);
        digitalWrite(RELAY3_PIN, LOW);
        digitalWrite(RELAY4_PIN, LOW);
        delay(5*60*1000);
    }
}
```

This code doesn't do what I want. How do I make them independent?

title: How to code 4 relays to go off in intervals and not in sequence?

Answers: 1

body:
Here is some code that might help you; leaving out the temperature and humidity stuff:

    // constants
    // number or relays
    const int relays = 4;

    // pins for the relays
    const int relayPins[] = {2, 3, 4, 5};

    // relay cycle times
    const unsigned long relayTimes[] = {
         5*60*1000, // 5 min
         60*60*1000, // 1 Hour
         2*60*60*1000, // 2 hours
         12*60*60*1000 // 12 hours
      };

    // relay on durations
    const unsigned long relayOntimes[] = {
        1000, // 1 second
        10*1000, // 10 seconds
        60*1000, // 1 minute
        60*60*1000 // 1 hour
      };

    // timing for the relays
    // storing the last time
    unsigned long relayElapsed[] = {0, 0, 0, 0};

    // state of each relay
    int relaystate[] = {0, 0, 0, 0};

    // helper function to process each relay
    void relay_helper(unsigned long t, unsigned long &elapsed, int pin, int &state, unsigned long delta, unsigned long ontime)
    {
      // depending on the state we do different things
      switch (state)
      {
      case 0: // state 0 is off, wait until time has passed
        if ((t-elapsed) > delta)
        {  // then
           state = 1; // set the state to on
           elapsed = t; // reset the time
           digitalWrite(pin, HIGH); // turn on
        }
        break;
      case 1: // state 1 is on, wait until time has passed
        if ((t-elapsed) > ontime)
        {  // then
           state = 0; // set the state to off
           elapsed = t; // reset the time
           digitalWrite(pin, LOW); // turn off
        }
        break;
      }
    }

    void setup()
    {
      unsigned long start = millis();
      for(int i = 0; i < relays; i++) // for each pin
      {
        pinMode(relayPins[i], OUTPUT); // set it to output
        digitalWrite(relayPins[i], LOW); // and turn it off
        relayElapsed[i] = start;
      }
    }

    void loop()
    {
      unsigned long tm = millis();
      for(int i = 0; i < relays; i++)
      {
        relay_helper(tm, relayElapsed[i], relayPins[i], relaystate[i], relayTimes[i], relayOnTimes[i]);
      }
      // do other loop stuff
    }

The basic idea is that the only way to do thing simultaneously is to do things in sequence really fast, we can't use delay() because it is a busy loop, nothing else can happen during delay(), so we keep track of the time and when it is time to turn on the relay we turn it on, and when it is time to turn it off we turn if off.

Another option would be to write a class per relay:

    class Relay
    {
    public:
      Relay(int pin, unsigned long delta, unsigned long ontime);
      ~Relay();

      process(unsigned long t);

    private:
      unsigned long delta;
      unsigned long ontime;
      unsigned long last; // elapsed
      int pin;
    };

Then one can create an array of these:

    Relay[] relays = {
        Relay(2, 5*60000, 1000),
        Relay(3, 60*60000, 10000),
        Relay(4, 2*60*60000, 60000),
        Relay(5, 12*60*60000, 60*60000)
      };

put the code from setup into the constuctor, and the code from the helper into process, and finally call it in a loop in loop.

The first way shown is how one would do it without C++ classes, and the second way is with them!


body:
So I have a standard 16x2 LCD display with 16 pins. The LCD display works fine with every other aspect, however, the "lcd.clear" function doesn't work with "Serial.begin(ANY BAUD)". I have tried changing bauds and downgrading the board software but it still doesn't work.

Basically, instead of clearing the display like it should do, it displays a weird character with 4 horizontal lines (in one character space) and then continues to write stuff after it.

Here is my code:
<!-- language-all: lang-cpp -->

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

    void setup() {
     pinMode(8, INPUT);
     lcd.begin(16,2);
     Serial.begin(9600);
    }

    void loop() {
     lcd.print("incorrect");
     delay(3000);
     lcd.clear();
     delay(100);
    }

Whenever I delete the Serial.begin everything works fine, but when I add it the clear function doesn't work anymore.

So in this case, what happens is that the Arduino prints "incorrect", then instead of clearing the display, it prints out four horizontal lines, and then continues to print out "incorrect" infinitely.

title: lcd.clear doesn't work with Serial.begin(9600) on Arduino Mega 2560

Answers: 2

body: Pins 0 and 1 are the hardware serial pins on the Mega.  If you're going to use Serial, then you can't connect your LCD to those pins or it won't work.  Even if you are only connected to Serial through the USB, pins 0 and 1 are still acting as Tx and Rx.

body:
Buddy you are using those pins which are used for communication purpose that is pin No. 0 and 1 is for RXD and TXD  [![See the image you will observe what you are trying to do is wrong][1]][1]

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


body:
Whenever I try to compile a script, the Arduino IDE throws the error ```avr-g++: error: CreateProcess: No such file or directory```. I've already tried reinstalling the IDE, changing the board version in the board manager to 1.6.21, and deleting the Arduino15 folder under ```AppData/Local/Arduino15```.
This problem appeared suddenly - one compilation worked, and two minutes later, nothing would compile - and occurs across all scripts that I've tried.

I'm working from Windows 10 and compiling for an Arduino Uno.

title: Error "avr-g++: error: CreateProcess: No such file or directory" When Compiling Script

Answers: 1

body: Turns out that McAfee's Host Intrusion Prevention had decided to start blocking ```avr-g++.exe```. Not sure why it did so all of a sudden, but it's an easy fix once you know where to look. Anyone finding this in the future should be sure to check their antivirus logs to see if the compiler's executable is being blocked.


body:
With regards to the Adafruit LSM9DS1 breakout:
[enter link description here][1]

And using the Library:
[enter link description here][2]

I am trying to increase the sample rate, or speed of this chip.
I am using a Sparkfun Pro Micro 5V

With the adafruit library, you need to request accelerometer, gyro, magnetometer and temperature at once, and all I need is the accelerometer values. I am hoping by figuring out how to request only the accel values it will speed up the loop. But also, there must be another setting that could speed up the sample rate?

Any help would be appreciated!

my code currently:
<!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_LSM9DS1.h>
    #include <Adafruit_Sensor.h>  // not used in this demo but required!
    Adafruit_LSM9DS1 lsm = Adafruit_LSM9DS1();
    #define LSM9DS1_SCK A5
    #define LSM9DS1_MISO 12
    #define LSM9DS1_MOSI A4
    #define LSM9DS1_XGCS 6
    #define LSM9DS1_MCS 5

    void setupSensor()
    {
      // 1.) Set the accelerometer range
      lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_2G);
      //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_4G);
      //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_8G);
      //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_16G);

      // 2.) Set the magnetometer sensitivity
      lsm.setupMag(lsm.LSM9DS1_MAGGAIN_4GAUSS);
      //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_8GAUSS);
      //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_12GAUSS);
      //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_16GAUSS);

      // 3.) Setup the gyroscope
      lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_245DPS);
      //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_500DPS);
      //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_2000DPS);
    }

    double accelX = 0;
    double accelY = 0;
    double accelZ = 0;
    double rms = 0;

    void setup()
    {
      Serial.begin(115200);
      // Try to initialize and warn if we couldn't detect the chip
      if (!lsm.begin())
      {
        Serial.println("Oops ... unable to initialize the LSM9DS1. Check your
    wiring!");
        while (1);
      }
      Serial.println("Found LSM9DS1 9DOF");
      setupSensor();
      delay(5000);//program stabilization
    }

    void loop()
    {
      lsm.read();
      sensors_event_t a, m, g, temp;
      lsm.getEvent(&a, &m, &g, &temp);
      accelX = a.acceleration.x;
      accelY = a.acceleration.y;
      accelZ = a.acceleration.z;
      rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
      Serial.println(rms);
    }

  [1]: https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/overview
  [2]: https://github.com/adafruit/Adafruit_LSM9DS1

title: LSM9DS1 breakout - How to increase speed

Answers: 2

body:
Check the [header][1] of the library,

you will find `readAccel` `readMag` `readGyro` and `readTemp` in separate public functions and looking at the [implementation][2] of `read` it just calls those 4 in sequence. `readAccel` will update the `accelData` member field.

So you can just call `lsm.readAccel()` in the loop and then grab `lsm.accelData` directly and ignore the rest.

  [1]: https://github.com/adafruit/Adafruit_LSM9DS1/blob/master/Adafruit_LSM9DS1.h
  [2]: https://github.com/adafruit/Adafruit_LSM9DS1/blob/master/Adafruit_LSM9DS1.cpp#L158

    void loop()
    {
      lsm.readAccel();
      accelX = lsm.accelData.x;
      accelY = lsm.accelData.y;
      accelZ = lsm.accelData.z;
      rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
      Serial.println(rms);
    }

body:
Here is a link to the [LSM9DS1 datasheet][1]. In Chapter 3 it describes how to put the device in Accelerometer-only mode. At a quick scan of it, I believe there was timing information also, but at least knowing how to do it, you could then make your own timing measurements.

  [1]: https://www.st.com/resource/en/datasheet/lsm9ds1.pdf


body: So far I have seen in LED matrix related projects that the brightness is controlled in an entirety manner. That means the   brightness of total display can either be reduced or increased. How can we display only a part of the display with more brighter than the remaining matrix? Appreciate if anyone provide some pseudo logic to achieve this.

title: LED Matrix Display with dissimilar brightness

Answers: 4

body:
Short answer: You likely can't, at a hardware level.

The only way you'd be able to do this is to vary the duty cycle of each individual LED in the matrix (the percent of on-time vs. off-time).

The device would have to support that. Edit your question with the model number of the LED matrix you're using and it's spec sheet.

(Note that if you're using a simple grid of LEDs and row/column addressing you could use PWM to get some control over brightness, but you'd probably already be using multiplexing of the LEDs, which makes varying brightness per LED more complex.)

body:
There's two options:

1. Use a matrix driver that supports different brightnesses per pixel, or:
2. Rapidly display a different arrangement of pixels in quick succession. The pixels that are on more often are brighter.

Option 1 basically does option 2 in hardware.

The theory is simple:  For one LED you can vary the brightness by using PWM - that switches the LED on and off very rapidly. The longer it is on the brighter it appears.

You can do the same with a matrix of pixels. Instead of dealing with one pixel though you are dealing with, in effect, a series of "images". Each "image" has a different combination of pixels. The more "images" you have the greater variation you can get in your pixel brightnesses.

For example if you first display a frame of:

    . . . . . . . .
    . . # # # # . .
    . # . . . . # .
    . # . . . . # .
    . # . . . . # .
    . # . . . . # .
    . . # # # # . .
    . . . . . . . .

followed by the image:

    . . . . . . . #
    . . # # # # # .
    . # . . . # # .
    . # . . # . # .
    . # . # . . # .
    . # # . . . # .
    . # # # # # . .
    # . . . . . . .

then you will get a bright circle(ish) shape with a dimmer slash through it.

The only problem with this method is flicker. You have to have your matrix refreshing very fast. The more "images" you have to display in sequence the more it will flicker and the faster you will have to refresh your matrix to compensate.

body:
LED brightness is normally controlled by how long a given LED is lit.  An LED that is on for 70ms and off for 30ms will be brighter then an LED that is on for only 30ms and off for 70ms.

So, the answer is to shorten the amount of time which the LED is on and lethen the time the LED is off for only those LEDs in your display which are to be dimmer.

This is usually referred to as the [duty cycle][1] of the LED.  On an Arduino, the [PWM or Pulse Width Modulator][2] feature of the embedded processor is normally used to create the duty cycle signal for an LED.

  [1]: https://en.wikipedia.org/wiki/Duty_cycle
  [2]: https://www.arduino.cc/en/tutorial/PWM

body:
Depends on what LEDs your matrix is made of. One option would be to make it from 'smart' LEDs at each location, such as WS2812B. These are a chip and 3 LEDs in one package, usually a 5050 size SMD package, but they can also be had in thru hole packages, and can be found built up into boards also (look at Sparkfun and Adfruit for examples). Serial data is sent in, with a 0-255 value for each LED, the control chip then drives the 3 LEDs with the PWM level commanded - 0/255 for off, 128/255 for 1/2 on for example, 255/255 for full on.  The data is passed from device to device to load them up, so for example an 8x8 matrix would need 8x8x3 = 192 bytes of data sent in to load the display. The Arduino then doesn't need to do any more until the matrix needs to change.  WS2812B needs some fancy timing to send in 0/1 data in a combined data/clock signal line, options are the Neopixel library or the FastLed.h library for Arduino, to send data in at up to 800 KHz rate. There is also another version of the chip that uses seperate clock and data lines, SPI.transfer I think can be used to send in data even faster.  I don't recall that device's part number off hand, I've not used it.

For premade 8x8 modules using single color LEDs, then as described in other answers  MAX7219 is often used, with 15 levels of brightness available for the whole display.


body:
I am totally new to Arduino. I have a Arduino Mega 2560 and I would like to perform long-term observations of PM, Ozone and NO2 (for around a year, outdoors).

Do you have any ideas which sensors might be suitable for this? I have a few sensors in mind (SDS011, Plantower PMS 1003, Sharp GP2Y1010AU0F, Honeywell HPMA115S0...) but since this is my first time doing this kind of stuff, I dont have any experience.

title: Suitable long-term sensors for PM, Ozone and NO2

Answers: 0


body:
this is the code i am working on for controlling leds

    #include <WiFi.h>                                                // esp32 library
    #include <IOXhop_FirebaseESP32.h>                                             // firebase library
    #define FIREBASE_HOST "mmmmm"                         // the project name address from firebase id
    #define FIREBASE_AUTH "mmmmmmm"                    // the secret key generated from firebase
    #define WIFI_SSID "mmmmm"                                          // input your home or public wifi name
    #define WIFI_PASSWORD "mmmmmm"                                    //password of wifi ssid

    String fireStatus ;
    String fireStatus1 ;
    String fireStatus3 ;
    String fireStatus4 ; // led status received from firebase
    int relay1 = 15;
    int relay2 = 2;
    int relay3 = 4;
    int relay4 = 5;

    void setup() {

    Serial.begin(115200);

    pinMode(15, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);                                      //try to connect with wifi
    Serial.print("Connecting to ");
    Serial.print(WIFI_SSID);
      while (WiFi.status() != WL_CONNECTED) {
          Serial.print(".");
        delay(300);
      }
      Serial.println();
      Serial.print("Connected to ");
      Serial.println(WIFI_SSID);
      Serial.print("IP Address is : ");
      Serial.println(WiFi.localIP());                                                      //print local IP address
      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                                       // connect to firebase

    }
    void loop() {

      {
        fireStatus =  Firebase.getString("S1");

        Serial.println("Switch1 Turned ON/OFF");
        digitalWrite(15,fireStatus );
        fireStatus1 =  Firebase.getString("S2");
         Serial.println("Switch2 Turned ON/OFF");
        digitalWrite(2,fireStatus1 );

         fireStatus3 =  Firebase.getString("S3");
         Serial.println("Switch3 Turned ON/OFF");
        digitalWrite(4,fireStatus3));

         fireStatus4 =  Firebase.getString("S4");

         Serial.println("Switch4 Turned ON/OFF");
        digitalWrite(5,fireStatus4 );

    }
    }

title: error cannot convert string TO uint_8t

Answers: 0


body:
I'm stuck, I figured I'd ask here for some help... Note I'm a newb and this is essentially my first Arduino project beyond blink...

I'm creating Virtual cockpit panels for DCS World, using an Arduino Leonardo as an HID device. I'm using three SN74HC165 Shift-In registers for multi-buttons (24) - as it seemed the easiest - and all in all it does work...

So I figured that I'm using only 4 pins on the Leonardo, so why not try to setup 3 of these "shift-in clusters" (12 pins) to appear as 3 separate joysticks?

I got the one working and I got 2 more joysticks showing up in Windows10... now my problem is: how would I setup 2 more "shiftIn Clusters", I've tried many things but I must defer to outside help (cause I really don't know what I'm doing)

Edit to clarify: So each joystick need 3 or 4 shift registers making 24-32 buttons on each joystick

Shift In Lib: https://github.com/…/Ardu…/blob/master/ShiftIn/src/ShiftIn.h

Joy2 Lib: https://github.com/MHeironimus/ArduinoJoystickLibrary

Here's an image of the Layout I want: https://i.stack.imgur.com/sEtRp.png

... any help would relieve a great headache, Thank for your time

    #include <ShiftIn.h>
    #include <Joystick.h>

    // use <n> shift registers
    ShiftIn<3> shift;             // use three shift register

    // Create joystick
    // TESTING MULTI JOYSTICKS
    // 1/3 Works!!!
    // 3/3 Appear in Windows
    // ????? must add shiftIn sections for 2nd and 3rd joysticks????
    // (add pin usage + modify line 77-79 stuff)

    #define JOYSTICK_COUNT 3
    Joystick_ Joystick[JOYSTICK_COUNT] = {
      Joystick_(0x03, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
      Joystick_(0x04, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
      Joystick_(0x05, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
    };

    // Set to true to test "Auto Send" mode or false to test "Manual Send" mode.
    //const bool testAutoSendMode = true;
    const bool testAutoSendMode = false;

    const unsigned long gcCycleDelta = 1000;
    const unsigned long gcAnalogDelta = 25;
    const unsigned long gcButtonDelta = 500;
    unsigned long gNextTime = 0;
    unsigned int gCurrentStep = 0;
    int gJoystickId = 0;

    /*
    // WORKING SECTION Single Joystick with Shift Reg
    Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID, JOYSTICK_TYPE_GAMEPAD,
      32, 0,                        // Button Count, Hat Switch Count
      false, false, false,          // X and Y, but no Z Axis
      false, false, false,          // No Rx, Ry, or Rz
      false, false,                 // No rudder or throttle
      false, false, false);         // No accelerator, brake, or steering
    */

    void setup() {

      shift.begin(8, 9, 11, 12);  // set pins of the shift register
    //  shift[1].begin(7, 6, 5, 4);  // set pins of the shift register
    //  shift[2].begin(3, 2, 1, 0);  // set pins of the shift register

     Joystick[0].begin();
     Joystick[1].begin();
     Joystick[2].begin();
    }

    void loop() {

      if (shift.update()) {
        for (int i = 0; i < shift.getDataWidth(); i++)
        Joystick[0].setButton(i, shift.state(i));            // just press or release the button
      }
    /*if (shift[1].update()) {
        for (int i = 0; i < shift[1].getDataWidth(); i++)
        Joystick[0].setButton(i, shift[1].state(i));            // just press or release the button
      }
    if (shift[2].update()) {
        for (int i = 0; i < shift[2].getDataWidth(); i++)
        Joystick[0].setButton(i, shift[2].state(i));            // just press or release the button
      }
      delay(10);
    */
    }

title: Stuck making multi, many button, joysticks

Answers: 1

body:
Each `ShiftIn` instance handles just one connection. You need to make multiple instances.

    ShiftIn shift1<3>;
    ShiftIn shift2<3>;
    ShiftIn shift3<3>;

Then you `begin` each of them:

    void setup() {
        shift1.begin(8, 9, 11, 12);
        shift2.begin(7, 6, 5, 4);
        shift3.begin(3, 2, 1, 0);
        ... etc ...
    }

Each `shiftx` is a completely separate entity. You can just repeat your block of code for each `shift` object:

    if (shift1.update()) {
        for (int i = 0; i < shift1.getDataWidth(); i++)
        Joystick[0].setButton(i, shift1.state(i));
    }

    if (shift2.update()) {
        for (int i = 0; i < shift2.getDataWidth(); i++)
        Joystick[1].setButton(i, shift2.state(i));
    }

    if (shift3.update()) {
        for (int i = 0; i < shift3.getDataWidth(); i++)
        Joystick[2].setButton(i, shift3.state(i));
    }

You could arrange the `ShiftIn` objects into an array like you do with your `Joystick` objects and then loop through them, but that is pretty pointless for just three of them.


body:
I've installed an [I2C module][1] on my [16x2 LCD][2] so i don't have access to all those LCD pins to control the backlight LED.

**BUT** there is a 100 ohm smd resistor in series with anode of the backlight LED, i want to remove the resistor and use Arduino PWM to control the backlight or i can just replace that resistor with a 330 ohm or a 1K resistor.

[![][3]][3]

*Red box showing the resistor and blue box showing the Jumper.*

Also I2C module itself have a jumper for LED backlight which also goes to that resistor...

Just wanted to ask here and make sure it is going to work before doing any modification to the LCD.

which way is better? is it going to work?
___
**UPDATE:** *i used Arduino PWM and a 2n2222 transistor and was able to successfully control the backlight brightness via jumper pins of I2C module.*

  [1]: http://www.mantech.co.za/datasheets/products/lcd2004-i2c.pdf
  [2]: https://components101.com/16x2-lcd-pinout-datasheet
  [3]: https://i.stack.imgur.com/0qfa7.jpg

title: Controlling 16x2 LCD backlight (I2C module)

Answers: 1

body:
It's hard to tell from the limited information, but chances are the "backlight jumper" mentioned in passing in the datasheet can be simply removed.  This will then give you two pins.  One will connect to pin 3 of the IO expander, and the other will connect to the back light anode itself.

Which is which you will have to discover for yourself.  One of them will have the 100Ω resistor in line with it as well.

If you can't see the tracks (some black boards are hard to make them out) then you should get a digital multimeter and set it to continuity mode and probe the pins to see where they lead.

Once you have identified which pin is which you can connect the one that goes to the back light to your Arduino and drive it with PWM.


body:
Can somebody help me , when i run this code separately , no problem was found , but when i fuse it together , only fuzzy work and the data can't be sent to my server, sorry for my bad english

i already tried to separate them with function and give delay to make time for posting data , but maybe that not the real problem

    #include "SoftwareSerial.h"
    #include <dht.h>
    #include <Fuzzy.h>
    #define DEBUG true
    #define dht_apin A1 // Analog Pin sensor is connected to
    SoftwareSerial esp(6, 7);// RX, TX
    String ssid = "BU SIS";
    String password = "Bismillah";
    dht DHT;
    // Fuzzy
    Fuzzy *fuzzy = new Fuzzy();
    // FuzzyInputKudara
    FuzzySet *urendah = new FuzzySet(0, 50, 50, 50);
    FuzzySet *usedang = new FuzzySet(45, 60, 60, 75);
    FuzzySet *utinggi = new FuzzySet(70, 70, 100, 100);
    // FuzzyInputKtanah
    FuzzySet *trendah = new FuzzySet(0, 50, 50, 50);
    FuzzySet *tsedang = new FuzzySet(45, 60, 60, 75);
    FuzzySet *ttinggi = new FuzzySet(70, 70, 100, 100);
    // FuzzyInputSudara
    FuzzySet *srendah = new FuzzySet(20, 27, 27, 31);
    FuzzySet *stinggi = new FuzzySet(30, 35, 40, 40);
    // FuzzyOutputKondisi
    FuzzySet *tidak = new FuzzySet(0, 25, 25, 50);
    FuzzySet *siram = new FuzzySet(50, 80, 100, 100);
    String data;
    String server = "192.168.100.11";
    String uri = "/web/insertx.php";
    String temp , hum;
    int ftemp, fhum;
    int tanah;
    void setup() {
      Serial.begin(9600);
      esp.begin(9600);
      // Reset modul
      sendCommand("AT+RST\r\n", 1000, DEBUG);
      // Konfigurasikan sebagai Akses poin & Wifi
      sendCommand("AT+CWMODE=3\r\n", 1000, DEBUG);
      // Sesuaikan dengan SSID dan Password
      sendCommand("AT+CWJAP=\"BU SIS\",\"Bismillah\"\r\n", 10000, DEBUG);
      // Mendapatkan IP adress
      sendCommand("AT+CIFSR\r\n", 1000, DEBUG);
      // Konfigurasikan untuk multiple connection
      sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG);
        //   FuzzyInput
        FuzzyInput *kudara = new FuzzyInput(1);
        kudara->addFuzzySet(urendah);
        kudara->addFuzzySet(usedang);
        kudara->addFuzzySet(utinggi);
        fuzzy->addFuzzyInput(kudara);
        // FuzzyInput
        FuzzyInput *ktanah = new FuzzyInput(2);
        ktanah->addFuzzySet(trendah);
        ktanah->addFuzzySet(tsedang);
        ktanah->addFuzzySet(ttinggi);
        fuzzy->addFuzzyInput(ktanah);
        // FuzzyInput
        FuzzyInput *sudara = new FuzzyInput(3);
        sudara->addFuzzySet(srendah);
        sudara->addFuzzySet(stinggi);
        fuzzy->addFuzzyInput(sudara);
        // FuzzyOutput
        FuzzyOutput *kondisi = new FuzzyOutput(1);
        kondisi->addFuzzySet(tidak);
        kondisi->addFuzzySet(siram);
        fuzzy->addFuzzyOutput(kondisi);
        // Building FuzzyRule 3
        FuzzyRuleAntecedent *a3 = new FuzzyRuleAntecedent();
        a3->joinWithAND(urendah, tsedang);
        FuzzyRuleAntecedent *ktanah3 = new FuzzyRuleAntecedent();
        ktanah3->joinSingle(srendah);
        FuzzyRuleAntecedent *aa3 = new FuzzyRuleAntecedent();
        aa3->joinWithAND(a3, ktanah3);
        FuzzyRuleConsequent *maka3 = new FuzzyRuleConsequent();
        maka3->addOutput(siram);
        FuzzyRule *fuzzyRule3 = new FuzzyRule(3, aa3, maka3);
        fuzzy->addFuzzyRule(fuzzyRule3);
        // Building FuzzyRule 5
        FuzzyRuleAntecedent *a5 = new FuzzyRuleAntecedent();
        a5->joinWithAND(urendah, ttinggi);
        FuzzyRuleAntecedent *ktanah5 = new FuzzyRuleAntecedent();
        ktanah5->joinSingle(srendah);
        FuzzyRuleAntecedent *aa5 = new FuzzyRuleAntecedent();
        aa5->joinWithAND(a5, ktanah5);
        FuzzyRuleConsequent *maka5 = new FuzzyRuleConsequent();
        maka5->addOutput(siram);
        FuzzyRule *fuzzyRule5 = new FuzzyRule(5, aa5, maka5);
        fuzzy->addFuzzyRule(fuzzyRule5);
        // Building FuzzyRule 9
        FuzzyRuleAntecedent *a9 = new FuzzyRuleAntecedent();
        a9->joinWithAND(usedang, tsedang);
        FuzzyRuleAntecedent *ktanah9 = new FuzzyRuleAntecedent();
        ktanah9->joinSingle(srendah);
        FuzzyRuleAntecedent *aa9 = new FuzzyRuleAntecedent();
        aa9->joinWithAND(a9, ktanah9);
        FuzzyRuleConsequent *maka9 = new FuzzyRuleConsequent();
        maka9->addOutput(siram);
        FuzzyRule *fuzzyRule9 = new FuzzyRule(9, aa9, maka9);
        fuzzy->addFuzzyRule(fuzzyRule9);
        //   Building FuzzyRule 11
        FuzzyRuleAntecedent *a11 = new FuzzyRuleAntecedent();
        a11->joinWithAND(usedang, ttinggi);
        FuzzyRuleAntecedent *ktanaha11 = new FuzzyRuleAntecedent();
        ktanaha11->joinSingle(srendah);
        FuzzyRuleAntecedent *aa11 = new FuzzyRuleAntecedent();
        aa11->joinWithAND(a11, ktanaha11);
        FuzzyRuleConsequent *maka11 = new FuzzyRuleConsequent();
        maka11->addOutput(siram);
        FuzzyRule *fuzzyRule11 = new FuzzyRule(11, aa11, maka11);
        fuzzy->addFuzzyRule(fuzzyRule11);
        // Building FuzzyRule 12
        FuzzyRuleAntecedent *a12 = new FuzzyRuleAntecedent();
        a12->joinWithAND(usedang, stinggi);
        FuzzyRuleAntecedent *ktanaha2 = new FuzzyRuleAntecedent();
        ktanaha2->joinSingle(ttinggi);
        FuzzyRuleAntecedent *aa12 = new FuzzyRuleAntecedent();
        aa12->joinWithAND(a12, ktanaha2);
        FuzzyRuleConsequent *makaa2 = new FuzzyRuleConsequent();
        makaa2->addOutput(siram);
        FuzzyRule *fuzzyRule12 = new FuzzyRule(12, aa12, makaa2);
        fuzzy->addFuzzyRule(fuzzyRule12);
        // Building FuzzyRule 15
        FuzzyRuleAntecedent *a15 = new FuzzyRuleAntecedent();
        a15->joinWithAND(utinggi, srendah);
        FuzzyRuleAntecedent *ktanaha5 = new FuzzyRuleAntecedent();
        ktanaha5->joinSingle(tsedang);
        FuzzyRuleAntecedent *aa15 = new FuzzyRuleAntecedent();
        aa15->joinWithAND(a15, ktanaha5);
        FuzzyRuleConsequent *makaa5 = new FuzzyRuleConsequent();
        makaa5->addOutput(siram);
        FuzzyRule *fuzzyRule15 = new FuzzyRule(15, aa15, makaa5);
        fuzzy->addFuzzyRule(fuzzyRule15);
        // Building FuzzyRule 17
        FuzzyRuleAntecedent *a17 = new FuzzyRuleAntecedent();
        a17->joinWithAND(utinggi, ttinggi);
        FuzzyRuleAntecedent *ktanaha7 = new FuzzyRuleAntecedent();
        ktanaha7->joinSingle(srendah);
        FuzzyRuleAntecedent *aa17 = new FuzzyRuleAntecedent();
        aa17->joinWithAND(a17, ktanaha7);
        FuzzyRuleConsequent *makaa7 = new FuzzyRuleConsequent();
        makaa7->addOutput(siram);
        FuzzyRule *fuzzyRule17 = new FuzzyRule(17, aa17, makaa7);
        fuzzy->addFuzzyRule(fuzzyRule17);
      delay(10000);
    }
    void dataku() {
      DHT.read11(dht_apin);
      fhum = DHT.humidity;
      ftemp = DHT.temperature;
      tanah = analogRead(A0);
      tanah = map(tanah, 1023, 36, 100, 0);
      hum = String(fhum);
      temp = String(ftemp);
      fuzzy->setInput(1, fhum);
      fuzzy->setInput(2, tanah);
      fuzzy->setInput(3, ftemp);
      fuzzy->fuzzify();
      Serial.println(fhum);
      Serial.println(ftemp);
      Serial.println(tanah);
      Serial.print("\n\nKondisi: ");
      if (siram->getPertinence() > tidak->getPertinence()) {
        Serial.println("Siram\n");
        pinMode(10, OUTPUT);
        digitalWrite(10, LOW);
      } else {
        Serial.println("Tidak Siram\n");
        pinMode(10, OUTPUT);
        digitalWrite(10, HIGH);
      };
      float output1 = fuzzy->defuzzify(1);
      data = "suhu=" + temp + " & udara=" + hum + " & tanah=" + tanah;// data sent must be under this form //name1=value1&name2=value2.
    //    data = "suhu=10 & udara=20 & tanah=30";
      Serial.println(data);
    }
    void loop() {
      esp.println("AT+CIPSTART=0,\"TCP\",\"" + server + "\",80");//start a TCP connection.
      if ( esp.find("OK")) {
        Serial.println("Koneksi siap");
      };
      Serial.println("=>======================================");
      dataku();
      httppost();
      delay(5000);
    }
    void httppost () {
      String postRequest =
        "POST " + uri + " HTTP/1.1\r\n" +
        "Host: " + server + "\r\n" +
        "Connection: close\r\n" +
        "Content-Type: application/x-www-form-urlencoded\r\n" +
        //    "Content-Type: application/json;charset=UTF-8\r\n"+
        "Content-Length: " + data.length() + "\r\n" +
        "\r\n" + data;
      String sendCmd = "AT+CIPSEND=0";//determine the number of caracters to be sent.
      //Serial.println(postRequest);
      esp.print(sendCmd);
      esp.print(",");
      esp.println(postRequest.length());
      delay(200);
      if (esp.find(">")) {
        Serial.println("Sending.."); esp.print(postRequest);
        if ( esp.find("SEND OK")) {
          Serial.println("Packet sent");
          while (esp.available()) {
            String tmpResp = esp.readString();
            Serial.println(tmpResp);
          }
          // close the connection
          delay(3000);
          esp.println("AT+CIPCLOSE");
          Serial.println("PUTUS");
        }
        //    Serial.println(postRequest);
      }
      delay(4000);
      //  Serial.println(sendCmd + postRequest.length() );
    }

    String sendCommand(String command, const int timeout, boolean debug) {
      String response = "";
      esp.print(command);
      long int time = millis();
      while ( (time + timeout) > millis())  {
        while (esp.available())    {
          char c = esp.read();
          response += c;
        }
      }
      if (debug) {
        Serial.print(response);
      }
      return response;
    }

Sketch uses 17524 bytes (54%) of program storage space. Maximum is 32256 bytes. Global variables use 832 bytes (40%) of dynamic memory, leaving 1216 bytes for local variables. Maximum is 2048 bytes.

title: Post Data Server from Arduino using Fuzzy Logic

Answers: 0


body:
Hello Arduino Community

I am collecting data and attempting to log it on to a Deek Robot SD shield via a Mega.

I have the data  in a dataString which I can Serial.print to the monitor but would like to log it to an SD card instead. When I run the the Datalogger example sketch from the SD library I can see the data and access the datalog file from the SD card (as per point of the example) but when I try to cross-pollinate the example with mySketch the debugging message

> error opening datalog.txt

is all I get.

I've uploaded the sketch, apologies it is pretty long, there's some adc stuff going on, the call for the data file open and write etc starts on line 200 and ends on 212.

I've tried positioning the datafile functions in different places in the code, using other libraries, reading forum posts but I am getting nowhere. if anyone could point out what I'm doing wrong I would be eternally grateful.

Cheers,
Michael
<!-- language-all: lang-cpp -->
```
//!!!change this to name of sketch!!!!
#define SKETCH_VERSION "SD for loop array test"

//include relevant libraries
#include <EnableInterrupt.h>
#include <SPI.h>
#include <SD.h>

//globally define pins
#define BUSY 3    //purple*
#define RD 4      //yellow* RD+CS tied together
#define RESET 5   //grey*
#define CONVST 6  //green* CONVSTA+CONVSTB soldered together on the board
#define RANGE 7   //blue*   *not permanent - double check!!!*

#define DB0 38
#define DB1 39
#define DB2 40
#define DB3 41
#define DB4 42
#define DB5 43
#define DB6 44
#define DB7 45
#define DB8 46
#define DB9 47
#define DB10 48
#define DB11 49
#define DB12 50
#define DB13 51
#define DB14 52
#define DB15 53

byte statusLed       = 13;
byte sensorPin1       = 10;
byte sensorPin2       = 11;
byte sensorPin3       = 12;

int sensorValue[8];
int rawData[16];

//change the size  of these arrays to match the amount of channels being read by the ADC
int adcChannel[5];
int adcData[5];
int channelCount=5;

volatile byte pulseCount1;
volatile byte pulseCount2;
volatile byte pulseCount3;

int pulses[3];

// cs pin for sd-shield *NB 53 for Mega
const int chipSelect = 53;

unsigned long oldTime;

void setup() {             //set up the hardware

  Serial.begin(9600);
  //sd card.....
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");

  enableInterrupt(BUSY, bitBang, FALLING);

  oldTime            = 0;

  pinMode(DB0, INPUT_PULLUP);
  pinMode(DB1, INPUT_PULLUP);
  pinMode(DB2, INPUT_PULLUP);
  pinMode(DB3, INPUT_PULLUP);
  pinMode(DB4, INPUT_PULLUP);
  pinMode(DB5, INPUT_PULLUP);
  pinMode(DB6, INPUT_PULLUP);
  pinMode(DB7, INPUT_PULLUP);
  pinMode(DB8, INPUT_PULLUP);
  pinMode(DB9, INPUT_PULLUP);
  pinMode(DB10, INPUT_PULLUP);
  pinMode(DB11, INPUT_PULLUP);
  pinMode(DB12, INPUT_PULLUP);
  pinMode(DB13, INPUT_PULLUP);
  pinMode(DB14, INPUT_PULLUP);
  pinMode(DB15, INPUT_PULLUP);

  pinMode(RESET, OUTPUT);
  pinMode(CONVST, OUTPUT);
  pinMode(RD, OUTPUT);
  pinMode(RANGE, OUTPUT);
  pinMode(BUSY, INPUT);

  //reset ADC to begin conversion
  digitalWrite(RESET, HIGH);
  delayMicroseconds(10);
  digitalWrite(RESET, LOW);

  digitalWrite(CONVST, LOW);
  digitalWrite(RD, HIGH);
  digitalWrite(RANGE, LOW);
  digitalWrite(BUSY, LOW);

  delayMicroseconds(100);

  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin1, INPUT);
  digitalWrite(sensorPin1, HIGH);

  pinMode(sensorPin2, INPUT_PULLUP);
  digitalWrite(sensorPin2, HIGH);

  pinMode(sensorPin3, INPUT_PULLUP);
  digitalWrite(sensorPin3, HIGH);

  pulseCount1        = 0;
  pulseCount2        = 0;
  pulseCount3        = 0;

  oldTime            = 0;

  // the hall effect sensors are configured to trigger on a FALLING state change
  // (transition from HIGH state to LOW state)
  enableInterrupt(sensorPin1, pulseCounter1, FALLING);
  enableInterrupt(sensorPin2, pulseCounter2, FALLING);
  enableInterrupt(sensorPin3, pulseCounter3, FALLING);

  //this prints the name of the sketch !!!read line 1!!!
  Serial.print("sketch version: ");
  Serial.println(SKETCH_VERSION);

}

void loop() {
  //Serial.print("hello");
  //change this value to preferred sampling rate
  if ((millis() - oldTime) == 1000) {

    oldTime = millis();

    //Serial.print(millis());
    //Serial.print("\t");

    //tell ADC to start read (converting analogue input to digital output)
    delayMicroseconds(10);
    digitalWrite(CONVST, LOW);
    delayMicroseconds(10);
    digitalWrite(CONVST, HIGH);
    //when read-conversion is complete ADC sends the BUSY pin low triggering the bitBang ISR

    //print ADC data from array within the bitBang ISR to a string
    String adcString = "";
    for(int thisChannel=0; thisChannel<channelCount; thisChannel++){
      adcString += String(adcData[thisChannel]);
      adcString += ",";
    }

    //disable interrupt to access current pulse count
    disableInterrupt(sensorPin1);
    disableInterrupt(sensorPin2);
    disableInterrupt(sensorPin3);
    //grab current pulse count and store in a variable
    pulses[0] = pulseCount1;
    pulses[1] = pulseCount2;
    pulses[2] = pulseCount3;
    //reset pulse count
    pulseCount1 = 0;
    pulseCount2 = 0;
    pulseCount3 = 0;
    //enable interrupt and start incrementing pulse count again
    enableInterrupt(sensorPin1, pulseCounter1, FALLING);
    enableInterrupt(sensorPin2, pulseCounter2, FALLING);
    enableInterrupt(sensorPin3, pulseCounter3, FALLING);

    String pulseString = "";
    for(int i=0; i<3; i++){
      pulseString += String(pulses[i]);
      if (i<2) {
        pulseString += ",";
      }
    }

    String dataString = String(adcString + pulseString);
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }

 //Serial.println(dataString);

  }
//start again
}

//grabbing ADC data ISR (for n channel)
void bitBang ()  {
  //a for loop to bitbang the values fom the analogue (ADC) channels (maximum 8) sequentially storing them in a variable array (equal to the channels of the ADC)
  for(int thisChannel=0; thisChannel<channelCount; thisChannel++){
  //send ADC read pin low to bitbang the first channel
  digitalWrite(RD, LOW);
  //read the state of the 16 pins and store in a variable
  rawData[0] = digitalRead(DB15);
  rawData[1] = digitalRead(DB14);
  rawData[2] = digitalRead(DB13);
  rawData[3] = digitalRead(DB12);
  rawData[4] = digitalRead(DB11);
  rawData[5] = digitalRead(DB10);
  rawData[6] = digitalRead(DB9);
  rawData[7] = digitalRead(DB8);
  rawData[8] = digitalRead(DB7);
  rawData[9] = digitalRead(DB6);
  rawData[10] = digitalRead(DB5);
  rawData[11] = digitalRead(DB4);
  rawData[12] = digitalRead(DB3);
  rawData[13] = digitalRead(DB2);
  rawData[14] = digitalRead(DB1);
  rawData[15] = digitalRead(DB0);
  //convert into 16bit 2s compliment and store in a variable array
  adcData[thisChannel] = rawData[0] | (rawData[1] << 1) | (rawData[2] << 2) | (rawData[3] << 3) | (rawData[4] << 4) | (rawData[5] << 5) | (rawData[6] << 6) | (rawData[7] << 7) |  (rawData[8] << 8) | (rawData[9] << 9) | (rawData[10] << 10) | (rawData[11] << 11) | (rawData[12] << 12) | (rawData[13] << 13) | (rawData[14] << 14) | (rawData[15] << 15);
  //send ADC pin high to say we have read the first channel
  digitalWrite(RD, HIGH);
  //repeat for n channels
  }
}

//counting pulses ISRs
void pulseCounter1(){
  // Increment the pulse counter
  pulseCount1++;
}
void pulseCounter2(){
  // Increment the pulse counter
  pulseCount2++;
}
void pulseCounter3(){
  // Increment the pulse counter
  pulseCount3++;
}
```

title: I cannot open/write to dataFile SD shield in mySketch but have no problem with Datalogger example sketch from the SD library...?

Answers: 1

body: The SD card uses SPI for communications.  You appear to be using those pins for some other purpose.  If you want to use the SD card, then you need to choose other pins and let the SD card have 50, 51, 52, and 53.


body:
I'm trying to use the popular SN74HC595 Shift Register, but I think something isn't right because when the bits are submitted to the register it comes out with something similar but not the same.

```c
#define Latch 9
#define CLK 10
#define DATA 8

byte led = B10110111;

void setup()
{
  pinMode(Latch, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(DATA, OUTPUT);

  digitalWrite(Latch, LOW);
  shiftOut(DATA, CLK, MSBFIRST, led);
  digitalWrite(Latch, HIGH);
}

void loop()
{
  //LOOP
}
```
After this completes I receive an output of 10110101 instead of 10110111. Has anybody had the same area? Any fixes? Could my chip be faulty inside?

Schematic:
[![Schematic][1]][1]

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

title: SN74HC595 Shift Register Issue

Answers: 0


body:
I was wondering how I could overcome the next issue;

My ESP8266 12E is connected as follows:

 - GPIO0 ground if needed to program, vcc otherwise
 - GPIO2 vcc
 - GPIO15 ground

[Bootmodes explained in the this schematic][1]

I also want to connect a MCP3002 to my ESP. However to use SPI I also need the GPIO15 pin to be connected to the Chip Select pin.

[MCP connections explained in this article][2]

----

I tried connecting the GPIO15 pin from the ESP to the CS pin of MCP3002 and connecting ground in between. This did not work though, should I switch/remove the ground after boot somehow?
(Or should I connect it differently?)

  [1]: https://www.circuito.io/blog/programming-esp8266-12e/
  [2]: https://prkl.info/esp8266-mcp3002-driver/

title: ESP12E Boot vs SPI

Answers: 1

body:
The io 15 is SS if esp8266 is slave. If esp8266 is SPI master, you can choose any free pin as CS of the slave.

----------

The esp8266 arduino boards package SPISlave library examples have a solution for master if esp8266 is slave.

The state of the boot pins is required only at boot. You should wire boot pins over a 10 kOhm resistor to create a pull-up/pull-down which can be override by pin output state to use the pins for devices which are OK with or need pull-up or pull-down, for example momentary switches (buttons).


body:
I am currently researching on I2C, and I made a configuration that has MasterWriter that transmits data to a SlaveReceiver that will store the data received from Master, into an SD card, and then transmit the same line of data by GPRS onto my back end.

Now the new requirement needs some kind of a caching system, so that if the GPRS failed to transmit, it'll instead save into the SD card under a different filename (the previous step of saving into SD Card is still done but it's for another purpose), so when the GSM signal needed has recovered it'll read the cached/backed-up data, and then transmit the backed-up data. So that means I'll use the loop block (which currently only has one line of delay function).

My question is, will the triggered function "receiveEvent" registered in setup for Wire Slave :

> Wire.onReceive(receiveEvent);

conflict with the ongoing loop block where the system reads the backed-up data and sends the backed-up data?

Here's my SlaveReceiver code :
<!-- language-all: lang-cpp -->

```

#define ONLINE_MODE 1 //  turn on for GSM.
#define CACHE_MODE 1 //   turn on for SD-based caching
#define I2C_MODE 1  //    turn on for I2C mode SDA-SCL

#include <Arduino.h>
#include "Slave_GSM_SD.h"

#if ONLINE_MODE
// Sim900
#include "GSM.h"
SIM900 gprs;
#endif

#if I2C_MODE
#include <Wire.h>
#endif

#if CACHE_MODE
//SD Card
#include <SPI.h>
#include <SD.h>
#define DEBUG_SD 1
#define SD_CS_PIN 4
File cacheFile;
#endif

void setup()
{
    console.begin(9600);
    while (!console);

    #if CACHE_MODE
     //SD Card
    Serial.print(F("Initializing SD card..."));

    if (!SD.begin(SD_CS_PIN)) {
      Serial.println(F("initialization failed!"));
      while (1);
    }
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    cacheFile = SD.open("CACHE.txt", FILE_WRITE);
    Serial.println(F("SD Card initialization done."));
    #endif

    #if ONLINE_MODE
    gprsSetup();
    #endif

    #if I2C_MODE
    Wire.begin(8);                // join i2c bus with address #8
    Wire.onReceive(receiveEvent); // register event
    #endif
    console.println(F("SLAVE GSM SD READY"));

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
// [Q] : will this interrupt/conflict with loop() if loop is still ongoing?
void receiveEvent(int howMany) {
  #if DEBUG_I2C
  Serial.print(F("available bytes : "));
  Serial.print(howMany);
  Serial.print(F(" or "));
  Serial.println(Wire.available());
  #endif

  #if I2C_MODE
  char jsonData[128]="";
  while (Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character

    int len = strlen(jsonData);
    jsonData[len] = c;
    jsonData[len+1] = '\0';

    #if DEBUG_I2C
    Serial.print(c);         // print the character
    #endif

    if (c == '}'){

      #if CACHE_MODE
      writeToSd(jsonData);
      #endif

      #if ONLINE_MODE
      gprsSequence(jsonData);
      #endif

      #if DEBUG_I2C
      Serial.println(F("SAVING TRIGGERED"));
      Serial.println(jsonData);
      #endif
    }

  }
  #endif
}

void writeToSd(char *jsonToWrite){

  #if CACHE_MODE
  // open the file. note that only one file can be open at a time,
 // so you have to close this one before opening another.
  cacheFile = SD.open("CACHE.txt", FILE_WRITE);
  if (cacheFile) {
    cacheFile.write(jsonToWrite);
    cacheFile.close();
  }

  #if DEBUG_SD
  Serial.println(F(" << "));
  // re-open the file for reading:
    cacheFile = SD.open("CACHE.txt");
    if (cacheFile) {
    Serial.println("CACHE.txt:");

    // read from the file until there's nothing else in it:
    while (cacheFile.available()) {
      Serial.write(cacheFile.read());
    }
      // close the file:
      cacheFile.close();
    } else {
      // if the file didn't open, print an error:
      Serial.println(F("error opening CACHE.txt"));
    }
  #endif
  #endif

}

void loop() {
    // i wanted to code the cached-data sending here
    delay(2000);
}

void gprsSetup() {
  //... cleared for brevity
}

void gprsSequence(char *jsonData) {
    //... cleared for brevity. the point is, this function is to send the jsonData by GPRS
}
```

title: Wire SlaveReceiver : will the registered function in onRecieve interrupt/conflict with loop block?

Answers: 1

body:
Generally the `onReceive` callback function is called from an ISR in the `Wire` library. That means, that no other interrupts can be handled during that time. For this reason an ISR always should be as short as possible. Writing to the SD card is a rather long process and it also uses interrupts, so it might block forever, when used in an ISR (though I'm not sure, since I didn't look through the SD library). You should do the SD card stuff outside of the ISR. In the ISR you can receive the I2C message and then set a flag variable, that will tell the code in the `loop()` function, that new data is available and that it can start processing it. That way your ISR stays short and the other operations will not be blocked by it. Do the same with the direct sending of GPRS data.

Also note, that transmitting Serial data inside of an ISR also does not work for the same reason (Serial relies on interrupts). The calls to `Serial.print()` or `Serial.write()` will only fill the libraries internal buffer. The data will get transmitted after the ISR was left. If you try to print/write data to Serial, when the buffer is full, the library will block, until the buffer has again space for sending the data, which will never happen inside the ISR. So you should be cautious with writing Serial inside an ISR. A bit doesn't hurt, but it can get a big problem.

> will the triggered function "receiveEvent" registered in setup for
> Wire Slave `Wire.onReceive(receiveEvent);` conflict with the ongoing
> loop block where the system reads the backed-up data and sends the
> backed-up data?

From the general logic there cannot happen more than 1 specific data operation on the SD card at the same time. If you are currently writing one file, you cannot simply break the transmission through an interrupt and writing another file without breaking things. The transaction has to be completed, or you will fastly corrupt your file system. But, as I wrote above, this isn't really possible either way, because the SD card calls will not work properly inside of an ISR. So just put all the GPRS and SD card code into the `loop()` function and trigger the corresponding code blocks with a flag from the ISR. That way nothing can conflict here.


body:
Currently, I'm doing a project as I want to use my Arduino Mega 2560 as an interface to my computer with a photo interrupter and stepper motor. So I need to send some commands and data to the Arduino from my PC. However, after upload the code to the board, I found out the serial communication of the Arduino quite slow. In fact, the moment after the code done uploading, my command in the Serial Monitor takes almost a second to execute. Below is the details about the code:-

        // Include the Arduino Stepper Library
    #include <Stepper.h>

    // Number of steps per output rotation
    const int stepsPerRevolution = 200;

    // Create Instance of Stepper library
    Stepper myStepper(stepsPerRevolution, 12, 11, 10, 9);

    int val;
    int counter = 0;

    void setup()
    {
      // set the speed at 200rpm:

      myStepper.setSpeed(200);
      // initialize the serial port:
      Serial.begin(9600);
    }

    void loop()
    {
      val = analogRead(A0);
      Serial.println(val);

      myStepper.step(stepsPerRevolution);
      counter = counter + 1;
      Serial.println(counter);

    if (val > 200){
        Serial.println("it is running");

       } else {
        myStepper.setSpeed(0);
        Serial.println(counter);

       }

    }

Any help so much appreciated.

title: Slow serial communication with arduino and response on the application?

Answers: 0


body:
I want to control about 20 leds with an arduino mega.
This leds works with 12v voltage.

I tried to put 20 relays but this solution is not good for me because leds will often blink

I have also tried transistors but it needs to make a pcb.

I am looking for a solution without having to create a pcb

Any idea ?

Thanks

title: Connect 20 12v led to an arduino mega

Answers: 4

body:
You can use the commonly available L298N module to drive four of your LEDs with each module. That means you would need five of them.
[![L298N module][1]][1]
Those modules are suitable for driving either one stepper motor, two DC motors (in both directions), or four "unidirectional" loads such as your LEDs.

The input can be connected directly to your MEGA, but you may need additional series resistors depending on the LED you use (though this likely does not apply for LEDs specified as "12V").

There are also LED driver eval boards available which may suit your needs:
https://www.digikey.de/product-detail/de/adafruit-industries-llc/1455/1528-1019-ND/4990768

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

body:
The ULN2803 is a chip with 8 darlington transistors in it designed for driving higher voltage, low-ish current, loads like this.  With 3 of them you have 24 channels to drive your LEDs.

You can get them on a breakout board quite easily, or as a DIP chip for working with breadboards.

body: Try s MOS- FET transistor.  Its not expensive and easy to drive.  Can be directly connected to the Arduino.  Look for standard circuit diagrams.  1 P- Mos Fet and 1 Resistor per channel,  esch can drive several Amperes st 12V...

body:
Three TPIC6B595 shift registers, controlled by 3 pins from the Mega, can do this easily. Shift in 3 bytes with on/off state of the LEDs.
Can sink 150mA per output from 12V source.  The LEDs need current control, from simple resistor for 20mA loads, to a constant current driver per LED for higher current LEDs.

I used them to sink current from 12V for the LED strings in this display. The small digits needed ~ 20mA per segment, the larger digit is really 2 groups of 3 LEDs, drawing about 40mA per segment. One shift register per digit.

https://www.youtube.com/watch?v=6HZ0Mr51jUY


body:
This is probably a fundamental question but I am hoping to get some pointers on how to chose between Arduino Pro Mini and ESP 32.

I am hoping to make a wrist based wearable like fitbit. Three primary needs are

1. Accelerometer or MPU module is important to collect movement data.
2. Wi-fi is not important because I think bluetooth would be enough to sync the data to a cell phone.
3. Battery management is of course more critical as I want it to last longer.
4. Smaller the dimensions, better for design and aesthetics.

My first choice was using Arduino  pro mini because it is smaller and less  power consuming.  However, we do need to manually connect BLE module like HC-05 to it. Now I think ESP32 could also be a good option because it has both wifi and bluetooth although I do not care about wifi.

Now I found these useful comparisons on web

 1. Arduino and NodeMcu (ESP8266) like [this][1]
 2. Between ESP32 vs ESP8266 like [this][2]
 3. Between Nano or pro mini like [this][3]

However, none of them help me directly in my case. I understand ESP32 and ProMini are meant for different things and hence should not be compared for a single project. May be I am missing something more fundamental. Any guidelines in this would really help.

  [1]: https://www.reddit.com/r/arduino/comments/8elsur/arduino_uno_vs_nodemcu/
  [2]: https://makeradvisor.com/esp32-vs-esp8266/
  [3]: https://forum.arduino.cc/index.php?topic=545132.0

title: Choosing between ESP32 and Arduino Pro Mini

Answers: 0


body:
I'm stuck in my project, I try to read an absolute encoders angular position with my Arduino.
I used and cabled a differential line receiver and driver between Arduino and the encoder, like explained in the 2 following links:

- Figure 2.1 [here](https://www.posital.com/media/posital_media/documents/AbsoluteEncoders_Context_Technology_SSI_AppNote.pdf)

- [Input circuitry of subsequent electronics](https://www.heidenhain.co.kr/fileadmin/pdb/media/img/1078628-21_Interfaces_en.pdf)

[Here][3] are the specifications of the encoder that I try to read.

[3]: https://www.heidenhain.de/fileadmin/pdb/media/img/1113963_00_A_02_ROQ425_TTL_HTL.pdf

Here is my Arduino code :

    const int CLOCK_PIN = 5;
    const int DATA_PIN = 6;
    const int BIT_COUNT = 25;

    void setup() {
      //setup our pins
      pinMode(DATA_PIN, INPUT);
      pinMode(CLOCK_PIN, OUTPUT);

      //give some default values
      digitalWrite(CLOCK_PIN, HIGH);

      Serial.begin(115200);
    }

    void loop() {
      float reading = readPosition();

      if (reading >= -0.5) {
          //Serial.print("Reading: ");
          //Serial.println(reading,2);
      }

      delay(200);
    }

    //read the current angular position
    float readPosition() {
      unsigned long sample1 = shiftIn(DATA_PIN, CLOCK_PIN, BIT_COUNT);
      unsigned long sample2 = graytobin(sample1, BIT_COUNT);
      delayMicroseconds(25);  // Clock mus be high for 20 microseconds before a new sample can be taken

      Serial.print("grey: ");
      Serial.println(sample1, BIN);
      Serial.print("binary: ");
      Serial.println(sample2, BIN);
      Serial.print("decimal: ");
      Serial.println(sample2 & 0x0FFF);
      Serial.print("\n");

      return ((sample2 & 0x0FFF) * 360UL) / 4096.0;
    }

    // gray to binary
    int graytobin(int grayVal, int nbits ) {
      int binVal = 0;
      bitWrite(binVal, nbits - 1, bitRead(grayVal, nbits - 1)); // MSB stays the same
      for (int b = nbits - 1; b > 0; b-- ) {
        // XOR bits
        if (bitRead(binVal, b) == bitRead(grayVal, b - 1)) { // binary bit and gray bit-1 the same
          bitWrite(binVal, b - 1, 0);
        }
        else {
          bitWrite(binVal, b - 1, 1);
        }
      }
      return binVal;
    }

    //read in a byte of data from the digital input of the board.
    unsigned long shiftIn(const int data_pin, const int clock_pin, const int bit_count) {
      unsigned long data = 0;

      for (int i=0; i<BIT_COUNT; i++) {
        data <<= 1;
        digitalWrite(clock_pin,LOW);
        delayMicroseconds(1);
        digitalWrite(clock_pin,HIGH);
        delayMicroseconds(1);

        data |= digitalRead(data_pin);

      }

      return data;
    }

I'm still able to receive information with my Arduino from the encoder but they are totally random. Here is an example of the output I get (I didn't move the encoder during this exercition):

    grey: 1001111101110100011111001
    binary: 11111111111111111011000010101110
    decimal: 174

    grey: 111110110010001111100111
    binary: 11110101000101
    decimal: 3397

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 1111111111111111111111111
    binary: 11111111111111111010101010101010
    decimal: 2730

    grey: 1011001110011011100010001
    binary: 10010111100001
    decimal: 1505

    grey: 1100111011011100100011111
    binary: 11111111111111111101000111101010
    decimal: 490

    grey: 1101110110111001000111111
    binary: 101110000101010
    decimal: 3114

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 111111
    binary: 101010
    decimal: 42

    grey: 111011011100100011100111
    binary: 11111111111111111000111101000101
    decimal: 3909

    grey: 1100111001101110010001111
    binary: 11111111111111111001011100001010
    decimal: 1802

    grey: 1100111011011100100011111
    binary: 11111111111111111101000111101010
    decimal: 490

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

    grey: 0
    binary: 0
    decimal: 0

I don't know how to diagnose the problem, and how to find it.

title: read with Arduino SSI encoder signal

Answers: 0


body:
I am trying to run a Stepper motor from my c++ application, from which I sent commands but its not running not sure why would it not run, outside serial check it run but inside serial check it not run.

Here is my code, not sure what am doing wrong, my first time with Arduino.
<!-- language-all: lang-cpp -->

    #include <AccelStepper.h>

    #define BAUD 9600

    // CNC Shield V3  Step and Dir pins on Mega 2560
    #define step_pin_x 2
    #define dir_pin_x 5
    #define MOTOR_X_ENABLE_PIN 8
    // Drive A4988
    #define motorInterfaceType 1

    AccelStepper stepper_X = AccelStepper(motorInterfaceType, step_pin_x, dir_pin_x);

    void setup() {
      Serial.begin(BAUD);
      pinMode(53, OUTPUT);   // for red led it pin # 53
      pinMode(MOTOR_X_ENABLE_PIN, OUTPUT);  // for X stepper motor

        stepper_X.setMaxSpeed(1000);
        stepper_X.setSpeed(500);
    }

    void loop() {
        String input;
      //If any input is detected in arduino
      if(Serial.available() > 0){
        //read the whole string until '\n' delimiter is read
        input = Serial.readStringUntil('\n');

        if (input.equals("ON")){
           digitalWrite(53, HIGH);   // Turn ON RED LED
           stepper_X.runSpeed();      // Suppose to run stepper motor .. but not working
           Serial.println("X Motors:: "+input);

        }else if (input.equals("OFF")){
           stepper_X.stop();
           digitalWrite(53, LOW);    // Turn OFF RED LED
           Serial.println("X Motors:: "+input);
        }

      }else{
      //  stepper_X.runSpeed();      // if uncommented stepper motor will run
      }
    }

**Update**
so it seems its code blocking issues

i update my code according to tut : https://majenko.co.uk/blog/reading-serial-arduino

        char buf[80];

        int readline(int readch, char *buffer, int len) {
            static int pos = 0;
            int rpos;

            if (readch > 0) {
                switch (readch) {
                    case '\r': // Ignore CR
                        break;
                    case '\n': // Return on new-line
                        rpos = pos;
                        pos = 0;  // Reset position index ready for next time
                        return rpos;
                    default:
                        if (pos < len-1) {
                            buffer[pos++] = readch;
                            buffer[pos] = 0;
                        }
                }
            }
            return 0;
        }

    void loop() {
       if (readline(Serial.read(), buf, 80) > 0) {
       if(strcmp("n", buf) == 0){
              digitalWrite(53, HIGH);
             stepper_X.setMaxSpeed(1000);
             stepper_X.setSpeed(500);
              stepper_X.runSpeed();
              Serial.print("All Motors:: ");
              Serial.print(buf);

            }
        }
    }

now its working ok

**Update 2 :** c++ sending command via Serial

        std::string input_command = "ON";
        //Creating a c string
         char *c_string = new char[input_command.size() + 1];
         //copying the std::string to c string
         std::copy(input_command.begin(), input_command.end(), c_string);
         //Adding the delimiter
         c_string[input_command.size()] = '\n';

    // using this serial lib : https://github.com/manashmndl/SerialPort
       writeSerialPort(c_string, MAX_DATA_LENGTH);

title: How to Run Stepper motor through Serial Communication

Answers: 1

body:
Per [the documentation of the AccelStepper’s `runSpeed()`
method][runSpeed]:

> You must call this as frequently as possible, but at least once per
> step interval,

It appears the AccelStepper library is not compatible with blocking
code. Not a big deal, blocking code is almost always bad practice
anyway. However, `Serial.readStringUntil()` is a blocking function: it
will prevent the program from doing any useful work.

You have to [read the serial port in a non-blocking fashion][serial],
use the commands to set the motor speed, and always call `runSpeed()` as
frequently as possible.

[runSpeed]: http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#aa4a6bdf99f698284faaeb5542b0b7514
[serial]: https://majenko.co.uk/blog/reading-serial-arduino


body:
I get new boards from the shop but they are little different from the previous version. I got software what works ok on Nodemcu lolin v3 now I get Nodemcu Amica what is almost same board but if I got attachInterrupt function in the program it crashes immediately.

        attachInterrupt(6, bowlingCall, RISING);
    //attachInterrupt(digitalPinToInterrupt(D1), statekCall, RISING);

I try different pins but not change. I debug all program(comment all out and left just attachInterrupt and it crashes again).

        ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v8b899c12
    ~ld

The board cycle in the reboot sequence, even serial output do not work ok. Why did esp crash at attachInterupt on this board?

title: ESP - Nodemcu amica - attachInterrupt crash program

Answers: 1

body:
thanks @Juraj.

Ok, so all you need is rewrite all your interrupt function.
For example:

    void getStatusFromMaster()

to

    void ICACHE_RAM_ATTR getStatusFromMaster()


body:
i'm having an odd problem where despite having the correct port selected 3 times i'm still getting an error as shown below: [![error][1]][1] message:

    Arduino: 1.8.9 (Windows 10), Board: "Adafruit Feather M0, Arduino, Off"

    Sketch uses 20876 bytes (7%) of program storage space. Maximum is 262144 bytes.
    Atmel SMART device 0x10010005 found
    Device       : ATSAMD21G18A
    Chip ID      : 10010005
    Version      : v2.0 [Arduino:XYZ] Mar  5 2016 17:46:52
    Address      : 8192
    Pages        : 3968
    Page Size    : 64 bytes
    Total Size   : 248KB
    Planes       : 1
    Lock Regions : 16
    Locked       : none
    Security     : false
    Boot Flash   : true
    BOD          : true
    BOR          : true
    Arduino      : FAST_CHIP_ERASE
    Arduino      : FAST_MULTI_PAGE_WRITE
    Arduino      : CAN_CHECKSUM_MEMORY_BUFFER
    Erase flash
    done in 0.832 seconds

    Write 21164 bytes to flash (331 pages)

    [=====                         ] 19% (64/331 pages)
    [===========                   ] 38% (128/331 pages)
    [=================             ] 58% (192/331 pages)
    [=======================       ] 77% (256/331 pages)
    [============================= ] 96% (320/331 pages)
    [==============================] 100% (331/331 pages)
    done in 0.128 seconds

    Verify 21164 bytes of flash with checksum.
    Verify successful
    done in 0.016 seconds
    CPU reset.
    Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

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

title: Why is the IDE not able to find the board despite it being clearly seen and selected?

Answers: 1

body:
The SAMD boards connect to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.

A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by **double clicking the reset button** on board.


body:
I have a VERY long code:

> Sketch uses 30468 bytes (92%) of program storage space. Maximum is
> 32768 bytes.

I've been trying to reduce it's size so i can write more code, one of my main part of code which repeated many times in switch cases or in if statements is related to de-bouncing the buttons.

Here's a piece of my code as an example:

      case 12:
        if ((millis() - millistimer) > BounceD) {
          if (receivedValue == RFb) {
            magnetDistance += 5;
            millistimer = millis();
            receivedValue = 0;
          }
        }
        if ((millis() - millistimer) > BounceD) {
          if (receivedValue == RFd) {
            magnetDistance -= 5;
            millistimer = millis();
            receivedValue = 0;
          }
        }
        break;

The de-bouncing actions happens in each and every case and for each and every button.

There's two buttons which in each `case` increase/decrease different values.

How to avoid repeating the de-bouncing action for every button?

___

**EDIT:**

The `recievedValue` is updated via RC buttons value once any button is pressed on the remote.

title: How to NOT repeat a piece of code again and again?

Answers: 1

body:
In the short example of above, first find out what is a duplicate (the two outer `if` statements including their body), than the differences:

- Rfb versus Rfd
- +5 versus -5

Than make a function for the duplicated code, and turn all differences into a parameter (I don't know the type of Rfd, so I take an int for it).

You will get:

    case 12:
      processButton(&Rfb,  5); // Offset magnet distance by +5
      processButton(&RFd, -5); // Offset magnet distance by -5
      break;

      ...

    void processButton(int* rf, int diff)
    {
      if ((millis() - millistimer) > BounceD) {
        if (receivedValue == *rf) {
          magnetDistance += diff;
          millistimer = millis();
          *rf = 0;
        }
      }
    }

Note that if `magnetDistance` and `millistimer` are local variables you also have to pass them (as pointer to change the value), if they are globals you can keep the code as is above.

**UPDATE**

The way parameter works is as follows. E.g.

    processButton(Rfb,  5);

Will call the following function:

    void processButton(int rf, int diff)

Where value rf will be Rfb, and diff will be 5 (+5).

Thus when `magnetDistance += diff;` is executed, diff will be +5 and magnetDistance will be increased with +5. In the next call, magnetDistance will be -5 and thus will be subtracted.

**UPDATE 2**

To change a variable, you have to pass it as pointer, otherwise the (copied) parameter value will be changed and not return its value to the called function. So you have to give the parameter as an address (& operator), and use -> instead of . to get to the value.


body:
So, I've finally able to send and receive MIDI using Arduino.

My next thing to do was sending 5 pin MIDI to rtpMIDI, and vice versa, using ESP8266, but so far I can't even send MIDI correctly.
So far, I used this library, and it send midi without issues with Arduino Mega. But using Wemos D1, strange thing happens.

[![enter image description here][1]][1]
this is output of MIDI OX. Pretty sure I wasn't sending MIDI CC.

Here's the code so far :

    #include <MIDI.h>

     // Created and binds the MIDI interface to the default hardware Serial port
     MIDI_CREATE_DEFAULT_INSTANCE();

     void setup()
     {
         MIDI.begin(MIDI_CHANNEL_OMNI);  // Listen to all incoming messages
     }

     void loop()
     {
         // Send note 42 with velocity 127 on channel 1
         MIDI.sendNoteOn(42, 127, 1);

         // Read incoming messages
         MIDI.read();
     }

UPDATE : Here goes the settings.

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

Any reason why this happens? Please help me. Thanks!

Schematics :

Basically I just change the Arduino to Wemos D1 Uno.
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/i5EX0.png
  [2]: https://i.stack.imgur.com/eWgcu.png
  [3]: https://i.stack.imgur.com/jqPZz.png

title: How do I send MIDI properly with ESP8266?

Answers: 1

body:
NOTE : Probably not the answer you're looking for, but it works for me.

Solution : Move the jumper from 5V to Vin.

Why? I don't know. It just works.

Please notice that this is Wemos D1 Uno, which has adaptor input, which can receive 9-24V.

If you're going to use the adaptor, IT MAY BROKE YOUR MIDI DEVICE!

As far as I know, Vin stands for Voltage Input, and everything from the adaptor is routed there. That means if you use 24v adaptor, Vin is 24v!

I'm only planning to use USB as power supply, so yeah. it works for me.

If you're going to use Vin with external power supply, please use voltage regulator to 5v. Better safe than sorry.

Anyway, since I'm planning to use 6N137 to receive MIDI also on this board, here goes :

> Input voltages greater than 7 V must be avoided to preclude damage to
> the gate oxide of the input stage. This damage is not necessarily
> permanent, but will adversely affect the expected lifetime of the
> circuit. The gate oxide of AHC devices is only 200 Å thick. An input
> voltage of 7 V corresponds to a field strength over the gate oxide of
> 350 kV/cm. Although breakdown of the oxide is expected only at input
> voltages above 10 V, electrons tunnel increasingly into the gate oxide
> at field strengths greater than 350 kV/cm, influencing characteristics
> of the transistors and causing failure.

Source : this question on electronics stackexchange.