message:
Arduino UNO two SoftwareSerial ports communication

I am working on a project involving bluetooth and wifi communications. Both of them are wired up to the Arduino and communicate to it using two software serial port.
The scenario is the one in the picture attached.

What I am doing is:

 - retrieve the sensor value
 - send it from the BT slave module to the master one (wired up to Arduino)
 - take it and send it, using AT commands, through the WIFI channel (the WIFI module is a ESP8266-01) to a web server.

The problem is that if I start listening to the BT serial port (BTSerial.listen()) I am not able to properly send the sensor values through the WIFI connection. But if I comment out the lines related to the BT sotware serial, and try to send fixed value to the web server, the sending terminates succesfully.

In my opinion there are some problems with the BTSerial.listen() and WIFISerial.listen() calls, since they are not able to switch from one the the other correctly.

I saw the TwoSerialPort example provided into the Arduino IDE and I tried to apply it into my code but it still not works to me.

Does anyone have a idea which would be the problem? Does anyone already faced with this problem or a similar one?

Hoping to be as much clear as possible, thanks in advance to anyone would help me.

Filippo

**[EDIT] Added two code snippets**

    // This method prepares the AT commands will be send to the ESP8266-01 module in order to upload the values on the web server
    void send2server(String ip, int port, String file, int t, int h, int p) {

      String queryString = "temp=";
      queryString.concat(t);
      queryString.concat("&hum=");
      queryString.concat(h);
      queryString.concat("&press=");
      queryString.concat(p);
      Serial.println(queryString);

      // Prepare and exec the AT+CIPSTART command provideing the TCP connection init
      String CIPSTART_cmd = "AT+CIPSTART=\"TCP\",\"" + ip + "\"," + port + "";
      exec_cmd(CIPSTART_cmd, 1000);

      // Prepare the POST request
      String httpPOST_cmd = "POST /";
      httpPOST_cmd.concat(file);
      httpPOST_cmd.concat(" HTTP/1.1\r\n");
      httpPOST_cmd.concat("Host: ");
      httpPOST_cmd.concat(ip);
      httpPOST_cmd.concat("\r\n");
      //httpPOST_cmd.concat("Accept: */*\r\n");
      httpPOST_cmd.concat("Content-Length: ");
      httpPOST_cmd.concat(queryString.length());
      httpPOST_cmd.concat("\r\n\r\n");
      //httpPOST_cmd.concat("Content-Type: text/html\r\n\r\n");
      httpPOST_cmd.concat(queryString);

      // Calculate the POST request length
      unsigned int len = httpPOST_cmd.length();

      // Prepare and exec the AT+CIPSEND statement with the POST request length just calculated
      String CIPSEND_cmd = "AT+CIPSEND=";
      CIPSEND_cmd.concat(len);
      exec_cmd(CIPSEND_cmd, 1000);

      // Exec the HTTP POST request
      exec_cmd(httpPOST_cmd, 1000);

      // Close the connection
      exec_cmd("AT+CIPCLOSE", 1000);
    }

    // This method execute each AT command in the previuous method
    void exec_cmd(String cmd, int delayTime) {
       byte i = 0;

       while(1) {
          Serial.println("invio comando");
          WIFISerial.println(cmd);
          while(WIFISerial.available()) {
             if(WIFISerial.find("OK")) {
                i = 8;
             }
          }
          delay(delayTime);

          if(i > 5)
             break;

          i++;
       }

       if(i == 8) {
          Serial.println("OK");
          //return true;
       } else {
          Serial.println("ERRORE");
          //return false;
       }
    }
The problem is the code goes properly till the AT+CIPSEND command, then the POST request is sent but no good feedback arrives, ending with the "ERRORE" error message.
[![enter image description here][2]][2]

**[EDIT 2] Attached serial monitor output**
This is the serial monitor output when I execute the skecth. It seems to work properly but it does not upload any value.
[![enter image description here][1]][1]

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

body:
[This answer](https://arduino.stackexchange.com/questions/34126#34130) provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

*  Use the `HardwareSerial` port (i.e., `Serial`) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.

*  Use `AltSoftSerial` for the other device.  It is the most efficient software serial port, and it can be used at the same time as `Serial`.  It only works on two specific pins.

*  `NeoSWSerial` is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on `NeoSWSerial` prevents them from receiving.

*  `SoftwareSerial` is the worst choice.  Receiving **or** transmitting on `SoftwareSerial` prevents all of the above from receiving anything.  It disables interrupts for long periods of time.

<hr>
### UPDATE - Here is the most reliable configuration:
[![enter image description here][1]][1]

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

Your code will have something like this:

    #include <AltSoftSerial.h>
    AltSoftSerial BT; // 8 is RX, 9 is TX

    #define WIFI Serial  // 0 is RX, 1 is TX (disconnect 0 to upload new sketch)

    void setup()
    {
      WIFI.begin( 115200 );
      BT.begin( 9600 );
    }

    void loop()
    {
      if (BT.available) {
        char c = BT.read();
        // do something with the character
           ... save them until '\n' arrives?
             ... then parse some values?

        if (values all received) {
          Serial.print( F("Sending values") ); // this is the WIFI port, but
              //  the ESP8266 ignores this debug print because it doesn't
              //  start with "AT".

          WIFI.println( F("AT+ ...") ); // all the AT commands
              ...
          WIFI.print( btValue1 );    // and the BT values
              ...
        }
      }
    }


sender: user

message:
ATtiny85 soft-latching, and sensor-waking: Are multiple switches differentiable by pin change interrupt?

I am using a vibration switch with a pin change interrupt on an ATTiny85 to wake the processor and run some code when the vibration switch grounds an input pin. The circuit is battery-powered, so sleep mode is important. I would now like to add another input switch (momentary pushbutton) between an internal pullup on the ATtiny and ground to use as a soft latching switch to accomplish on/mode/off (power-on/case-selection/power-off). I'd like the vibration-wake-sleep code to be one of the cases selectable by the pushbutton. The ATtiny85 has one hardware interrupt (pin2 aka INT0), and the rest are pin change interrupts available on the other I/O pins.
After reading around, my understanding is that the pin change interrupts *cannot* be separated to run pin-specific code, as they all trigger the same pin change interrupt effect. Is that correct?
To put it another way, do I need to put my pushbutton on the hardware interrupt pin, or can I put it on any old I/O pin and still be able to use the vibration switch on another I/O pin only when I select that mode, without it triggering the same effect as the pushbutton every time there's a vibration? Or is there a better way? I'm trying to minimize the number of components, as this is a space-constrained project. Thanks!

sender: assistant

body:
If you have one dedicated interrupt signal, and enable the shared pin change interupt *for only one* pin, then you have no ambiguity - the hardware ISR is caused by the dedicated pin, and the shared pin change ISR is caused by the only enabled pin change pin.

Where things get more complicated is if you enable more than one pin to trigger the pin-change interrupt.  In this case, either the ISR or whatever follows in cause from it will need to figure out which pin caused the interrupt.

Unless I'm overlooking it in the data sheet, the ATtiny pin change interrupts don't have a register which latches the causing condition, so you may have to look at the actual pin input register.   The catch is that things like contact bounce might make the causing signal no longer present at the exact instant you check it.  However, contact bounce is typically a more serious problem when *releasing* a contact than closing it.

Some things you can do:

- In the ISR, don't actually do anything, but set an "interrupt happened" flag.  Then in the main program, poll the inputs for a while until you see one actually asserted, and act on that.  You should only need to stay awake for a small fraction of a second before you catch the responsible contacts closed when you are looking.

- You could try to use a small capacitor to slow the rate at which the pullup resistor responds to the switch bouncing back open, in the hopes of  making sure that the causing condition is seen when the ISR itself looks.

In either case you will probably want to stay awake and keep the pin change interrupt *disabled* until the switch has been released, and for maybe a hundred milliseconds thereafter to let release bounces die out.  Then you can re-enable the interrupt and go back to sleep.

Do keep in mind that regardless if the MCU is awake or not, if someone wedges the product into packing material or something which holds the switch closed in opposition to the pullup resistor, then that pullup resistor itself may drain your battery over a few weeks/months.


body:
> Or is there a better way?

Read the data sheet to see if it has individual flags for those pins.

Short of that, read and keep track of the pin states in the use to see which pins may have changed.


message:
Maximum Delay time

I am designing a driver for a Bipolar stepper motor using Arduino Mega 2560 and DRV8825 Stepper driver.

In my application, a stepper motor (Nema 24) will run for 5 minutes and stop for 2 minutes. I have doubts about is what is the maximum time an Arduino Mega can delay the process, or how much a maximum time `delay()` function will last, or work in programming?

body:
*Note: there's an existing question here this should be closed as a duplicate of, but that is proving hard to find.  So until someone does find it...*

The arduino `delay()` function creates a *blocking* delay of the provided number of milliseconds.   The argument is an `unsigned long` which on a 16-bit Arduino is a 32-bit unsigned integer type, having a maximum value of 4,294,967,295.  Since these are milliseconds, the maximum `delay()` would be 4,294,967.295 seconds, or about 49 days.

However, you can easily achieve longer delays by using counting variables to count up instances of shorter delays.  At an extreme, by using up available memory for keeping track of such counting, you can readily achieve theoretical delays exceeding the age of the universe.

Note that the Arduino `delay()` function is *blocking*, which is to say that nothing else (except interrupts and on-chip hardware peripherals) runs during it.  This is often undesirable.  A more useful solution might be to make a loop taking say 20 milliseconds to run, as the result of a `delay()` and a few housekeeping operations, and then run this over and over again while counting.  Or you could make a 1 second loop, or whatever you choose.


message:
How to get Arduino to talk to two seperate motors wirelessly?

I have an Arduino Uno and I also have two Servo Motors. Say I have a room that is 15 feet wide, and I want to be able to place the Arduino in the center of the room and control two servo motors placed at each end of the room using a button on the Arduino. Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers? Or will I have to use three Arduinos, one for the center with the button and one for each servo. If so, will I be able to substitute the two servo Arduinos with an ATtiny chip?

body:
You'll probably need 3 "controllers", of which the one in the middle of the room might need to be a full-featured Arduino. Depending on the the needed libraries of your bluetooth receivers at the remote servos, it seems likely that you could use ATTinys in place of more feature-filled Arduino, but you would still have to think of the ATTinys as Arduinos or at least the glue controller to translate commands from Bluetooth to servo signals (PWM).

You could provide us with more details, such what particular bluetooth modules or transceivers you plan to use; some might provide an asynchronous serial interface, others might present an I2C or SPI interface, and given the small flash and RAM size in the ATTiny line, you would need to evaluate the code and associated libraries needed to operate it on such a processor.

The answer to your question is, "Maybe", given the small amount of detail you have provided.


message:
SPI MOSI receive error

I have a master and a slave (both are arduino UNO) connected through SPI connected. I want to transmit a character to the slave and receive true or false to the master. The transmission is working perfectly. If I send `'2'`, slave is receiving `'2'`. When I try to transmit an integer from slave to master, the master is always receiving some arbitrary number like 128 or 255.

Master Code:

    void setup() {
      Serial.begin(9600);
      Serial.println("Master");
      digitalWrite(SS,HIGH);
      SPI.begin();
      SPI.setClockDivider(SPI_CLOCK_DIV8);
    }
    void loop() {
      digitalWrite(SS,LOW);  //  Slave select to low
      received1 = SPI.transfer(test);  // test is a variable which is '2'. The data received by master is stored in received1 variable which is char.
      Serial.println(received1);
      digitalWrite(SS,HIGH);
    }

Slave code:

    void setup() {
      Serial.begin(9600);
      Serial.println("Slave");
      pinMode(MISO,OUTPUT);
      SPCR |= _BV(SPE);
      process = false;
      SPI.attachInterrupt();
    }
    ISR(SPI_STC_vect){
      received = SPDR;  // the data received by slave is slored in **received** variable(the variable is char type)
      Serial.println(received);
      process = true;
    }
    void loop() {
      if(process){
        SPDR = jj;  // Updating SPDR to send data from slave. jj is char type
        process = false;
      }
    }

body:
I have found a solution for this problem in a blog.

Link: http://www.gammon.com.au/forum/?id=10892

I modified my master code and got my desired result.

Master code:

    byte transferAndWait (const byte what)
    {
      byte a = SPI.transfer (what);
      delayMicroseconds (2000);
      return a;
    } // end of transferAndWait

    void loop() {
      digitalWrite(SS,LOW);
      transferAndWait (10);
      received1 = transferAndWait (11);
      digitalWrite(SS,HIGH);
      Serial.println(received1);
    }

The response will be "collected" next time through the loop. That's why we need to keep a dummy `transferAndWait()` function first and then the result of that transfer will be stored in `received1` variable.


message:
My Arduino code will not compile, when I can't see anything wrong with it

It keeps on giving me the error:

    Error compiling for board Arduino/Genuino Mega or Mega 2560.

Other sketches work fine, but this one will not compile, even though I have all the libraries.

Here is the link for the code:
https://drive.google.com/open?id=0B3R5NMiGZ3RPSk9WS0Y1amtEYms

The full error:

    Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

    (.text+0x0): multiple definition of `__vector_13'

    libraries\IRLibRecv\IRLibRecv.cpp.o (symbol from plugin):(.text+0x0): first defined here

    d:/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

    collect2.exe: error: ld returned 1 exit status

    exit status 1 Error compiling for board Arduino/Genuino Mega or Mega
    2560.

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

body:
I can't see you code, but my guess is that you are passing an unsigned value into `round()`.

`millis()` returns an unsigned long, this means it can never be negative, so if you test `millis() >= 0` it will always be true.  That is your issue.

Write you own round function that doesn't check its greater than 0.


body:
There are a number of issues with your code besides the actual error:

* You are dividing an unsigned long by an integer which results in an unsigned long, then rounding it. Makes no sense.
* You are assigning (I assume - without seeing your code I can't be sure) long constants (eg `0xFFE01F`) to an integer - which overflows and whinges.

However your main problem is that you have two interrupt service routines (ISRs) for the same interrupt (vector 7). What that interrupt is I can't say, since it is different on different chips, and you don't seem able to make your mind up if you're using an Uno or a Mega (you tagged your question both for some reason). So you will have to change code and/or libraries to use different interrupts or combine the two together to use just one ISR.


body:
just some warnings about generally unsafe/unsound code pieces.

the major issue (potentially unresolvable) is the vector-7 error. you should look into the datasheet to see what interrupt vector it is referring to first. There are more than one of such ISRs declared in your code.


body: I searched but couldn't find an answer, then I suddenly released my Arduino external power caused this problem. When I shut down the external power I could install it in my device. I hope it works for your problem.


message:
How to control Arduino using mBlock and Bluetooth?

Is it possible to control an Arduino using mBlock and Bluetooth?

Assuming yes, I tried various things, but was not able to come to a conclusion.

I am trying to get this combination working using a HC-05 Bluetooth module. I am not sure if my Bluetooh setup is the problem or is mBlock is not able to recognize the COM port provided by Bluetooth.

I can see the COM device (in fact two?) when I pair HC-05 with PC. I have the following questions based on whatever I have tried so far:

- When I connect HC-05, should I connect TX to TX OR reverse them?
- There are varying articles describing both ways of connection.
- How much baud rate do I need to set on the Bluetooth device?
- Do I need to use the voltage divider for RX? Again there are varying tutorials.
- Is mBlock default Arduino firmware sufficient for such setup?

body:
> - When I connect HC-05, should I connect Tx to Tx OR reverse them?
>     - There are varying articles describing both ways of connection.

Yes, swap them. TX on the HC-05 to RX on the Arduino. However you could struggle to use pins 0/1 since they are the USB connection. SoftwareSerial (which is nasty) is what most people use instead.

> -  How much baud rate do I need to set on the bluetooth device?

Whatever rate you want to communicate at. It's up to you. However all baud rates must match throughout the system - the baud rate on the Arduino, the baud rate of the HC-05, the baud rate of the SPP port on your PC, etc.

> - Do I need to use the voltage divider for Rx? Again there are varying tutorials.

Which RX? Arduino TX to HC-05 RX yes. HX-05 TX to Arduino RX no.

> - Is mblock default arduino firmware sufficient for such a setup?

What is *mblock*?


body:
I got it working. Following are steps.

- Set the Bluetooth baud rate to 115200. The mBlock firmware uses
  this baud rate for serial communication.
- Connect Bluetooth to Rx and Tx of Arduino.
- Upload default Arduino firmware (orion firmware) to
  Arduino using mBlock.
- Use mBlock to interact with Arduino using Bluetooth.
  - Please note that Bluetooth cannot be used to upload
    the sketches to Arduino for offline mode.

Connecting Bluetooth COM device to PC in AT mode to set baud rate.
==================================================================
- Upload empty (default) sketch to Arduino using USB cable.
- Connect 5V of BT shield to 3.3V of Arduino.
- Connect EN or BT to 5V.
- Connect Tx to Tx and Rx to Rx.
- Use USB cable to power on Arduino.
- Before turning the power ON, keep pressing the EN
  button on BT shield. The LED should blink with almost
  a second delay. That is the indication that it is AT mode.
- Start Arduino IDE, and connect to the COM port of Arduino
  and NOT that of the BT.
- Start serial monitor.
- Set the baud to 38400 and terminate character settings to
  "Both NL $ CR".
- In the command input field of Serial Monitor type `at` twice. First time response will be error, second time it should be ok.
- Now use the at commands to set baud rate using "at +uart=115200,0,0" e.g.
- Use "at +uart?" to see what is the baud rate set on the device.

Connect Bluetooth device to Rx and Tx of Arduino.
==================================================
   Arduino  <-> HC-05
   =======      =======
   5V            Vcc
   GND           GND
   Rx            Tx
   Tx            Rx (Via Voltage divider)

Some of the articles talk about connecting 3.3V of Arduino to the
Vcc of HC-05 and not using the voltage divider at all. However this
combination fails as once increases the baud rate.

Check out more details about voltage divider here. https://electronics.stackexchange.com/questions/280500/why-do-you-have-to-use-a-voltage-divider-with-hc-05-bluetooth-module-arduino

What is the story of two COM devices for Bluetooth?
===================================================
- https://electronics.stackexchange.com/questions/13741/bluetooth-module


message:
Arduino USB and 9V

I'm working on a project for interfacing the Arduino with the Raspberry Pi. I need to be able to exchange serial data between the two using the USB port.

My question is, can I do that while having the Arduino powered, by using a 9 V battery connected to the DC pin and at the same time have serial data connection using the USB port?

body:
Yes, you can. Arduino can be connected to multiple power sources at the same time.

From this excelent page about [Arduino power][1], I cite:

>Arduino is provided with a comparison circuit that controls a type P MOSFET; if a tension is found on Vin (powering from the JACK or from the Vin socket), the MOSFET is interdicted and the possible presence of voltage coming from the USB port is ignored; in the opposite case, the MOSFET will connect the USB port’s 5 V to the 5 V socket, hence below the regulator, thus powering Arduino.

>Therefore it is clear that if you apply the voltage to the USB port and an external source to the JACK socket at the same time, it will be this last one to power the circuit, while the USB connection will keep working for the data exchange with the computer and no longer as a power source. We remind that in both cases the 5 V socket cannot be used as input, but only as output.

  [1]: http://www.open-electronics.org/the-power-of-arduino-this-unknown/


message:
Feasibility of project with 50 leds working independently

I don't have much knowledge in Arduino and I'm about to start a new project which I believe can be done with it.

There will be 50 boxes with a led in top of each one. The user will type a number in a keyboard (1 to 5 for example), and then based on a table, the leds according to that number should light up.

It will have some overlaps, for example, Number 1 would light led 1, 2 and 3, while Number 2 would light leds 1, 2, 3 and 4.

Could I build such a project with arduino? Or are there too many inputs/outputs (keyboard, 50 leds)? I was thinking to buy an Arduino Uno to start learning, but first I'd like to know if it's feasible.

Thanks already

body:
depending on how you want to control your LED's there are several options.
firstly to be clear you could not feasibly connect that many LEDs to an arduino that could all be turned on at once (if that was needed) without damaging the arduino.

if all you need is on/off level of control then you could look at [shift registers][1] or if you have pre built arrays of LEDS in a grid type layout you could look at the [MAX7219/MAX7221][2]

if you also wanted to be able to control the brightness individually then you could look at the [TLC5940][3]

if we look at the pros and cons of each approach:
# 74HC595
pros:

 - cheap to buy
 - simple to use

cons:

 - each LED needs its own resistor
 - cannot vary brightness
 - if not using the hardware SPI pins can be slow for large numbers of outputs

# MAX7219/MAX7221
pros:

 - lower current draw than 74HC595
 - only needs one resistor per IC which can drive 64 LEDs

cons:

 - actually flashes LED's really fast to look like they are always on
 - costs more than 74HC595

# TLC5940
pros:

 - can vary brightness with a high number of steps (4096 steps from fully off to fully on)

cons:

 - uses more output pins than either of the above methods
 - requires resistor per LED
 - costs more for the IC than 74HC595

so to sum up, each method has its merits. if you are driving individual LEDs the the 74HC595 is probably the best/simplest route, if you are driving an array then the MAX7219/MAX7221 is best, and if you need variable brightness then the TLC5940 is probably best.

  [1]: https://www.arduino.cc/en/Tutorial/ShiftOut
  [2]: https://playground.arduino.cc/Main/MAX72XXHardware
  [3]: https://playground.arduino.cc/Learning/TLC5940


message:
Is it possible to make normal pins act like ground pins?

So what exactly I am trying to do is control a motor and be able to turn it both ways without any extra parts.

So if the hmp was on (the plus pole) and the hmm (the minus pole) acted like ground the motor should start turning right.

But if the hmp acted in this case as ground and the hmm like the plus pole it should start turning the other way.

I know that it's probably not going to work. I'm just experimenting.

    int Hmp=12; // the plus pole
    int Hmm=11; // the minus pole

    while (HR=0 || Sr > Sl+300) {
      pinMode(Hmp, OUTPUT);
      digitalWrite(Hmp, HIGH);
      pinMode(Hmm, INPUT);
    }

    while (HR=1 || Sl > Sr+300) {
      pinMode(Hmp, INPUT);
      pinMode(Hmm, OUTPUT);
      digitalWrite(Hmm, HIGH);
    }

body:
No, it's not going to work - even worse, you risk frying your Arduino -, for the following reasons:

 1. The Arduino data pins can't source (neither sink) enough current for that to work.

 2. The inductive kickback of the motor could fry Arduino pins.

The right way to do what you want to do is **using an H-bridge controlled by your Arduino data pins**. There are lots of Motor Driver PCB modules for Arduino (most of them based on the inefficient L298 driver IC, which you should ignore and look instead on those based on the TB6612FNG driver IC or similar, because it would be a far better solution) that implement this function.


body:
You have to put both pin in OUTPUT mode. You digitalWrite() the "positive" pin HIGH and the "negative" pin LOW.

But, it's not a good idea in this case:

1. Motor's power requirement exceeds digital output pin current of 40 mA.
2. Back EMF. Every time you stop the motor, there is a brief current pulse back to your pins. Bad.

The proper ways to control a motor is this:

[![Arduino controlled motor][1]][1]

This will control only one direction. For changing directions, you need a H-Bridge. An H bridge is an electronic circuit that can drive the motor in both directions.

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


body:
> is it possible to make normal pins act like ground pins?

the answer is yes: i'm looking right now at a blinking led that straddles between two GPIOs with one of them permanently (via code) grounded so i can blink it via the other GPIO pin.

Obviously the usual limitations that apply to a GPIO pin apply here.


body:
I don't think that's going to work.

You'll be better off using a cheap module like the Pololu [Pololu DRV8838][1] which implements a MOSFET H-bridge.

(Note: I'm not related in any way with Pololu.)

  [1]: https://www.pololu.com/product/2990


body:
I just tried what you suggest, and it works fine, with only one (big)
caveat: you can only power this way very low power motors. I did this to
drive the linear motor that moves an HDD head assembly. This motor works
perfectly fine with less than 18 mA.

Note that I switch the Arduino pins between the `HIGH` and `LOW` states,
not going through `INPUT`. Setting the pin to `INPUT` would send the
motor's inductive kickback through the pin's protection diodes. On the
other hand, the inductance of this motor is presumably tiny...

For anything that can draw more than 40 mA, I would use an
H-bridge. For something between 20 and 40 mA, I may take the
risk of driving it directly _if_ it's for an experiment where I am not
too much concerned about the risk of loosing my Arduino.


message:
Arduino PC to RS232 not reading data

I am trying to read data from [RS232 Shield][1] with an Arduino Mega.

This is the [schematic pin][2], TX is 3 and RX is 2.

Wiring:
PC > USB-RS232 cable > Arduino RS232 Shield.
Software to send/receive data:
[Hercules Setup Utility][3]

From Arduino, I can transmit data to RS232, the TX led blink and I got the value at PC.
From PC, I send the data, the RX led blink but nothing is showed in Arduino Monitor.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

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

      Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.println("Hello, world?");
    }

    void loop() { // run over and over
      if (mySerial.available()) {
        Serial.write(mySerial.read());
      }
      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
    }

I also tried to move RX and TX to Pin 15 and 14 but worked as the same as before.

  [1]: https://www.embarcados.com.br/arduino-rs-232-rs-485-hardware/
  [2]: https://www.embarcados.com.br/wp-content/uploads/2015/02/pinos-conectores-headers.png
  [3]: http://www.hw-group.com/products/hercules/index_en.html

body:
Found the problem, cant use PIN 2 as RX.

> Note: Not all pins on the Mega and Mega 2560 support change
> interrupts, so only the following can be used for RX: 10, 11, 12, 13,
> 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69


message:
Detect where pressure is being applied by using force resistors

I have 3 force resistors in a row, on top of which I have placed a board. I read values from the resistors through analogue ports. My goal is to be able to detect whether someone is pressing on the top, middle, or bottom of the board.

So far I can easily detect the left and right, like this: I first calibrate the 3 sensors for 2 seconds. Then I detect if pressure is applied on any of the calibrated sensors. If yes, I sum for all of them the values that they return on each round of the loop, until force has stopped being applied. I finally compare the 3 values against each other and I find which received higher pressure in total. This works perfectly fine for the left and right. However, when the board is pressed in the middle, pressure is applied on all 3, since the board is flat. Sorting the values does not help, because very often the left and right sensors have recorded a higher value than the middle.

I noticed that when the board is pressed on the left, the right sensor records very few values, and the same for the other way around. So, I get a high success rate in detecting middle presses like this:

    int threshold = 80;
    if (left_sum > threshold && middle_sum > 80 && right_sum >80)
        return middle_pressed;

However, when someone presses hard enough on the left or right, the if statement is satisfied.

Is there a more accurate way to detect where force is being applied?

*(Following is a quick schematic I made - I am not at all an expert so please excuse me for my mistakes, I just hope it illustrates more or less what it is supposed to)*

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/n1jev.png)

<!-- End schematic -->

Please ignore the double arrows right on top of the resistors.

body:
Let's assume that you have only two FSR sensors. With those you can make three virtual buttons (above the left sensor, above the right sensor and in the middle).

To measure someone's weight, it is allowed to have a scale under each foot and add both weights. We can use that to calculate the total force pressing to the board, by just adding the two forces.

The FSR sensors have a curve to calculate the force in newtons. It is very inaccurate, but works more or less. That can be added later. For now let's assume that it is linear to the ADC value of the Arduino.

Are the FSR sensors connected to an analog input and GND ? Do you have a resistor between the analog input and 5V ? I assume you do. You need the resistors so that a nice pressing force to the board results somewhere in the middle of the ADC range.

Pseudo code:

    setup()

      Measure both ADC values (or a number of values and use the average)
      Store them as offsets in a global variable.

    loop()

      Measure both ADC values, substract the offset.

      Translate the ADC values into force.
      The more force the higher the number should get.
      Any range is okay for now.
      They can be translated into Newton later.

      The total force is by adding the two forces.

      The position in percentage is the force of the right sensor
      divided by total force times 100.
      Then the position will be 0 for left sensor, 50 for middle
      and 100 for right sensor.

      If the total force is above threshold, then check the position.

      for example position -50 to 20 for left virtual button.
      for example position 30 to 70 for middle virtual button.
      for example positition 80 to 150 for right virtual button.

You can start by printing the forces to the serial monitor. Press the board and check if the numbers increase when pressing more.

Don't get confused when you print the position. It will be very noisy when no force to the board is applied. It should be valid when the total force is above the threshold.

For the position I allow a large error of 50 percent left of the left sensor and right of the right sensor. It depends on the mechanical construction and the rest of the code if that makes sense.

Print the results to the serial monitor.
If that is working well, then you have to detect a single press.

Let's assume that as soon as the threshold is reached, a press to a virtual button is accepted. Let's not wait until the peak of the force is reached.
The [State Change Detection][1] example can be used to create a single event for pressing the virtual button.

Any jitter or noise (for example a single press to the board results into two events for the virtual button) can be solved by averaging or filtering in software. I think that it will be needed.

I'm not sure if all of this is okay. I hope that someone else will look into it as well.

  [1]: https://www.arduino.cc/en/Tutorial/StateChangeDetection


body:
> Is there a more accurate way to detect where force is being applied?

normalize your measurements vs. the static values of those strain gauge readings obtained during calibration.


message:
What is the relationship of an Arduino .ino file to main.cpp?

Is the `.ino` file an alternative from a `main.cpp` file?

If yes, then could someone mind explaining the structure of the `.ino` file in `main.cpp` and its relationship?

body:
The Arduino uses the gcc compiler. That compiler wants a normal `main` function of course. Arduino has put a layer on top of that with `setup` and `loop`.

The hidden `main` function for basic Arduino boards is in [main.cpp][1] (click on it to see it).
You see that `init` is called, and `setup` and `loop` and a few other things.

To learn how to use `setup` and `loop`, you can try a few examples. They are in the menu of the Arduino IDE and they are also online.

The .ino files are all combined together and presented to the compiler as a single .cpp file to compile. The Arduino libraries are compiled from source as well, and everything is linked into a binary.

When you know how to use `setup` and `loop`, try the [Blink Without Delay example][2]. It can be used to run different software timers and do all kind of tasks and keep everything running smooth.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp
  [2]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


message:
Communicate between NodeMCU ESP8266 gateway and multiple sensor nodes

What is the best **wired** way to communicate between multiple **NodeMCU ESP8266** boards for home automation.

Every room should get at least a light, temp, PIR and xx relay modules to switch things on and off.

To connect all these sensors the GPIOs from one NodeMCU are sometimes not enough.

To reach this goal I planned to install in every room one NodeMCU as gateway and multiple NodeMCU as nodes for my sensors. The gateway will receive and forward information from/to my **openHAB** center via **MQTT** messaging.

I thought to use an **RS-485** 2-Wire connection between my sensor nodes and the room gateway. The gateway from my room will be connected via wifi or wired cable to my network.

I2C seems more to be for communication directly on PCBs or only short wiring.

Do you have any suggestions for me, is my plan possible? Any better ideas?

body:
If you really wanted wired communication then yes, RS-485 is the way to go.

In any installation where you will be running cables in the vicinity of mains wiring you will have noise. I2C is very bad with noise and not a good choice for any off-board wiring. RS-485, however, owing to the balanced line nature of the signalling, is designed to reject common mode noise such as is induced by mains wiring.

I would ask, though, *why use ESP8266 as remote wired nodes?* It seems a real waste to use a WiFi module for wired communication - a smaller, simpler, lower powered board (Arduino Micro / Mini maybe [3.3V, 8MHz version for simplicity of interfacing]) would be far more suitable for such a role.


message:
Stepper motor not working in Arduino 101

I am trying to connect a stepper motor ( this model exactly https://create.arduino.cc/projecthub/trduunze/grove-starter-kit-for-arduino-stepper-motor-driver-66471d ) in an arduino 101 but it does not work for some reason. I have tried connecting everything ast they tell in the website with no results:

[![Pinout from motor controller to arduino 101 grove shield][1]][1]

And then I tried connecting directly to the board without using the shield, and still getting nothing.

The code I am using is this :

    #include <Stepper.h>
    int t =0;
    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution for your motor
    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    int stepCount = 0;  // number of steps the motor has taken

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

    void loop() {
      // set the motor speed:
      int motorSpeed = 15;
      if (motorSpeed > 0) {
        myStepper.setSpeed(motorSpeed);
        // step 1/100 of a revolution:
        myStepper.step(stepsPerRevolution / 25);
      Serial.println(motorSpeed);//print how fast the motor is going in the serial monitor
      }
    }

Connecting the stepper motor and the driver, and launching the sketch in an arduino UNO board **works perfectly**, so I am really worried about that maybe the Stepper.h library might be different for the Arduino 101 but I couldn't find anything about that. I just have no idea why the project is not working in the 101 but working perfectly in the UNO. Any help or tips would be highly appreciated.

Cheers!

***EDIT***

After a lot of messing around, I have only been able to light up one led in the controller connecting one of the motor cables to GPIO5. None of the other GPIOS seem to work with the step motor controller.

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

body:
After reading the Stepper library and searching for several, I saw that in an example using an EDISON ( [I want to thanks to Guimficus for posting his code here: ][1]https://communities.intel.com/thread/99133) they changed the pinMode of the GPIOS they were using in the setup function :

    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);

And after adding that seems to work like it is supposed to work.

Cheers!

  [1]: https://communities.intel.com/thread/99133 "merci mon ami"


message:
Running a 7 pin OLED with 4 pins (I2C)

I have an OLED with this 7 pin pinout:

[![My OLED][1]][1]

I want to use an existing code i found that makes use of U8Glib.
But in the example, use uses 4 pins to control the OLED via I2C.
This is the pinout he uses:

[![Pinout][2]][2]

Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

EDIT: Here is also a picture of the back of the OLED PCB that mentions how to use IIC but i do not understand it!
[![back of pcb][3]][3]

  [1]: https://i.stack.imgur.com/b2Uwo.jpg
  [2]: https://i.stack.imgur.com/p9ZW2.png
  [3]: https://i.stack.imgur.com/AVgmd.jpg

body:
That is a SPI interface. Often the CS is missing, but you seem to have that pin. I suggest to start with the software PCI mode of the U8Glib.

This is the best explanation that I can find: [Github: SSD1306 based OLED connected to Arduino][1]

Would you consider using the newer [U8g2 library][2] ?
It is easier to use with Arduino boards that have more memory. But it has also the same mode for low memory usage, just like the U8Glib.

  [1]: https://github.com/jandelgado/arduino/wiki/SSD1306-based-OLED-connected-to-Arduino
  [2]: https://github.com/olikraus/u8g2


body:
> Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

i'm sure somewhere there is an i2c->spi bridge. if not, you can always code your arduino to behave like one.

short of that, you can simply code to control the board via spi.


body:
[This page][1] has the answer to your questions. For reference:

> Setting up SPI/I2C Connection with GMS096A OLED Module
>
> Being a new entry to the market, only limited resources are available
> on this small piece of miracle (GMS096A). I2C/SPI configuration always
> demands helpful resources as in any case. For the SPI setup, the
> module comes in 4 wire SPI configuration by default and to make it
> work with the arduinos you can use these libraries from Adafruit.
>
> For the I2C setup it demands a little bit of work on the module.
> Actually it was one of our customers who shared these simple
> configuration steps with us, start with resoldering the resistor from
> position R3 to R1 and then short the R8 resistor with some solder tin
> (0 Ohm resistor). The R6 and R7 pullup resistors are already soldered,
> nothing to do there. Once done, the module is ready for I2C
> communication! The CS Pin is not necessarily needed, so just connect
> it to GND. The DC Pin selects the address. For standard address wire
> it to GND. The RES-pin needs a low pulse at startup and high voltage
> during operation (as in SPI mode), a 100nF capacitor to GND and a 10k
> res to VCC would be ideal!

Your module might differ sightly. But you should be able to figure it out from there. The pulse on the RES-pin needed at startup took me a while to figure out!

  [1]: http://www.rhydolabz.com/displays-c-88/096-oled-display-module-spii2c-128x64-7-pin-blue-p-2079.html


body:
Yes, it works IIC as described above, with my Arduino MEGA.
You can also connect RST Pin at Arduino RESET signal, so no need of extra R and C components


message:
Hiding WLAN password when pushing to GitHub

I have started to use GitHub to store Arduino code. However some of my code uses the SSID and password for my WLAN which I don’t want published.

A common way of handling this in non-embedded programming is to use a configuration file, but that doesn’t seem to be a viable approach in programming the Arduino. I’m currently just commenting out the sensitive information before pushing it to GitHub, but one day I’m sure I’ll forget.

Is there another – better - way of handling this?

body:
Sure you can use a config file. It's called a "header" file, and you just `#include` it in your sketch.

    [config.h (not pushed)]

    const char *password = "DOD982yp398fhgpwbn09tupf0p04";

    [sketch.ino (pushed)]

    #include "config.h"

    // Now you can use the password variable.

Another method, which is better if you have multiple files in your sketch, is to use `#define` instead of variables in your header file:

    [config.h]

    #define WIFI_PASSWORD "348r0yp80ytwp85tpj8yjp98y97t8t"

    [sketch.ino]

    #include "config.h"

    const char *password = WIFI_PASSWORD;


body:
You could commit the following file into your project, named
credentials.h:

    // Replace with your actual SSID and password:

    #define WIFI_SSID "Your SSID here"
    #define WIFI_PASSWD "WLAN AP password here"

Near the beginning of your sketch, you add:

    #include "credentials.h"

    const char ssid[] = WIFI_SSID;
    const char password[] = WIFI_PASSWD;

Now, you can edit credentials.h to add your real SSID and password, and
go on with your normal git workflow, with one exception: never
`git add credentials.h` again, nor `git commit -a`.

Now, git will always remind you that credentials.h has been modified and
is not staged for commit. It will do so even if you add the file to your
.gitignore. If you always review your changes before committing, this is
only a minor inconvenience. If, on the other hand, you tend to
`git commit -a` without reviewing what you are committing, then this
solution is likely not for you.

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

**Edit**: An idea I got from reading Chris Stratton's comments. **If**
you use a Makefile in your own workflow (this has already been discussed
in this site a few times), you could commit this credentials.h to your
repo:

    #ifndef CREDENTIALS_H
    #define CREDENTIALS_H

    // Replace with your actual SSID and password:
    #define WIFI_SSID "Your SSID here"
    #define WIFI_PASSWD "WLAN AP password here"

    #endif

Make a copy of this file named true-credentials.h and put the real
credentials there (but do not rename the include guard). Then add to
your Makefile

<!-- language: lang-none -->

    CFLAGS += -include true-credentials.h

Keep true-credentials.h and the Makefile out of the repo. You can add
them to your .gitignore or, better yet, to .git/info/exclude.

Now you have a compilable version with dummy credentials in the
repository, you have the true credentials when you compile on your own
machine, and git does not bother you about credentials.h being changed.


body:
Building upon the shoulders of giants I took Edger Bonet's answer and used a slightly different twist.  I went this route because I don't use a makefile and found this solution works well for me in my project.

I created a placeholder credentials.h file with the following info (Edger's answer).

    #ifndef CREDENTIALS_H
    #define CREDENTIALS_H

    // Replace with your actual SSID and password:
    #define WIFI_SSID "Your SSID here"
    #define WIFI_PASSWD "WLAN AP password here"

    #endif

I further added the reference to this new file in the .ino file.

    #include "credentials.h"

    const char ssid[] = WIFI_SSID;
    const char pass[] = WIFI_PASSWD;

Now the twist.. I excluded the file from being checked for changes using the --assume-unchanged command.

> git update-index --assume-unchanged credentials.h

You can then modify the credentials.h file and wont be prompted to add it to github.

Note, to re-check the file use --no-assume-unchanged.


message:
Encode & decode boolean values into a single integer?

I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:

    Pin 1: TRUE
    Pin 2: FALSE
    Pin 3: FALSE
    Pin 4: TRUE

    Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
    1 + 0 + 0 + 8
    Result: 9

This is pretty efficient.
But how do I decode the pin states from this best?
Or do you recommend a better way to do this?

body:
You are almost there with that. Personally I'd use OR not +:

This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the *bit number* in there. The `<<` is *left shift*.

    #define PIN0 (1 << 0)
    #define PIN1 (1 << 1)
    #define PIN2 (1 << 2)
    #define PIN3 (1 << 4)

Now you can combine:

    uint8_t val = PIN0 | PIN3; // 9

And you can check if one is set:

    if (val & PIN3) {
        // ....
    }

To loop through the pins you can use the `<<` again:

    for (uint8_t pin = 0; pin < 8; pin++) {
        if (val & (1 << pin)) {
            // ....
        }
    }

etc.


body:
use the AND operator.

for example:

pin 2's state would be (result & 0x02)?TRUE:FLASE


message:
How to programmatically choose "board model" and "port number" in Arduino IDE?

I'm testing three different Arduino (nano, Uno and Mega) each of them having a nRF module. The codes (sketches) are different for each module.
I've connected the arduinos to my single laptop via 3 USB ports.

Problem is, whenever I want to re-upload a sketch and fix a bug, I have to choose board model and port number of that sketch by using the menus. It has become frustrating using mouse each time I need to change something.
How can I set these parameters in code so each sketch knows which port and model it is related to?

body:
You can't in the Arduino IDE, it's not designed that way (you can't even have different board/port settings in different windows - it's stored in the Java equivalent of a single global).

Instead you will have to switch to a different programming environment.

Personally (since I am the author) I would suggest switching to [UECIDE](http://uecide.org). That has far more advanced facilities than the Arduino IDE, yet still retains most of the simplicity of use.

In UECIDE you can not only have different ports and boards selected in different windows, you can also configure individual sketches to automatically select their board and port.

* **Sketch -> Sketch Properties... -> Objects tab**

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

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


body:
Take a look at the (similar) question and answer in https://arduino.stackexchange.com/a/9182/22924

It talks about multiple UNOs, but the solution should help here.


message:
Send AT commands programatically to ESP8266 without Arduino

Let me explain my question in more details. I want to use ESP8266-01 as standalone micro-controller for my project. I don't want to use Arduino or any other board with that.
Using Arduino i can use two of the pins as software serial and can send different AT commands to ESP module to ESP's Tx and Rx pins, but now what I want is to eliminate the need to Arduino.

What I want to do is to to program ESP itself to toggle mode from AP mode to Host mode on press of a push button. for that I has to send AT commands to ESP from the code while i will write to the ESP itself. Is there any way to achieve the same.

I tried searching a lot but what I found everywhere is how to send AT commands from Arduino.

Thanks in advance.

body:
You don't use AT commands. You install the esp8266 boards package and program the esp8266 as if it were an Arduino. That means learning the esp8266 WiFi API which has plenty of examples included.

* https://github.com/esp8266/Arduino/


message:
If (serial.available()) conditional statement

I am very new to Arduino and I have a question I would like to clarify on Serial.Available()

According to Arduino documentation, Available() returns the number of bytes that are stored in the buffer, ready to be read. Why then, both If function below works, when there are data in the buffer? For Scenario A, it appears to me that there is no conditional statement, how then, would the IF function evaluates to TRUE?

Scenario A: IF(Serial.Available())

compare with

Scenario B: IF(Serial.Available()>0)

Thanks in advance!

body: In C, 0 is false and anything else is true. So if Serial.available() returns 0 it is considered false. If it returns 7, 23, 44, etc it is considered true.


message:
How can the sensitivity of capacitive touch sensors be limited?

I have an [Adafruit circuit playground classic][1], and the touch-pads are so very sensitive. From a centimeter away, they trigger.  I would be happy to just have regular inputs, or to have the sensitivity reduced. How can I do this?

To clarify, here is my code:

    //keyboard control for TuxKart power Glove
    #include <Adafruit_CircuitPlayground.h>
    #include <Keyboard.h>
    #include <Mouse.h>
    // set pin numbers for the five buttons:
    const int Fire = 6;
    const int Nitro = 9;
    const int Eagle = 10;
    const int _Esc = 12;

    bool slideSwitch;

    void setup() { // initialize the buttons' inputs:
      pinMode(Fire, INPUT_PULLUP);
      pinMode(Nitro, INPUT_PULLUP);
      pinMode(Eagle, INPUT_PULLUP);
      pinMode(_Esc, INPUT_PULLUP);

      Serial.begin(9600);
      // initialize mouse control:
      //Mouse.begin();
      Keyboard.begin();
    }

    void loop() {
      if (!CircuitPlayground.slideSwitch()) {
        return;
      }

      // use the pushbuttons to control the keyboard:
      if (!digitalRead(Fire) == HIGH) {
        Keyboard.write('KEY_SPACE');
        Serial.println("F");
      }
      if (!digitalRead(Nitro) == HIGH) {
        Keyboard.write('n');
        Serial.println("U");
      }
      if (!digitalRead(Eagle) == HIGH) {
        Keyboard.write(0xB2);
        Serial.println("N");
      }
      if (!digitalRead(_Esc) == HIGH) {
        Keyboard.write(0xB1);
        Serial.println("K");
      }
    delay(200);
    }

This code or any other, where capacitive touch sensitivity has not been specified, yields pins having extreme sensitivity. I have read the comments, that say the MCU doesn't feature this natively. If that were true, how would the pins remain sensitive?

My solution to this is to set sensitivity so low, that it is negligible. If capacitive touch sensing is not specified, why am I getting that functionality? Why would this code give me capacitive touch sensing?
Ideally, I would disable the touch sensing somehow, or have the pins simply behave normally, like any other Arduino based device that doesn't have touch sense. But what I have guessed, (shown in code) doesn't work. If there is a more explicit way to specify that IO pins should act as normal pins, without capacitive touch sensing, I would surely like to know.

  [1]: https://www.adafruit.com/product/3000

body:
Its not the best method for finding a solution, perhaps, but I was tooling around in the Adafruit_CircuitPalyground repo, and found a macro for the Capacitive touch sensitivity.

The macro is:

    #define CAP_THRESHOLD 300 // Threshold for a capacitive touch (higher = less sensitive).

Located here:
https://github.com/adafruit/Adafruit_CircuitPlayground/search?utf8=✓&q=CAP_THRESHOLD&type=

I'm reading more, and trying to find the libraries for capacitive touch. There may be a much better solution, but for now defining CAP_THRESHOLD works well enough.


body:
`digitalRead(pin)` is the wrong way to read capacitive touch inputs.

In the [file from the example][1] you linked in [your answer][2], the reading is made by calling `CircuitPlayground.readCap(pin, num_samples)` and then the returning value is compared to a threshold.

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

    const uint16_t TOUCH_THRESHOLD = 300;

    ...

    if (CircuitPlayground.readCap(Fire) >= TOUCH_THRESHOLD) {
       Keyboard.write(KEY_SPACE);
       Serial.println('F');
    }
    ...

You can change the sensitivity by changing `TOUCH_THRESHOLD`. You could also add and fiddle with the second argument to change the number of samples.

  [1]: https://github.com/adafruit/Adafruit_CircuitPlayground/blob/e871c0b23ff6731489045142464f233853ac43cd/examples/mega_demo/CapTouchDemo.h
  [2]: https://arduino.stackexchange.com/a/41446


message:
How to use Atmega1284AU with Arduino IDE

Is there any support to this chip in Arduino IDE, like bootloaders and boards definitions.. i want to use this chip with 3.3V and 8Mhz crystal speed..

I have seen Nick Gammon bootloaders supports this chip for bootloaders, but not with 8Mhz.? and how to add this chip to Arduino IDE.

anybody help..

thanks you

body:
Please check out MightyCore library by MCUdude.

https://github.com/MCUdude/MightyCore

I have used it and can verify it works pretty well with ATmega1284.


message:
I can't upload sketches to my Arduino 101

When connected to USB green Power LED on but doesn't upload sketch(that says press master reset therefore i've pressed several time but timeout). And main thing is device doesn't show in device manager.(I'm working on windows10).

 - Have I "bricked" it?
 - What steps can I take to work out what is wrong?
 - What can I do to fix it?

I've search in many sites but doesn't give me detail about hardware repairing guide for arduino 101.

I've checked working usb cable and another laptop but not work.I think **hardware problem**.Once arduino getting hot near usb.

body:
It's hard to tell, but you can try a lot of options:

- Use another USB port
- Use another USB cable
- Reinstall the Arduino IDE
- Remove the device in the device manager and try reinstalling the Arduino IDE again
- Try another Arduino (to see if the USB/install is ok)
- Try on a different computer/laptop


body: If you checked all of the above as *Michel Keijzers* mentioned then it might be a hardware problem. Actually, your usb cable might not fitting correctly to the usb port.


message:
Problem with reading series of bytes over serial port

I'm writing a program to read bytes from serial channel, copy those into an array and then do some verification on those copied numbers.

I'm able to read and copy bytes into an array of bytes.
However, I'm facing an issue with the verification of those bytes.

Here's the code I've written:

    #include <SoftwareSerial.h>

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

    void loop()
    {
        char charRead = 0x00u;
        byte byteArray[10];
        int i=0 , j=0;

        //Clear the array contents
        for(j = 0; j < 10u; j++)
        {
           byteArray[j] = 0x00u;
        }

        //Wait for data on serial channel
        while(Serial.available() > 0)
        {
           //Copy bytes received into array
           charRead      = Serial.read();
           byteArray[i] = (byte)charRead;
           i++;
        }

        //Just for the sake, print the array contents
        for(j = 0; j < i; j++)
        {
           Serial.print(byteArray[j],HEX);
        }

        //Check for first two bytes
        if( (byteArray[0] == 0x31) && (byteArray[1] == 0x32) )
        {
            Serial.println("Verified.");
        }
    }

To test this program, I entered "12345" (without quotes) on the serial monitor which gave me an output as "3132333435" since I'm printing the contents of the array in HEX format.

What I'm not being able to understand is even if this output shows that the first two bytes in the array are 0x31 & 0x32 respectively, why not the verification logic of those two bytes is getting executed? If it would, then the string 'Verified' would get printed on the output.

Am I doing something wrong here with Serial.read() or some typecasting?

I'm running this on an Arduino Uno

body:
So, as result of Edgar Bonet's good remark, change

    int i=0 , j=0;

to

    int j = 0;

and define

    int i = 0;

Outside the loop (as a global variable).

Also it is quite dangerous to define the length of the array as 10, while not checking for writing over the boundary of the array. What if you receive more bytes? The application might crash or give unpredictable behavior.


message:
DigitalWrite Cannot Power HC-06 Bluetooth

To save power consumption, I tried to connect the HC-06 bluetooth module to a digital pin of my Arduino Nano. (HC-06 +5V <=> pin 11, HC-06 gnd <=> gnd) In that way, I can toggle the bluetooth when I am not using it. However, when I tried to pinMode(11, OUTPUT) and digitalWrite(11, HIGH), the led on HC-06 does not turn on which means it is not powered. I have tried to connect the HC-06 +5V to the 5V output of arduino and the HC-06 can turn on sucessfully. I have also tried to use a multimeter and the digital pin outputs a voltage of 5V. As the digital pins of Arduino can give 40mA while the HC-06 draws 30mA - 40mA, it should have enough power. I have also tried to use other digital pins as well but still the HC-06 cannot be powered.
What have I done wrong?

body:
A digital IO pin is only capable of powering an LED or an incredibly low powered device. It is **not** suitable for powering meaty RF modules.

Instead you need to control the power to your module using a P-channel MOSFET as a High-Side switch.

For instance, assuming a 5V module with built in 3.3V LDO:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/YSY9f.png)

<!-- End schematic -->

Note that `/RFEN` is active low - set the pin OUTPUT and LOW to turn the module on. M1 should have a threshold of no lower than -4V, better -2V or higher.

Also be sure to set RX and TX to be INPUT when you power down the module or back-powering through the TX/RX pins may occur.

R2/R3 is a simple logic level shifter for the 3.3V logic signal the RX pin expects.


message:
Send signal to vibrate a Restaurant buzzer via web based app to a PC

I'm new to Arduino, I want to create a restaurant buzzer using Arduino and it should turn on/off via web based interface. It will be locally connected only.

Is it possible to send a signal with the mac address of the master transmitter pc to vibrate the buzzer?

What are the materials should I need? Suggestions or any tips is greatly appreciated.

body:
You need a webserver, a defined interface for the client to connect to and a buzzer you can make some noise with.

Because you want to do it over WIFI, an Arduino is probably not the best choice.  As 'Look Alterno' says you might be better with an ESP8266 based device, because that has inbuilt WIFI.  I would suggest a Wemos D1, its an ESP8266 12 with a power supply and 2.54 pitch connectors, which means its easy to use with things.
[![enter image description here][1]][1]

Now you can program an ESP8266 using LUA, but I really wouldn't try that. Also if you do that you won't get any help on this forum.  Use the Arduino IDE and program it in the same language as an Arduino (You will need to download support for the ESP via the Board Manager in the IDE).  There is an example called "Advanced Web Server", done by Majenko on here, that will suit your needs.  You just need to change the root handler to activate the buzzer for n seconds and then return HTTP code 200.

Then your client just needs to connect to the root page of the webserver and the buzzer will sound.  You don't say how many clients will use this, but this will allow 5 simultaneous clients, if you need more that can be achieved easily.

You can then expand this to identify which client sounded the buzzer.

As to keeping it local, use the firewall on your router.

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


message:
Can't print on LCD

I'm a newbie here. And sorry for my bad English first of all.

Right now I'm working on VLC (Visible Light Communication). I have working code, in which output is displayed on the Serial Monitor. But now I want to print this output on an LCD.

I made necessary changes like including the LCD library and instead of `Serial.print` I used `lcd.print`. But nothing is displayed on the LCD.

Here is the modified code including LCD:

    static int TRESHOLD = 500;
    static unsigned int standardDelay = 13500000; //1350 is limit
    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 7,6,5,4);

    void setup() {
      Serial.begin(9600); // 9600 bits per second
      pinMode(3,OUTPUT); //digital PWM 3 on output
      int sensorValue = 0;
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // initialize the serial communications:
    }

    void loop() {
      WriteChar('h');
      WriteChar('e');
      WriteChar('l');
      WriteChar('l');
      WriteChar('o');
      WriteChar('w');
      WriteChar('o');
      WriteChar('r');
      WriteChar('l');
      WriteChar('d');
    }

    void WriteChar(char str){
      switch (str - '0'){
        case 49:
          //code for a is 011 0001
          LightFlash(false, true, true, false, false, false, true);
          break;
        case 50:
          //code for b is 011 0010
          LightFlash(false, true, true, false, false, true, false);
          break;
        case 51:
          //code for c is 011 0011
          LightFlash(false, true, true, false, false, true, true);
          break;
        case 52:
          //code for d is 011 0100
          LightFlash(false, true, true, false, true, false, false);
          break;
        case 53:
          //code for e is 011 0101
          LightFlash(false, true, true, false, true, false, true);
          break;
        case 54:
          //code for f is 011 0110
          LightFlash(false, true, true, false, true, true, false);
          break;
        case 55:
          //code for g is 011 0111
          LightFlash(false, true, true, false, true, true, true);
          break;
        case 56:
          //code for h is 011 1000
          LightFlash(false, true, true, true, false, false, false);
          break;
        case 57:
          //code for i is 011 1001
          LightFlash(false, true, true, true, false, false, true);
          break;
        case 58:
          //code for j is 011 1010
          LightFlash(false, true, true, true, false, true, false);
          break;
        case 59:
          //code for k is 011 1011
          LightFlash(false, true, true, true, false, true, true);
          break;
        case 60:
          //code for l is 011 1100
          LightFlash(false, true, true, true, true, false, false);
          break;
        case 61:
          //code for m is 011 1101
          LightFlash(false, true, true, true, true, false, true);
          break;
        case 62:
          //code for n is 011 1110
          LightFlash(false, true, true, true, true, true, false);
          break;
        case 63:
          //code for o is 011 1111
          LightFlash(false, true, true, true, true, true, true);
          break;
        case 64:
          //code for p is 100 0000
          LightFlash(true, false, false, false, false, false, false);
          break;
        case 65:
          //code for q is 100 0001
          LightFlash(true, false, false, false, false, false, true);
          break;
        case 66:
          //code for r is 100 0010
          LightFlash(true, false, false, false, false, true, false);
          break;
        case 67:
          //code for s is 100 0011
          LightFlash(true, false, false, false, false, true, true);
          break;
        case 68:
          //code for t is 100 0100
          LightFlash(true, false, false, false, true, false, false);
          break;
        case 69:
          //code for u is 100 0101
          LightFlash(true, false, false, false, true, false, true);
          break;
        case 70:
          //code for v is 100 0110
          LightFlash(true, false, false, false, true, true, false);
          break;
        case 71:
          //code for w is 100 0111
          LightFlash(true, false, false, false, true, true, true);
          break;
        case 72:
          //code for x is 100 1000
          LightFlash(true, false, false, true, false, false, false);
          break;
        case 73:
          //code for y is 100 1001
          LightFlash(true, false, false, true, false, false, true);
          break;
        case 74:
          //code for z is 100 1010
          LightFlash(true, false, false, true, false, true, false);
          break;
        default:
          lcd.print(str - '0');
          lcd.print("CAME IN DEFAULT IN WRITECHAR");
          break;
      }
    }

    void LightFlash(boolean a, boolean b, boolean c, boolean d, boolean e, boolean f, boolean g){

      digitalWrite(3,LOW);
      if (a == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue1 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (b == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue2 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (c == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue3 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (d == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue4 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (e == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue5 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (f == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue6 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);

      digitalWrite(3,LOW);
      if (g == true){
        digitalWrite(3,HIGH);
      }
      delayMicroseconds(standardDelay/2);
      boolean sensorValue7 = (analogRead(A0)>TRESHOLD);
      delayMicroseconds(standardDelay/2);
      delayMicroseconds(3*standardDelay); //1 second passed

      long result = 0;
      result = 1000000*sensorValue1 + 100000*sensorValue2 + 10000*sensorValue3
      + 1000*sensorValue4 + 100*sensorValue5 + 10*sensorValue6 + 1*sensorValue7;
      //lcd.print(result);
      PrintChar(result);
    }

    void PrintChar(long binary){

      switch (binary){

        case 110001:
          //code for a is 011 0001
          lcd.write("a");
          break;
        case 110010:
          //code for b is 011 0010
          lcd.print("b");
          break;
        case 110011:
          //code for c is 011 0011
          lcd.print("c");
          break;
        case 110100:
          //code for d is 011 0100
          lcd.print("d");
          break;
        case 110101:
          //code for e is 011 0101
          lcd.print("e");
          break;
        case 110110:
          //code for f is 011 0110
          lcd.print("f");
          break;
        case 110111:
          //code for g is 011 0111
          lcd.print("g");
          break;
        case 111000:
          //code for h is 011 1000
          lcd.print("h");
          break;
        case 111001:
          //code for i is 011 1001
          lcd.print("i");
          break;
        case 111010:
          //code for j is 011 1010
          lcd.print("j");
          break;
        case 111011:
          //code for k is 011 1011
          lcd.print("k");
          break;
        case 111100:
          //code for l is 011 1100
          lcd.print("l");
          break;
        case 111101:
          //code for m is 011 1101
          lcd.print("m");
          break;
        case 111110:
          //code for n is 011 1110
          lcd.print("n");
          break;
        case 111111:
          //code for o is 011 1111
          lcd.print("o");
          break;
        case 1000000:
          //code for p is 100 0000
          lcd.print("p");
          break;
        case 1000001:
          //code for q is 100 0001
          lcd.print("q");
          break;
        case 1000010:
          //code for r is 100 0010
          lcd.print("r");
          break;
        case 1000011:
          //code for s is 100 0011
          lcd.print("s");
          break;
        case 1000100:
          //code for t is 100 0100
          lcd.print("t");
          break;
        case 1000101:
          //code for u is 100 0101
          lcd.print("u");
          break;
        case 1000110:
          //code for v is 100 0110
          lcd.print("v");
          break;
        case 1000111:
          //code for w is 100 0111
          lcd.print("w");
          break;
        case 1001000:
          //code for x is 100 1000
          lcd.print("x");
          break;
        case 1001001:
          //code for y is 100 1001
          lcd.print("y");
          break;
        case 1001010:
          //code for z is 100 1010
          lcd.print("z");
          break;
        case 11000:
          lcd.print("dit gebeurt vaak");
          break;
        case 1011001:
          lcd.print("dit ook");
          break;
        case 100001:
          lcd.print("tenslotte dit nog");
          break;
        case 1011000:
          lcd.print("en dit is de laatste denk ik");
          break;
        default:
          lcd.print(binary);
          lcd.print("CAME IN DEFAULT ON PRINTCHAR");
          break;
      }
    }

I want to print this output on LCD. But I'm not able to do that. Please help me out.

Circuits:

(1) VLC Circuit

[![VLC Circuit][1]][1]

(2) LCD Circuit

[![LCD Circuit][2]][2]

I combined both circuits above and made a final circuit.

The VLC circuit is set up in which DATA is transmitted from SIMPLE LED and Capture on PHOTODIODE. And using LCD Circuit I want to display data on LCD.

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

body:
There is so many problems with your code. It can be so much short.

Take WriteChar. Why mess with binary value for chars? Use char directly, just here:

    void setup() {
      Serial.begin(9600);
      WriteChar('h');
      WriteChar('e');
    }

    void loop() {
    }

    void WriteChar(char c) {
      boolean b7 = c & B1000000;
      boolean b6 = c & B0100000;
      boolean b5 = c & B0010000;
      boolean b4 = c & B0001000;
      boolean b3 = c & B0000100;
      boolean b2 = c & B0000010;
      boolean b1 = c & B0000001;

      Serial.println(c);
      LightFlash(b7, b6, b5, b4, b3, b2, b1);

    }

    void LightFlash(boolean b7, boolean b6, boolean b5, boolean b4, boolean b3, boolean b2, boolean b1) {
      Serial.print(b7 ? "1" : "0");
      Serial.print(b6 ? "1" : "0");
      Serial.print(b5 ? "1" : "0");
      Serial.print(b4 ? "1" : "0");
      Serial.print(b3 ? "1" : "0");
      Serial.print(b2 ? "1" : "0");
      Serial.println(b1 ? "1" : "0");
    }

There is more simply ways to write that (using arrays and loops) but this is easier to understand. And better, pass the char directly to LightBlash.

Don't use a string when you just pass a char to a function.


body:
Finally, got the problem. My code is working fine. I have a problem with my LCD connection.

I write

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

Instead of

    LiquidCrystal lcd(12, 11, 4, 5, 6, 7);


message:
Differences between nodemcu and arduino processer

I have an arduino Uno and nodemcu development board.[![enter image description here][1]][1]

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

I have an OV7076 camera and used with arduino UNO. It worked flawlessly with it and the code used is provided in the [Instructables tutorial][2] named as FromComputerNerd.ino.

Now i want to use it with Nodemcu. Whereas Nodemcu have a single Analog input but OV7076 uses two analog inputs [shown in][2]. So to get it I am trying to use Multiplexer. I can change the code so that it would adjust for analog pins.

But will the code be compatible with Nodemcu. Since it was written for arduino uno.If not, What changes can be done to make it compatible?

http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/

body:
I am suggesting you to buy NodeMCU because it is having inbuilt WIFI, you can connect NodeMcu to internet without much effort compare to connecting UNO to internet, and the best thing is NodeMCU is arduino compatible you can do all possible stuff that can be done with UNO. We can also program NodeMCU in 'C' language using Arduino IDE directly

**Hardware comparison**

*NodeMCU*

1. 128KB RAM
2. 4MBytes ROM(flash)
3. micro USB port
4. Small Board Size

*Arduino UNO*

1. 2kB RAM
2. 32 KB ROM
3. USB type B connector
4. Bigger in size than NodeMCU

> Both are having nearly same prices.


body:
Camera doesn't send data via Analog to Arduino.
A5 and A4 are I2C bus beside Analog.

NodeMCU has Software I2C protocol bus too, You can use D1 (GPIO 5) as CLK, and D2 (GPIO 4) as SDA.

see : https://github.com/esp8266/Arduino/blob/master/doc/libraries.rst#i2c-wire-library


message:
Arduino Gesture Sensor error:No such file or directory

I cloned https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor
and copied the libraries into the Arduino `libraries` folder. I then launched Arduino and selected the example. I opened the file GestureTest and when I started upload I received this error:

>GestureTest.ino:49:31: fatal error: SparkFun_APDS9960.h: No such file or directory
>
>compilation terminated.

I checked the `SparkFun_APDS9960.h` and I found it in the `Gesture_Sensor/Libraries/src` folder.

Is there a solution to resolve this error?

body:
SparkFun made a poor choice for the folder structure of that repository. Likely this has caused you to incorrectly install the library. Please follow these instructions:

1. Download the latest release from https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/releases. Currently it is https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/archive/V_H1.0_L1.4.2.zip.
2. Unzip the downloaded file.
3. Rename the folder `APDS-9960_RGB_and_Gesture_Sensor-V_H1.0_L1.4.2/Libraries/Arduino` to `SparkFun_APDS9960`. This is not absolutely necessary but "Arduino" is not a very descriptive name for a library folder and the Arduino IDE works best when the library folder name matches the primary header file name so this is best practices.
4. Copy the `SparkFun_APDS9960` folder to `{sketchbook folder}/libraries`. You can find the location of the sketchbook folder at **File > Preferences > Sketchbook location**.
5. Restart the Arduino IDE if it's running (not necessary with recent versions of the Arduino IDE).

Note that the folder structure of this library requires Arduino 1.6.x or newer.

UPDATE: I submitted a pull request to put the library in an appropriately named folder. This won't change the instructions above until the next release but it does remove the need to rename the folder if you are cloning the repository or downloading from the tip of the repository rather than a release.


message:
Do all serial ports on an Arduino MEGA 2560 have the potential to "brick" attached items when being flashed?

I was browsing through the [hookup guide][1] for SparkFun's OBD-II UART breakout and found something particularly worrying written half way down in a quite casually presented way:

> Keep in mind when you upload this to your board, you will want to disconnect the OBD-II board RX line from the Arduino TX-0, to prevent issues during code upload, such as bricking the OBD-II board.

For my money I think bricking your device should come with a more stark warning than one stuffed part way down a guide starting with "keep in mind" and continuing with "issues". Nonetheless it caught my attention as I tend to build sealed boxes that aren't sprawled in front of a keyboard ready to be rewired any time a re-flash might happen.

Is the real risk here the fact that all of the flashed data would stream past the RX pin of the UART board and potentially accidentally send a 'self-destruct' signal? (Also I'm not sure a system is really up to scratch if you can accidentally tell it to kill itself.)

Surely the programming port is not the one being borrowed by the UART hookup? On a MEGA 2560, using a different serial port, is this still a risk or is that only on boards with one serial port?

  [1]: https://learn.sparkfun.com/tutorials/obd-ii-uart-hookup-guide

body:
In the Sparkfun example the Arduino Uno is used. The Uno has only one hardware serial port, and that is used to upload a sketch and for the serial monitor. Pin 0 (RX) and pin 1 (TX) can be overriden for something else. However, then you must know what you are doing, and connect and disconnect modules as required.

The Arduino Leonardo and (Pro) Micro use a USB CDC implementation and have a unused hardware serial port at pin 0 and 1.

The Arduino Mega 2560 uses the hardware serial port at pin 0 and 1 to upload a sketch, just as the Uno. However, the three other hardware serial ports are not used, and you are free to use them.

If you use an unused hardware serial port for the OBD-II, there is no risk at all. You can use that port and nothing else messes with that port.

If you use a serial port that is also used to upload a sketch, or a software implementation of a serial port, you probably are going to make a mistake some day, and there is a risk to send the wrong data to the wrong hardware.

[**ADDED**]
I see that the example code in the SparkfunHookup Guide uses the Arduino Uno and SoftwareSerial on pin 2 and 3. That is independent of the hardware serial port. The SoftwareSerial is something that should be used as a last resort, since it almost completely takes over the Arduino board. It's good to have SoftwareSerial, but try to avoid it.
If you do want to use an Arduino Uno, perhaps the [AltSoftSerial][1] can be used. The AltSoftSerial works okay for 9600 baud as long as no other code uses too much time in interrupts and no one else uses TIMER1.

  [1]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


message:
Wire library compatibility Arduino Pro Mini - nodeMCU (I2C/TWI) problem

I'm writing PortExtender, a library to convert an Arduino Pro Mini in a port expander and I ran into what seems to be a compatibility problem between Arduino and nodeMCU: I got different answers depending on who is the master (Arduino or nodeMCU).

This is my test configuration:

[![Test configuration][1]][1]

At the center, the Slave Arduino, with buttons, leds, and ldr for testing pin access.

I have two master, but only one is used at a time. The inactive one is powered off and disconected from the two others. The slave get its power from the master.

I compiled and ran the same Master program in the two master, while the slave remains the same. This is the Master test program:

    #include <Wire.h>
    #include <PortExtender.h>

    const int SLAVE_ADDRESS = 42;

    PortExtender port = PortExtender(SLAVE_ADDRESS);

    void setup ()
    {
      Serial.begin(9600);
      delay(1000);
      Serial.println("Master");
      Serial.println("-----");

      Wire.begin();
      int r;
      do {
        r = port.reset();
        Serial.print("Resetting Port Expander. Status=");Serial.println(r);
        delay(100);
      } while(r != SLAVE_ADDRESS);
    }

    void loop() {
    }

The test just sent a soft-reset to the slave. The slave answers with its own address (42), just to check that the command works.

**Master 1 execution**

This is the correct result from Master 1 (Arduino Pro Mini):

[![Master 1 response][2]][2]

In fact, I can run a complete test suit with no problems, testing the button, controlling the LED and reading the LDR.

**Master 2 execution**

This is the result from Master 2 (nodeMCU):

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

Response is some random value that change from run to run. Slave, however, receive the command and return the right response, as checked thru Serial Monitor connected to the slave.

Everything seems to work fine, but answer from slave looks like it changed "in the wire".

**PortExtender library code**

The relevant methods involved are:

    int PortExtender::reset() {
        return send(CMD_RESET);
    }

    int PortExtender::send(byte cmd) {
        Wire.beginTransmission(slave);
        Wire.write(cmd);
        Wire.endTransmission(false); // Also tested with true.
        return readAnswer();
    }

    int PortExtender::readAnswer() {
        short answer;

        Wire.requestFrom(slave, sizeof(answer));
        PortExtender::read((byte*) &answer, sizeof(answer));
        return (int) answer;
    }

    void PortExtender::read(byte* p, int len) {
        while (len > 0 && Wire.available() > 0) {
            *p++ = Wire.read();
            len--;
        }
    }

Arduino ints are 2 bytes, nodeMCU ints are 4 bytes. Data from slave is send as short (Arduino, 2 bytes), received as short (nodeMCU, 2 bytes) and then promoted to int (nodeMCU, 4 bytes).

**PortExtender.h**

    #ifndef PortExtender_h
    #define PortExtender_h
    /*
     *
     */
    #include <Arduino.h>
    #include <inttypes.h>

    #define NO_CMD             0
    #define CMD_DIGITAL_WRITE  1
    #define CMD_DIGITAL_READ   2
    #define CMD_ANALOG_WRITE   3
    #define CMD_ANALOG_READ    4
    #define CMD_PIN_MODE       5
    #define CMD_SET_WATCHDOG   6
    #define CMD_START_WATCHDOG 7
    #define CMD_STOP_WATCHDOG  8
    #define CMD_RESET          9
    #define CMD_PLAY          10
    #define CMD_PLAY_STEP     11
    #define CMD_DEBOUNCE      12
    #define CMD_TONE          13
    #define CMD_TONE_LEN      14
    #define CMD_NO_TONE       15

    #define ERROR_NO_RESET    -1
    #define ERROR_PARAMETER   -2

    struct PAR_TONE {
        byte pin;
        unsigned int freq;
    };

    struct PAR_TONE_LEN {
        byte pin;
        unsigned int freq;
        unsigned long len;
    };

    class PortExtender
    {
      private:
          short slave;
          int send(byte* b, int len);
          int send(byte cmd);
          int send(byte cmd, byte arg1);
          int send(byte cmd, byte arg1, byte arg2);
          int readAnswer();

      public:
          PortExtender(int slaveAddress);

          /*
           *     All same as Arduino, except as noted.
           */
          int pinMode(int pin, int mode);
          //    Set debouncer.
          int debounce(int pin, short debounce);

          int digitalWrite(int pin, int value);
          int digitalRead(int pin);
          int analogWrite(int pin, int value);
          int analogRead(int pin);
          int tone(int pin, unsigned int freq);
          int tone(int pin, unsigned int freq, unsigned long len);
          int noTone(int pin);

          /*
           * Watchdog functions
           */
          //    Designate the output pin and watchod parameters.
          int setWatchdog(int pin, unsigned long time, unsigned long pulse);
          int startWatchdog();
          int stopWatchdog();

          /*
           *    Timed switching of a pin, with a giving set of intervals.
           */
          int play(int pin, unsigned int score[]);

          /*
           *    Reset Port Extender.
           */
          int reset();
          static void read(byte*, int len);
    };

    #endif

**Slave PortExtender (Arduino Pro Mini)**

This is work in progress. Digital/Analog read/write completed, other methods (play, watchdog and tone still to be tested).

    /*
       Programable Port Extender by Look Alterno.

       Convert your Arduino in a I2C slave that extends
       the number of pin for your master Arduino.

       Your master Arduino will be able to:
       - Read/Write digital/analog pins.
       - Program one-shot pulses of any length.
       - Program PWM with arbitrary period and duty cycle.

       Applications:
       - Make timers for external appliances.
       - Implement watchdogs for resetting things.
    */

    //  ---- Change this address to a suitable value if needed ----
    #define MY_ADDRESS  42

    #include <Bounce2.h>
    #include <Wire.h>
    #include <PortExtender.h>

    //  A CMD_RESET has been received from master.
    boolean bReset = false;

    //  These port are programmables.
    struct {
      byte pin;
      byte exp;
    } pins[] = {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0},
      {8, 0}, {9, 0}, {10, 0}, {11, 0}, {12, 0}, {13, 0},
      {A0, 0}, {A1, 0}, {A2, 0}, {A3, 0}
    };

    const short nPins = sizeof(pins) / sizeof(pins[0]);

    struct {
      Bounce debouncer;
      short pin;
      short interval;
    } debouncer = {Bounce(), 0, 0};

    #define WD_NORMAL 0
    #define WD_PULSE  1

    struct {
      int pin;
      int state;
      boolean active;
      unsigned long lastBeat;
      unsigned long time;
      unsigned long pulse;
      unsigned long wait;
      unsigned long startPulse;
    } watchdog;

    #define SCORE_MAX_STEP 50
    struct {
      boolean active;
      int pin;
      unsigned long time; // start time of current step.
      int freeStep;       // for filling the array.
      int currentStep;    // for playing the array.
      unsigned int step[SCORE_MAX_STEP];
    } score;

    typedef void (*fcnptr)();

    void cmdBeat();
    void cmdDigitalWrite();
    void cmdDigitalRead();
    void cmdAnalogWrite();
    void cmdAnalogRead();
    void cmdPinMode();
    void cmdWatchdog();
    void cmdStartWatchdog();
    void cmdStopWatchdog();
    void cmdReset();
    void cmdPlay();
    void cmdPlayStep();
    void cmdDebounce();
    void cmdTone();
    void cmdToneLen();
    void cmdNoTone();

    struct {
      byte  cmd;
      fcnptr fcn;
    } commands[] = {
      { NO_CMD,             cmdBeat},
      { CMD_DIGITAL_WRITE,  cmdDigitalWrite},
      { CMD_DIGITAL_READ,   cmdDigitalRead},
      { CMD_ANALOG_WRITE,   cmdAnalogWrite},
      { CMD_ANALOG_READ,    cmdAnalogRead},
      { CMD_PIN_MODE,       cmdPinMode},
      { CMD_SET_WATCHDOG,   cmdWatchdog},
      { CMD_START_WATCHDOG, cmdStartWatchdog},
      { CMD_STOP_WATCHDOG,  cmdStopWatchdog},
      { CMD_RESET,          cmdReset},
      { CMD_PLAY,           cmdPlay},
      { CMD_PLAY_STEP,      cmdPlayStep},
      { CMD_DEBOUNCE,       cmdDebounce},
      { CMD_TONE,           cmdTone},
      { CMD_TONE_LEN,       cmdToneLen},
      { CMD_NO_TONE,        cmdNoTone}
    };

    unsigned long now = millis();
    byte  lastCommand;
    short answer;

    void setup() {
      Serial.begin(9600);
      Serial.println("--- Port Extender ---");

      initAll();
      Wire.begin(MY_ADDRESS);
      Wire.onReceive(receiveCommand);
      Wire.onRequest(sendAnswer);
    }

    void loop() {
      now = millis();

      checkDebouncer();
      checkWatchdog();
      checkPlay();
    }

    void checkDebouncer() {
      debouncer.debouncer.update();
    }

    /*
       Start playing a score on pin.
       The pin start at the last value set by master (HIGH or LOW)
    */
    void startPlay() {
      noInterrupts();
      score.active = true;
      score.time   = millis();
      score.currentStep = 0;
      digitalWrite(score.pin, !digitalRead(score.pin));
      interrupts();
    }

    void checkPlay() {
      noInterrupts();

      if (score.active) {
        unsigned long stepEnd = score.time + score.step[score.currentStep];

        if (now >= stepEnd) {
          score.currentStep++;

          if (score.currentStep >= score.freeStep) {
            score.active = false;
          } else {
            digitalWrite(score.pin, !digitalRead(score.pin));
            score.time = now;
          }
        }
      }

      interrupts();
    }

    /*
       Each if is time to reset the master.
       After resetting the master, soft-reset the slave.
    */
    void checkWatchdog() {
      if (watchdog.active) {

        switch (watchdog.state) {
          case WD_NORMAL:
            if (now - watchdog.lastBeat > watchdog.time) {
              pinMode(watchdog.pin, OUTPUT);
              digitalWrite(watchdog.pin, HIGH);
              watchdog.startPulse = now;
              watchdog.state = WD_PULSE;
            }

            break;

          case WD_PULSE :
            if (now - watchdog.startPulse > watchdog.pulse) {
              digitalWrite(watchdog.pin, LOW);
              cmdReset();
            }

            break;
        }
      }
    }

    /*
        Receive a command from Master
    */
    void receiveCommand(int howMany) {
      lastCommand = Wire.read();
      //  Serial.print("command="); Serial.println(lastCommand);
      answer = 0;

      if (!bReset && lastCommand != CMD_RESET) {
        //  The first command received must be a CMD_RESET.
        answer = ERROR_NO_RESET;
      } else {
        fcnptr f = commands[lastCommand].fcn;
        f();

        watchdog.lastBeat = now;
      }
    }

      // called by interrupt service routine when outgoing data is requested
      void sendAnswer() {
        Wire.write((byte *) &answer, sizeof(answer));
        lastCommand = NO_CMD;
      }
      void cmdBeat() {
      }

      void cmdReset() {
        //  Make a soft reset.
        initAll();
        bReset = true;
      }

      /*
         Initialize all variables and pins.
      */
      void initAll() {
        score.active = false;
        watchdog.active = false;
        debouncer.pin = -1;

        int size = sizeof(pins) / sizeof(pins[0]);

        for (int i = 0; i < size; i++) {
          int pin = pins[i].pin;
          pinMode(pin, OUTPUT);
          digitalWrite(pin, LOW);
        }

        answer = MY_ADDRESS;
      }

      void cmdPinMode() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();
          pinMode(pin, val);
        }
      }

      void cmdDebounce() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();
          debouncer.pin = pin;
          debouncer.interval = val;
          debouncer.debouncer.attach(pin);
          debouncer.debouncer.interval(val);
        }
      }

      void cmdDigitalWrite() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();

          digitalWrite(pin, val);
        }
      }

      void cmdDigitalRead() {
        if (Wire.available() == 1) {
          byte pin = Wire.read();

          if (pin == debouncer.pin) {
            answer = debouncer.debouncer.read();
          } else {
            answer = digitalRead(pin);
          }
        }
      }

      void cmdAnalogWrite() {
        if (Wire.available() == 2) {
          byte pin = Wire.read();
          byte val = Wire.read();

          analogWrite(pin, val);
        }
      }

      void cmdAnalogRead() {
        if (Wire.available() == 1) {
          byte pin = Wire.read();

          answer = analogRead(pin);
        }
      }

      void cmdTone() {

      }

      void cmdToneLen() {

      }

      void cmdNoTone() {
        if (Wire.available() == 1) {
          byte pin = Wire.read();
          noTone(pin);

        }
      }

      void cmdPlay() {
        if (Wire.available() == 1) {
          score.active = false;
          score.pin = Wire.read();
          score.freeStep = 0;
        }
      }

      void cmdPlayStep() {
        unsigned int val;

        if (Wire.available() == 2) {
          val = Wire.read() << 8 | Wire.read();

          if (val > 0) {
            Serial.print("val=");
            Serial.println(val);
            score.step[score.freeStep++] = val;
          } else {
            startPlay();
          }
        } else {
          answer = ERROR_PARAMETER;
        }
      }

      void cmdWatchdog() {
        PortExtender::read((byte *) &watchdog.pin, sizeof(watchdog.pin));
        PortExtender::read((byte *) &watchdog.time, sizeof(watchdog.time));
        PortExtender::read((byte *) &watchdog.pulse, sizeof(watchdog.pulse));
        watchdog.active = false;
      }

      void cmdStartWatchdog() {
        watchdog.active = true;
      }

      void cmdStopWatchdog() {
        watchdog.active = false;
      }

      int searchPin(int pin) {
        int i = 0;

        while (i < nPins && pins[i].pin != pin) {
          i++;
        }

        return (i < nPins) ? i : -1;
      }

**The question**

What is going wrong here?

  [1]: https://i.stack.imgur.com/ZY8sa.jpg
  [2]: https://i.stack.imgur.com/PTSVk.png
  [3]: https://i.stack.imgur.com/3kPP9.png

body:
**Hardware problem!**

The nodeMCU I'm using fails (mostly resets and garbage in the Serial Monitor) when inserted in the breadboard. That is. Them run OK when I let them just hanging from the USB cable.

I tested two of them in different breadboards. I also tested the breadboard for shorts and failed connections with an ohmmeter.

These are culprits:

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

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