message:
control 3 relays with 1 button

Is there a way to control 3 relays with 1 button?

My idea is: There are 3 modes; mode 1 for relay 1, mode 2 for relay 2 and mode 3 for relay 3.

With a long press you switch between modes (After 3 comes 1) and with a short press you activate the relay which is in the activated mode.

I need this for my wheelchair so please help me.

Thank you, Michael

---

Further question:
Does the relays really need a external power supply?
Because I have a small amount of power to control with the relays.

body:
Sure you can. This site isn't a great place for open-ended questions like this though. Since you have a serious real-world need I'll give you some guidance anyway.

You'd need to break it into pieces and solve each one in turn.

First create code that recognizes long and short presses (not using `delay()`.) You'll probably want to respond on releasing the button, since at that point it's easy to tell if it was a long or a short press.

The pseudo-code might look something like this:

    void loop()
       if button_is_pressed
          if !press_in_progress
             press_in_progress = true
             start = millis()
       else
          if press_in_progress //Button has been released
             elapsed = millis() - start
             press_in_progress = false
             if elapsed > long_press_threshold
                long_press_function()
             else
                short_press_function()

For controlling the relays, I suggest getting "digital" relays that are made to be controlled with 5V logic signals. Relays [**like this**][1] work well. (Link). Since you need to control 4 relays, a 4 channel model like [this one][2] would be a better choice. Note that you'll need a fairly high current power supply. A 2A 5V regulated supply should be plenty for both your Arduino and your relays, although it's more of a sure thing if you use separate power supplies for the arduino and the relays (that way the voltage to the arduino doesn't bounce around as the relays energize and de-energize.

You'll need a global variable for the currently active relay. The long press would increment that value modulo 4: (going from 0 to 3 and then back to 0)

    relay_index = (relay_index + 1) % 4;

You'd need an array of 4 bools for the states of each relay:

    bool relay_states[4];

The short press would toggle the state of the current relay

    relay_states[relay_index] = !relay_states[relay_index];

Note that if you're more interested in solving your wheelchair problem cost-effectively than tinkering, this is the sort of thing that a maker space would be ideal for. There are lots of tinkerers there who love a challenge, and would likely pitch in and help you.

  [1]: https://www.amazon.com/Tolako-Arduino-Indicator-Channel-Official/dp/B00VRUAHLE/ref=asc_df_B00VRUAHLE/?tag=hyprod-20&linkCode=df0&hvadid=309803885710&hvpos=1o1&hvnetw=g&hvrand=941850642207041054&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9007580&hvtargid=pla-568715033020&psc=1
  [2]: https://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTEN3TM/ref=sr_1_3?crid=1GPWH2OQM8ERY&keywords=arduino 4 channel relay&qid=1566257466&s=electronics&sprefix=arduino 4 ,electronics,134&sr=1-3


sender: user

sender: assistant

body:
Yes, it is possible to do that and there are libraries for that purpose. Check for example  [ObjecButton library][1], which supports click, press and double click action. It is well documented and comes with many examples...

And does the relays really need a external power supply? It depends, what kind of relays you want to use, what kind of power supply is available on wheelchair, what is the load switched by these relays and so on...

  [1]: https://github.com/JSC-electronics/ObjectButton


message:
How to program micro chips directly with USB

Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?
Where can i find information on the protocols/standards to do such a thing?

More specifically, I want to be able to make a custom pcb for my Attiny85 chips with a usb connector. I would prefer not to use the arduino IDE.
Is it possible to program this chip like so?

body:
> Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

The bare chip? Generally, no.

*Some* chips that include USB hardware also may include a DFU bootloader in ROM. If your chosen chip has this, then yes you can - you just need to wire it up and use a suitable DFU firmware upload program to install your compiled code into the chip.

However chips that don't have USB will *never* have a USB DFU bootloader in them. In such cases is is *your* responsibility to create (or otherwise obtain) a suitable bootloader that *you* will install into the chip.

Digispark and Adafruit both do that.  They take a chip that doesn't have USB and install software that tries to (poorly) emulate USB over GPIO pins1.

For chips that do not have actual USB hardware in them it is far more common to use a UART-based bootloader - simply because this is a much lighter and more "correct" way of doing it.

If you want to use a direct USB connection for your device you should be selecting a chip that has USB built into it (AVR "U" series2, most PIC32, many ARM-based chips) which will allow you to have *proper* USB communication instead of slow HID and custom (non-standard) protocols only3.

Note that at no point does your choice of bootloader, or method of communication with the bootloader, tie you in to using the Arduino IDE.  The IDE just compiles the code then runs an external program that communicates with the bootloader (different bootloaders need different programs to communicate with them). How you compile the software is up to you. How you execute the bootloader upload program is up to you.

----

1. Personally I think that's a *horrible* idea and should *NEVER* be done. I'm a purist though.
2. Such as the ATMega32U4 used on the Leonardo and Micro boards.
3. VUSB can only (barely) run fast enough for USB 1.1. That means only HID protocols are officially supported (keyboard and mouse), and anything else is non-standard and requires special supporting software to work with it.


body:
>Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

Put a bootloader on the chip first, then an offboard USB/Serial adapter can be used for the serial programming.   That's basically what a ProMini is - a bootloaded '328P (in SMD form) with a resonator & decoupling caps and a small voltage regulator - and a header to accept an FTDI Basic for programming serially.  If you notice the Black and Green colors next to the FTDI header, those are to match the wire colors on the the FTDI cables that were originally used, before seperate USB cable and FTDI modules became more popular.
https://www.sparkfun.com/products/9718
[![enter image description here][1]][1]

Instead of the 6-pin FTDI header, you could make an adapter board to go from FTDI to a USB-A 5-pin connector, then on your board have a USB-B-Mini or USB-B-Micro 5-pin connector to bring in the FTDI's 5V, Gnd, DTR, Tx, and Rx signals.

USB wouldn't be coming in directly, but you would have the spacing advantage of the small USB connector, and could program serially from a PC USB port.

Too bad you don't want to use the Arduino IDE, there are supported core codes to add to the IDE for the Attiny85 and other chips like that. Attiny85 with bootloader could then be serially programmed with an offboard USB/Serial adapter.

https://github.com/SpenceKonde/ATTinyCore

>ATtinyCore Universal
>
>This core supports the following processors - essentially every ATtiny processor that makes sense to use with Arduino. Click the processor name for part-specific information:
>
>ATtiny2313, 4313
>
>ATtiny24, 44, 84 (With or without Optiboot bootloader)
>
>ATtiny25, 45, 85 (With or without Optiboot bootloader)
>
>ATtiny261, 461, 861 (With or without Optiboot bootloader)
>
>ATTiny87, 167 (with or without Optiboot bootloader)
>
>ATTiny48, 88 (With or without Optiboot bootloader)
>
>ATTiny441, 841 (With or without Optiboot bootloader)
>
>ATTiny1634 (With or without Optiboot bootloader)
>
>ATTiny828 (With or without Optiboot bootloader)
>
>ATtiny43 (no bootloader)

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


message:
Dc motor backvoltage, how to place the diode correctly?

[![enter image description here][1]][1]My previous questions have been anwsered, so thank you all for that!

I make a new question post because I have some other problems with my setup. I use a esp12s 8266 chip. It sends a PWM signal to a n-channel mosfet, so I can regulate the speed of the dc motor that is attached to the drain of the mosfet. The DC motor has extra power from a 9v battery and this battery negative is connected to the GND of the 8266. I can control it with bluetooth hc-05 module, it has 3 options, 40%, 0% (off) and 100% (full power).

Here's the problem:
I can control everything and it seems like it works all fine, but when the motor starts spinning I see a yellow led flashing on my 8266 chip and I can't control it anymore. I read about backvoltage from the motor. So I think maybe the backvoltage is causing the chip not to function anymore. To make it work again I need to disconnect and reconnect the chip for it to work again.

So my question is: could this be the backvoltage or something else?
And if it's the backvoltage how do I need to connect the diode (1n4001) in this circuit?

I read when a motor stops then the backvoltage happens, but in my case the led on the 8266 starts flashing when it spins. So maybe I hooked something the wrong way. here I have some pictures of the different setups I tried.

Of course I will solder everything nicely, but for now it's just to get a quick impression of the hookup.

Hopefully someone can help me out, thanks in advance!

[![Version 1][2]][2]

[![Version 2][3]][3]

  [1]: https://i.stack.imgur.com/UelsX.png
  [2]: https://i.stack.imgur.com/bf66r.jpg
  [3]: https://i.stack.imgur.com/KrVN8.jpg

body:
> I read when a motor stops then the backvoltage happens,

That is not true. With a brushed DC motor the back-EMF ("backvoltage") occurs at least twice (often more, depending on the number of commutator segments) per revolution of the motor.  Brushed DC motors are *very* noisy.

While you *can* use a diode (connected as you would for a relay) it's not the best solution.  Instead you really need a proper EMI-absorbing circuit.

This consists of three capacitors - all very small values, in the range 1-10nF, which connect all parts of the motor together and bleed off any induced voltages safely.

The first capacitor connects directly across the terminals.  This will safely remove the back-EMF created in the windings as the voltages switch back and forth due to the rotation of the commutator.

The other two capacitors each connect from one terminal to the metal housing of the motor (one to each side of the housing).  This will safely couple the housing to the rest of the circuit and cause it to act as a shield containing the magnetic fields better within the motor.


body:
You're looking for something called a "[flyback diode](https://cdn.sparkfun.com/assets/9/8/6/0/f/51770c5bce395f3149000000.png)."

What happens is, during "normal use" (when the DC motor is being powered by the system), you have a DC motor.  But, when the system stops giving input, and the DC motor "spins down," it can become a power generator -- generators and motors are actually very much the same, it just depends on if they're generating the power, or using the power.

The idea with the flyback diode is that it doesn't let that generated current "back" into the system, and burn up your MCU.  I've seen them in series with a small resistance, to help quickly bleed off any current/voltage the DC motor ends up generating.  With it in series, the diode stops any power from being "wasted," as current will never flow "backwards" through the diode, and thus the resistor.

When you "cut the power" to the DC motor, current can then flow through the "mini-loop" and decay through the resistor (which is not pictured in this example).


body:
Okay, I'm not sure what you're trying to accomplish, electrically, but the diagram you added doesn't make sense.  It also doesn't match any of the pictures you've posted.  In the diagram, you have your emitter and collector tied together with a diode... but your pictures don't have **ANYTHING** attached to your emitter leg... you have things "wrapped" around your heatsink/ground, for some reason?

So we'll ignore the pictures that don't make actual circuits, and focus on your diagram.  In the diagram, you've accomplished this:

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

If you look at this, the diode is doing nothing -- your BJT already has Miller resistance between the emitter and collector, so the diode does nothing for you, here.  You also don't need any capacitors, as you are not looking to **store** any power, for any reason.  Because of this, I've changed it to a resistor (R4).

What you're really looking for is something more along these lines:

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

With this, your 9V battery will only power the motor when the BJT is on (your Pin10 is HIGH).  This completes the circuit, and current flows through your motor.  The diode (D1) prevents any current from flowing through the resistor (R2), and no power is lost.

When you turn your motor "off" by setting Pin10 to LOW, kinetic energy will cause your motor to "continue spinning" a little bit -- it's not going to just stop dead, since that energy needs to go somewhere.  This little bit of remaining spin turns your DC motor into a DC generator, and it provides its own power.  This current/voltage needs to go somewhere, or you'll burn things up.

This is where the diode (D1) and resistor (R2) come in handy.  That current can now flow through the mini-loop, and bleed-off this induced power -- or flyback voltage spike -- which is why it's called a "flyback diode."  You're trying to bleed-off that power, not store them, so you need a resistor instead of a capacitor.

So lose the caps, substitute with a resistor, and move your flyback diode.

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


message:
Mega2560 has 2 Crystal Oscillator?

Who knows this Mega2560 with two Crystal Oscillators: 12 000 MHz and 16 000 MHz? What is the use of them?

body:
There are two devices on an Arduino board than need a clock source:

* The ATMega328 / ATMega2560 main MCU (16MHz)
* The USB interface.

The USB interface crystal speed depends on what device is used on your board. Genuine Arduino boards use an ATMega16U2 which uses a 16MHz crystal.  Cheap Chinese clones use a CH340G which takes a 12MHz crystal.

Note that normally it's one crystal and one ceramic resonator.  USB requires very precise timing, so a crystal is used for that. The main MCU doesn't need quite such precise timing, so a cheaper (and less accurate) ceramic resonator is used.


message:
expected initializer before 'RF24'

The code i make is this
    */

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #include <Servo.h>
    #define CE_PIN   9
    #define CSN_PIN 10

    const uint64_t pipe = 0xE8E8F0F0E1LL;
    int servoy;
    int servox;
    Servo Yservo;
    Servo Xservo;

    RF24 radio(CE_PIN, CSN_PIN);

    int joystick[2];

    void setup()RF24
    {
      Serial.begin(9600);
      delay(1000);
      radio.begin();
      radio.openReadingPipe(1,pipe);
      radio.startListening();
      Xservo.attach(3);
      Yservo.attach(5);
    }

    void loop()
    {
      if ( radio.available() )
      {
        bool done = false;
        while (!done)
        {
    done = radio.read( joystick, sizeof(joystick) );
    servox= joystick[0]/5.683;
    servoy= joystick[1]/5.683;
          Serial.println(servoy);
          Yservo.write(servoy);
          Serial.println(servox);
          Xservo.write(servox);
        }
      }
      else
      {
          Serial.println("NO RADIO CONECTION");
      }

    }

and i don't know what  happen it's said that

     sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

     void setup()RF24

                 ^

    C:\Users\ASUS\Documents\Arduino\sketch_aug20b_rc_rc_rc_22\sketch_aug20b_rc_rc_rc_22.ino: In function 'void loop()':

    sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

     done = radio.read( joystick, sizeof(joystick) );

          ^

    exit status 1
    expected initializer before 'RF24'

body:
You have two problems:

    sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

    void setup()RF24

             ^

It's basically saying "I don't understand what you mean by RF24 here". That `RF24` in that line should not exist. I assume you made some kind of typo or copy-pasta error.

Second:

 C:\Users\ASUS\Documents\Arduino\sketch_aug20b_rc_rc_rc_22\sketch_aug20b_rc_rc_rc_22.ino: In function 'void loop()':

    sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

     done = radio.read( joystick, sizeof(joystick) );

That is saying that `radio.read` doesn't return a value - yet you are trying to assign that value that doesn't exist to something.

According to the documentation for `RF24::read()`:

> Read the available payload
>
> The size of data read is the fixed payload size, see getPayloadSize()
>
> **Note**
>
> I specifically chose 'void*' as a data type to make it easier for beginners to use. No casting needed.
>
> No longer boolean. Use available to determine if packets are available. Interrupt flags are now cleared during reads instead of when calling available().
>
> **Parameters**
>
>
> * `buf` Pointer to a buffer where the data should be written
> * `len` Maximum number of bytes to read into the buffer
>
>    if(radio.available()){
>      radio.read(&data,sizeof(data));
>    }
>
> **Returns**
>
> No return value. Use available().


message:
SD Card store struct: force big-endian / little-endian?

Following MAJENKO's tutorial on [sd card file optimization and data integrity][1], can I force the SDCard to read and write in either big-endian or little-endian?

I need this in order to maintain backup data integrity across a wide array of IoThings, using various boards (Arduino UNO, MEGA, Nano, NodeMCU, etc) for future parsing.

  [1]: https://hackingmajenkoblog.wordpress.com/2016/03/25/fast-efficient-data-storage-on-an-arduino/

body:
Many full C libraries have an `sys/endian.h` header file. This defines a number of macros so you can find out what the endianness of your device is.  It also usually defines a number of handy macros that can convert the endianness for you.

    htobe16(x)
    htobe32(x)
    betoh16(x)
    betoh32(x)

These convert **H**ost **to** **B**ig **E**ndian values and back again.

    htole16(x)
    htole32(x)
    letoh16(x)
    letoh32(x)

And these convert **H**ost **to** **L**ittle **E**ndian values and back again.

Not many embedded C libraries provide it, though, and not all that do provide the handy macros.

It's not too hard to implement yourself, but it does mean you deciding what to do depending on the target architecture. Which kind of negates the handiness of the endian.h file.

So really you want to re-implement the functionality in a form you can include in all your sketches.

Fortunately the compiler provides a set of macros defining the endianness that you can use though:

    #define __ORDER_LITTLE_ENDIAN__ 1234
    #define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
    #define __ORDER_PDP_ENDIAN__ 3412
    #define __ORDER_BIG_ENDIAN__ 4321
    #define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

So you can examine the `__BYTE_ORDER__` macro to see what byte order it equates to and use that to select whether `htobe32(x)` has to do anything to the byte order or not.

In the PIC32 compiler it's done as a set of macros that either call `swap32` / `swap16`, or pass the value unchanged:

    #if __BYTE_ORDER__ == __LITTLE_ENDIAN__

    #define htobe16 swap16
    #define htobe32 swap32
    #define betoh16 swap16
    #define betoh32 swap32

    #define htole16(x) (x)
    #define htole32(x) (x)
    #define letoh16(x) (x)
    #define letoh32(x) (x)

    #endif /* __BYTE_ORDER__ */

    #if __BYTE_ORDER__ == __BIG_ENDIAN__

    #define htole16 swap16
    #define htole32 swap32
    #define letoh16 swap16
    #define letoh32 swap32

    #define htobe16(x) (x)
    #define htobe32(x) (x)
    #define betoh16(x) (x)
    #define betoh32(x) (x)

    #endif /* __BYTE_ORDER__ */

So now depending on the byte order it will either swap the bytes around, or leave them unchanged.  It's now just a matter of implementing `swap16` and `swap32` - which I'll leave to you (hint: it just returns the value with the bytes in the reverse order - bit shifting and masking is good for that).

Then you need to decide on an endianness for your file.  Maybe choose little-endian since that is probably the most common.  So whenever you place a value into a struct for writing you pass it through either `htole32(...)` or `htole16(...)` depending on the data type.  Then whenever you read from a struct that has been read you pass the value through either `letoh32(...)` or `letoh16(...)` to get it in the host's endianness.


message:
FS100A works when Arduino connected to PC but not when connected to Raspberry Pi

I am building a simple circuit which monitors soil humidity in a flower pot. I was able to measure it and send it from one Arduino Nano to another Nano via FS100A transmitter and receiver and VirtualWire library.

As this is prototype so far I connected 1st (measuring) Nano to a powerbank and it works fine: I see the data is send and received by 2nd Arduino.

2nd Nano receives the data (it is less than 50 bytes) and send send it to PC via USB serial connection. All works fine as long as 2nd Arduino is connected to anything but Raspberry PI. Then it is not able to receive any data.

I modified source code of my program to blink built-in LED right after data is read. When 2nd Nano is powered by another powerbank it blinks (the data is read). The same happens using any other PC. But when I try to use it with RPi there is no blinking.
RPi is model B+ and I tried two different devices.

I suspect that Raspberries don’t provide stable power to usb or they cause a lot of noise preventing radio from reading the data. Is there any way to overcome this?

body:
After some attempts I finally made it work.
I tried to use a level shifter. It worked somehow but I could not find any library which would work with Arduino's VirtualWire.

I just put a 220µ capacitor on power lines to the radio receiver. It filtered all the noise and Arduino is able to interpret signals correctly.

[![wiring][1]][1]

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


message:
can I check if why my motor isn't working?

I am currently using the arduino Uno connected with L298N(green pcb) connected to a dc motor rated 12V. I provided dedicated 12v power supply to the dc motor and the arduino board's power is supplied by usb connected to my pc. I connected Pin 9 of arduino uno to 'ENA' on L298N , Pin 7 & 8 (UNO) to 'INA' & 'INB' of L298N. Connected '-' polarity of Motor power supply to GND of L298N, while also connecting the 'GND' of L298N to the GND of Arduino UNO. Last but not least, connecting the 'OUT B'to the dc motor. This is the picture of how L298N(green) look like https://sea.banggood.com/Green-Board-L298N-DC-Motor-Driver-Board-Stepper-Motor-p-974549.html?cur_warehouse=CN

Can i check why my motor isn't running? Thanks in advance.

    char data = 0;
    int enB = 9;
    int InC = 8;
    int InD = 7;

    void setup()
    {
        Serial.begin(9600);
        Serial.println("Motor test !");
      pinMode(enB, OUTPUT);
       pinMode(InC, OUTPUT);
      pinMode(InD, OUTPUT);

    }

    void loop()
    {Serial.println("Entered loop, should start moving now !");
      digitalWrite(InC, HIGH);
      digitalWrite(InD, LOW);
       digitalWrite(enB, HIGH);
       analogWrite(enB, 255);
     }

body:
Well, your wiring is OK, but I think the

'digitalWrite(enB, HIGH);

in the loop() code is causing your problem.  You don't want to try to use the same pin for both digital and analog functions.

I wired up a Uno here with your setup and a L298N, and got a motor to run fine with the following sketch that doesn't use the loop() at all - it does everything in setup().

    char data = 0;
    int enB = 9;
    int InC = 8;
    int InD = 7;

    void setup()
    {
     Serial.begin(9600);
     Serial.println("Motor test !");
     pinMode(enB, OUTPUT);
     pinMode(InC, OUTPUT);
     pinMode(InD, OUTPUT);

     Serial.println("motor should start moving now !");
     digitalWrite(InC, HIGH);
     digitalWrite(InD, LOW);
     //digitalWrite(enB, HIGH);

     for (size_t i = 0; i < 10; i++)
     {
      analogWrite(enB, 20*i);
      Serial.print("motor speed = "); Serial.println(20 * i);
      delay(2000);
     }

     Serial.println("quitting!");
     while (true)
     {

     }

    }

    void loop()
    {
     //Serial.println("Entered loop, should start moving now !");
     //digitalWrite(InC, HIGH);
     //digitalWrite(InD, LOW);
     //digitalWrite(enB, HIGH);
     //analogWrite(enB, 255);
    }

If you can't get your motor working with the above program, then you most likely have a connection or power supply or component problem that you'll need to troubleshoot.

Hope this helps,

Frank


message:
Slave to Send Data after Receiving Command using I2C

I want to have my Slave Arduino to send signal to Master after the command was made. But the Slave Arduino does not proceeds to sending the signal after doing the command. What is wrong with my code?

**Slave**
<!-- language-all: lang-cpp -->
```
void receiveEvent(int bytes) {
  dir = Wire.read();    // direction
  dis = Wire.read();    // distance
  spe = Wire.read();    // speed
  eStop = Wire.read();    // 1 or 0
  Serial.println(dir);
  Serial.println(dis);
  Serial.println(spe);
  mov = true;
}
void loop() {
    Wire.onReceive(receiveEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
       Wire.onRequest(requestEvent);
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
      Wire.onRequest(requestEvent);
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}
void requestEvent(){
    Wire.write(1);
    fin = false;
    Serial.println("sent");
}
```

**Master**
```

#include <Wire.h>

const byte interruptPin = 2;
byte dir = 0;
byte dis;
byte spe;
bool upd;

bool state= false;

void setup() {

  Wire.begin();
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), emergencyStop, CHANGE);
  Serial.begin(9600);

}
void loop() {
       if( state == false ){
       dir = 1;
       dis = 30;
       spe = 2;
       Wire.beginTransmission(9); // transmit to device #9
       Wire.write(dir);
       Wire.write(dis);
       Wire.write(spe);
       Wire.write(0);
       Wire.endTransmission();    // stop transmitting
       state = true;
       }
       if (state == true){
        if(Wire.available() > 0){
       Wire.requestFrom(9,2);   //6bytes from slave 9
          bool upd = Wire.read();
          Serial.println(upd);
        }
      }
}
void emergencyStop(){ // not working
  Wire.beginTransmission(9); // transmit to device #9
       Wire.write(0);
       Wire.write(0);
       Wire.write(0);
       Wire.write(1);
       Wire.endTransmission();    // stop transmitting

}
```

body:
found my solution for this. although not verified yet, but i removed Serial print and moved the Wire.onRequest outside of the if loop. and uses a ledPin for checkups

    void loop() {

            Wire.onReceive(receiveEvent);
            Wire.onRequest(requestEvent);
      if (dir == 1 && mov == true && eStop == false){
          motor.Distance(dis);
          motor.Speed(spe);
          motor.Forward();
          mov = false;
          fin = true;
        }
      if (dir == 2 && mov == true && eStop == false){
        motor.Distance(dis);
        motor.Speed(spe);
        motor.Reverse();
        mov = false;
        fin = true;
      }

      else{
        motor.Stop();
      }
    }

    void requestEvent(){
        if ( fin == true){
          Wire.write(1);
         fin = false;
        digitalWrite(ledPin, HIGH);
        }

    }


message:
LCD shield submenu

I need to make an app that does various functions regarding IR signals (remote-like)
I need to create a sub menu in order for me to access multiple functionalities.

[Arduino-Uno-Menu-Template][1]

I used the link above to create a menu and it works great! The problem is I can not do a sub menu without messing with the loop that display the original one. Any ideas?

  [1]: https://www.instructables.com/id/Arduino-Uno-Menu-Template/

This is the code I got so far:

https://pastebin.com/Vh5R2JVp

I'm trying in menuItem1() function to add a routine to create the submenu.
I tried to use a variable that changes when the menu does but it didn't work.

body:
What you can do (but there are many solutions):

- Keep a variable (e.g. `subMenu` that has the state of the current menu option selected (make this an `enum`).
- Whenever a sub menu is entered, assign the `subMenu` variable with the current sub menu value.
- Use a `switch` around the current `switch` statement for first switching subMenu (make different functions for clearity).

So the pseudo code would look like

    enum ESubMenu { MainMenu, Page1, Page2 };
    ESubMenu subMenu;

    void setup()
    {
      subMenu =  MainMenu;
    }

    void loop()
    {
       switch (subMenu)
       {
       case MainMenu : showMainMenu() ; break;
       case Page1Menu: showPage1Menu(); break;
       case Page2Menu: showPage2Menu(); break;
       }
    }

    void showMainMenu()
    {
       if (`sub menu 1 selected`)
       {
          subMenu = Page1Menu;
       }
       else if (`sub menu 2 selected')
       {
          subMenu = Page2Menu;
       }
       else
       {
          // Show/handle main menu
       }
    }

    void ShowPage1()
    {
       if `back'
       {
         subMenu = MainMenu;
       }
       else
       {
          // Show/handle page 1 menu options
       }
    }


message:
Why is observed clock rate < 3MHz on Arduino Uno?

I wrote a simple loop to test the processor speed on my Arduino Uno. The numbers I'm getting are much worse than the 16MHz advertised, by a factor of ~5. Trying to figure out what I'm missing.

    long counter = 0;
    int sum = 0;
    uint32_t t = 0;

    void setup() {
      Serial.begin(9600);
      t = micros();
    }

    void loop() {
      sum += counter;

      if (counter == 10000) {
        float usecsPerIteration = (micros() - t) / (counter * 1.0);
        Serial.print(usecsPerIteration);
        Serial.println(" microseconds per iteration");

        // Print result to avoid loop getting optimized away
        Serial.println(sum);
      }

      ++counter;
    }

The output is:

    3.77 microseconds per iteration

Here's how I'm estimating clock rate from this. The body of the loop involves two additions and an equality check. Even if we assume that these simple operations take 10 clock cycles, the implied clock rate is still just (1 iter / 3.77 us) * (1e6 us / sec) * (10 cycles / iter) = 2.65 MHz.

What am I missing?

body:
The loop function is called within the framework of the Arduino IDE.
Beyond the code you write, also an interrupt check is done, which also cost time, and explains the difference.

The following function CAN be called after every loop call.
See Majenko's answer about the details.

    /*
      SerialEvent occurs whenever a new data comes in the hardware serial RX. This
      routine is run between each time loop() runs, so using delay inside loop can
      delay response. Multiple bytes of data may be available.
    */
    void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          stringComplete = true;
        }
      }
    }

See [SerialEvent][1] for more info.

However, as Kwasmich's comment says, you can easily circumvent this by performing your test inside a `while`  loop.

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


body:
As Michael says there is a lot more going on than you think.

Firstly there are interrupts triggering which can slow things down (used to calculate milllis()).

Secondly you vastly under estimate the number of instructions that are being called.  For a start the `loop` is being called from a `for(;;)` loop in `main()`:

        for (;;) {
      loop();
    4   572: 0e 94 73 00  call 0xe6 ; 0xe6 <loop>
      if (serialEventRun) serialEventRun();
    2   576: 20 97        sbiw r28, 0x00 ; 0
    2   578: e1 f3        breq .-8       ; 0x572 <main+0x10>
    -   57a: 0e 94 1d 01  call 0x23a ; 0x23a <_Z14serialEventRunv>
    2   57e: f9 cf        rjmp .-14      ; 0x572 <main+0x10>
    10 total

Then for the call to `loop()` the registers used get pushed to the stack, then your code executed, and the registers popped off again before returning.  This is the code for loop when disassembled:

    000000e6 <loop>:
        // Save the registers to the stack
    2   e6:     cf 92        push r12
    2   e8:     df 92        push r13
    2   ea:     ef 92        push r14
    2   ec:     ff 92        push r15
    8 total

        // Add to the sum
    2   ee:     40 91 44 01  lds r20, 0x0144 ; 0x800144 <counter>
    2   f2:     50 91 45 01  lds r21, 0x0145 ; 0x800145 <counter+0x1>
    2   f6:     60 91 46 01  lds r22, 0x0146 ; 0x800146 <counter+0x2>
    2   fa:     70 91 47 01  lds r23, 0x0147 ; 0x800147 <counter+0x3>
    2   fe:     80 91 42 01  lds r24, 0x0142 ; 0x800142 <sum>
    2   102:    90 91 43 01  lds r25, 0x0143 ; 0x800143 <sum+0x1>
    1   106:    84 0f        add r24, r20
    1   108:    95 1f        adc r25, r21
    2   10a:    90 93 43 01  sts 0x0143, r25 ; 0x800143 <sum+0x1>
    2   10e:    80 93 42 01  sts 0x0142, r24 ; 0x800142 <sum>
    18 total

        // Check the value to see if it's time to print
    1   112:    40 31        cpi r20, 0x10 ; 16
    1   114:    57 42        sbci r21, 0x27 ; 39
    1   116:    61 05        cpc r22, r1
    1   118:    71 05        cpc r23, r1
    2   11a:    d1 f5        brne .+116     ; 0x190 <loop+0xaa>
    6 total

        // From here on is the "IF" section - skipped by the BRNE above
    -   11c: 0e 94 f5 04  call 0x9ea ; 0x9ea <micros>
    -   120: c0 90 3e 01  lds r12, 0x013E ; 0x80013e <__data_end>
    -   124: d0 90 3f 01  lds r13, 0x013F ; 0x80013f <__data_end+0x1>
    -   128: e0 90 40 01  lds r14, 0x0140 ; 0x800140 <__data_end+0x2>
    -   12c: f0 90 41 01  lds r15, 0x0141 ; 0x800141 <__data_end+0x3>
    -   130: 6c 19        sub r22, r12
    -   132: 7d 09        sbc r23, r13
    -   134: 8e 09        sbc r24, r14
    -   136: 9f 09        sbc r25, r15
    -   138: 0e 94 68 06  call 0xcd0 ; 0xcd0 <__floatunsisf>
    -   13c: 6b 01        movw r12, r22
    -   13e: 7c 01        movw r14, r24
    -   140: 60 91 44 01  lds r22, 0x0144 ; 0x800144 <counter>
    -   144: 70 91 45 01  lds r23, 0x0145 ; 0x800145 <counter+0x1>
    -   148: 80 91 46 01  lds r24, 0x0146 ; 0x800146 <counter+0x2>
    -   14c: 90 91 47 01  lds r25, 0x0147 ; 0x800147 <counter+0x3>
    -   150: 0e 94 6a 06  call 0xcd4 ; 0xcd4 <__floatsisf>
    -   154: 9b 01        movw r18, r22
    -   156: ac 01        movw r20, r24
    -   158: c7 01        movw r24, r14
    -   15a: b6 01        movw r22, r12
    -   15c: 0e 94 c7 05  call 0xb8e ; 0xb8e <__divsf3>
    -   160: ab 01        movw r20, r22
    -   162: bc 01        movw r22, r24
    -   164: 22 e0        ldi r18, 0x02 ; 2
    -   166: 30 e0        ldi r19, 0x00 ; 0
    -   168: 88 e4        ldi r24, 0x48 ; 72
    -   16a: 91 e0        ldi r25, 0x01 ; 1
    -   16c: 0e 94 a9 04  call 0x952 ; 0x952 <_ZN5Print5printEdi>
    -   170: 60 e0        ldi r22, 0x00 ; 0
    -   172: 71 e0        ldi r23, 0x01 ; 1
    -   174: 88 e4        ldi r24, 0x48 ; 72
    -   176: 91 e0        ldi r25, 0x01 ; 1
    -   178: 0e 94 0b 03  call 0x616 ; 0x616 <_ZN5Print7printlnEPKc>
    -   17c: 60 91 42 01  lds r22, 0x0142 ; 0x800142 <sum>
    -   180: 70 91 43 01  lds r23, 0x0143 ; 0x800143 <sum+0x1>
    -   184: 4a e0        ldi r20, 0x0A ; 10
    -   186: 50 e0        ldi r21, 0x00 ; 0
    -   188: 88 e4        ldi r24, 0x48 ; 72
    -   18a: 91 e0        ldi r25, 0x01 ; 1
    -   18c: 0e 94 b0 03  call 0x760 ; 0x760 <_ZN5Print7printlnEii>

     // All this is just counter++
    2   190: 80 91 44 01  lds r24, 0x0144 ; 0x800144 <counter>
    2   194: 90 91 45 01  lds r25, 0x0145 ; 0x800145 <counter+0x1>
    2   198: a0 91 46 01  lds r26, 0x0146 ; 0x800146 <counter+0x2>
    2   19c: b0 91 47 01  lds r27, 0x0147 ; 0x800147 <counter+0x3>
    2   1a0: 01 96        adiw r24, 0x01 ; 1
    1   1a2: a1 1d        adc r26, r1
    1   1a4: b1 1d        adc r27, r1
    2   1a6: 80 93 44 01  sts 0x0144, r24 ; 0x800144 <counter>
    2   1aa: 90 93 45 01  sts 0x0145, r25 ; 0x800145 <counter+0x1>
    2   1ae: a0 93 46 01  sts 0x0146, r26 ; 0x800146 <counter+0x2>
    2   1b2: b0 93 47 01  sts 0x0147, r27 ; 0x800147 <counter+0x3>
    20 total

     // Get the registers back and return
    2   1b6: ff 90        pop r15
    2   1b8: ef 90        pop r14
    2   1ba: df 90        pop r13
    2   1bc: cf 90        pop r12
    4   1be: 08 95        ret
    12 total

That's more than 10 instructions.  I make it 74 clocks to run one full iteration. (`counter++` alone is 20 clock cycles - double your estimation for the total...)

You have to remember two important things:

* AVR is a RISC CPU - that means that seemingly simple operations can take multiple instructions to perform.
* AVR is an 8-bit CPU - that means that working with any variables bigger than 8 bits in size require far more complex code, and you work with 32-bit variables (and floats, but that's outside the timing loop section of your code).


message:
Set PWM by period? And have it variable?

In [this other stack QA][1] I'm asking about generating a pulse signal with a period ranging from 63 ms to 6.5 ms. There is a popular PWM library however it doesn't compile and also since 63 ms is 15.8 Hz, that library's integer Hz setting isn't of help.

Is there a definitive process that isn't waving incense bundles in the corners of the room? There is an over abundance of "how tos" on the internet, however, none seemed to get me to a solution.

I've got a Mega and am using TIMER5. It's "just like" TIMER1 in that it is a 16 bit timer.

  [1]: https://electronics.stackexchange.com/questions/452219/

body:
I stumbled upon a solution via trial and error coupled with watching the results on an o'scope.

The best guidance came from a [Stack Exchange QA][1]. Setup isn't particularly special, however the combination of WGM bits here worked and I didn't investigate further. Of the biggest importance are the prescaler divider bits, the least three significant bits of TCCRxB. `001` means no dividing or prescaling of the clock.

It all boiled down to 4 registers and the `pinMode()` call. Ultimately, seven lines of code:
<!-- language-all: lang-cpp -->

 #define PULSE_PIN 45
 void setup() {
  // IMPORTANT: Clear Timer/Counter Control Registers
  TCCR5A = 0;
  TCCR5B = 0;

  // Set Timer/Counter Control Registers
  TCCR5A = B00101001; // Phase and frequency correct PWM change at OCRA
  TCCR5B = B00010010; // least sig bits sets "carrier frequency" by dividing CPU clock
  // Observation:
  // TCCR5B = B00010010 and OCR5A = 16667 results in period of 16.70 mSec
  // meaning OCR5A is period in uSec when TCCR5B = B00010010
  // TCCR5B = B00010001 : OCR5A = 20000 results in period = 2.5 mSec 399.3Hz

  pinMode(PULSE_PIN, OUTPUT);
 }

In the sketch, I watch an analog pin with a potentiometer on it and map its sweep to an effective RPM range of 950 to 9000 RPM. Hence the arbitrary range of periods I want to handle. When `loop()` sees the ADC change, the below code adjusts the PWM accordingly.

Note that no floating point data types are used. The magic numbers below were chosen by trial and error in a spreadsheet with values rounded to whole numbers.

 void setRpm(){
  // Getting to period in uSec from rpm the long way to keep
        //  the answer in range of the data type:
  unsigned int rpm = map(pot_adc, 0, 1023, RPM_MIN, RPM_MAX);
  unsigned long period = rpm/50;
  period = 24000/period;
  period = period*50;
  // The trigger lasts 26°, so the PW is 26/360 * period.
  dwell = period/36;
  dwell = dwell*26;
  dwell = dwell/10;

  // OCR5A is a counter the carrier frequency counts up to,
        //  which sets output period / frequency
  // meaning OCR5A is period in uSec when TCCR5B = B00010010
  OCR5A = period; // OCR5A is period in uSec when TCCR5B = B00010010
  // OCR5B is the width of the pulse. If we used floats,
        //  we could use duty cycle * period.
  OCR5B = dwell;
 }

Obviously, this code will have limitations to the range of frequencies it can handle, but the Internet has plenty of means for higher frequency PWM, especially when the desired PWM is fixed and doesn't need varying.

The most helpful way to see the control registers is as binary positions and not to rely upon macros, masks, and bit shifting. This comment block helped greatly:

     // WGM modes:
  // TCCR1A
  // Bit              7      6      5      4      3     2     1     0
  // Bit Name         COM1A1 COM1A0 COM1B1 COM1B0 ----- ----- WGM11 WGM10
  // Initial Value    0      0      0      0      0     0     0     0
  // changed to       1      1      1      1      0     0     0     1

  // TCCR1B
  // Bit            7      6      5       4        3        2        1        0
  // Bit Name       ICNC1  ICES1  -----   WGM13    WGM12    CS12     CS11     CS10
  // Initial Value  0      0      0       0        0        0        0        0
  // changed to     0      0      0       0        1        0        0        1
  // CS12,CS11,CS10 = (0,1,1) = prescaler divide by 64

  [1]: https://stackoverflow.com/questions/48873501


message:
How to detect V-SYNC on the SparkFun MicroView?

Is there a way to detect the start of the OLED screen refresh cycle (V-SYNC) on the SparkFun MicroView? There is no code for this functionality in the [Arduino library][1]; in fact it looks like the Arduino library is only set up to *send* data over SPI to the display, and not *receive* any data/status back.

Do you know how to access the internal state of the OLED screen directly, by polling some kind of status bit over SPI?

The only [datasheet][2] I can find of this OLED screen does not have SPI command details.

Update: here's a movie taken with an iPhone on "slo-mo" video, showing a full screen (all pixels on). There is clearly a screen refresh going on, which interlaces with the video frame rate.

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

  [1]: https://github.com/sparkfun/SparkFun_MicroView_Arduino_Library/blob/V_1.0.0/src/MicroView.cpp
  [2]: https://github.com/sparkfun/SparkFun_MicroView_Arduino_Library/blob/V_1.0.0/extras/OLED-Datasheet_SAS1-02007-A UG-6448HLBEG03 (WiseChip).pdf
  [3]: https://i.stack.imgur.com/qodx6.gif

body:
The scenario you describe is called the *Tear Effect*. On the SSD1306, which the device you are interested in is based around, a Frame Synchronisation pulse can be emitted on the FR pin.

However it would appear that the specific SSD in use by SparkFun does *not* provide this pin from the SSD1306 on the external FPC connector, so there is no way of getting it.  Probably owing to the small size of the display a reduced size connector without extra pins like FR was used.

So no, you can't combat the Tear Effect with that display.

There is nothing you can do over SPI, either. That is simply because SPI is just too slow for such things. You would use the FR pin because it's instantaneous.  With SPI you would have to make a request to read a register, then read that register's value back. In that time, coupled with the question of exactly *when* would the register say it was at the start of a frame, the information would be completely meaningless anyway.


message:
Running out of GPIO & looking for suggestions

I'm working on a project using a NodeMCU and am quickly running out of GPIO pins. I'm trying to decide which way to go to complete it.

Right now, I have the MCU connected to a MAX31856 PT100 thermocouple (SPI), a PWM output, a transistor (acting as a switch), a single button and a single LED. I'm needing to add at least 2 more of the MAX31856, a display (either I2C or SPI) and a rotary encoder/button.

I've looked into GPIO expanders, but I'm doubtful that the available libraries for the additional hardware will work through the expanders. I have a Mega that will work without a doubt, but then I will have issues with WiFi & MQTT. I looked at the Mega's with onboard WiFi, but I got so confused in reading how to program it, setting the DIP switches, etc that it doesn't seem like a valid choice.

Can anyone offer guidance?

body:
Two main solutions comes to my mind:

 1. GPIO expander (as you mentioned). It is really easy to use them as digital inputs or outputs. So you can connect button, LED, transistor and maybe even display (you did not specified type of the display, so I assume standard LCD 1602 or 2004 display). You can also connect SPI-CS signals to the expander, but this depends on used libraries...
 2. Auxiliary Arduino e.g. Nano. Arduino can be used for measurement of the temperature and other stuff and NodeMCU for communication. In this case you have to implement some kind of communication between these two boards (SPI, I2C or UART).


message:
Upload application from Visual Studio 2019 with PlatformIO

How upload application from Visual Studio? I can’t find upload process from standard VS in documentation https://docs.platformio.org/en/latest/ide/visualstudio.html

I hate VS Code.

body:
I am using Visual Studio Code, but I suppose the plugin works similar in Visual Studio. Look at the screenshot below.

[![this ][1]][1]

In red rectangle you have "Project tasks options", where you can find "Upload" button. This will not work, if you have not set at least one environment in platformio.ini file – see the [documentation][2].
Example of the simple environment for Arduino Uno created in  platformio.ini file:

    [env:uno]
    platform = atmelavr
    board = uno
    framework = arduino

  [1]: https://i.stack.imgur.com/2kbk3.png
  [2]: https://docs.platformio.org/en/latest/projectconf.html


body:
I have final solution for uploading application from VS 2019.

 1. Visual Studio have Tools > External Tools... where is possible add the PlatformIO command for uploading application `pio run -v -t upload`

[![VS External Tools settings by PlatformIO][1]][1]

 1. After that is possible adding custom button to Toolbar [![enter image description here][2]][2]
 2. Fantastic thing is, that during upload you can Stop the process [![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/nUJo9.jpg
  [2]: https://i.stack.imgur.com/fJwLI.png
  [3]: https://i.stack.imgur.com/ySQ2A.png


message:
Sim800 FTP Arduino

I've been unable to FTP anything using an Arduino and SIM800L. I have reduced the code as far as possible:

    #include <SoftwareSerial.h>

    //Create software serial object to communicate with SIM800L
    SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

    String moduleAnswer = "";

    void setup()
    {
      //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(9600);

      //Begin serial communication with Arduino and SIM800L
      mySerial.begin(9600);

      Serial.println("Initializing...");
      delay(1000);

      SoftwareATCommand("AT"); //Once the handshake test is successful, it will back to OK
      SoftwareATCommand("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
      SoftwareATCommand("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
      SoftwareATCommand("AT+CREG?"); //Check whether it has registered in the network

      //APN and GRPS Setup
       SoftwareATCommand("AT+SAPBR=0,1"); //Close GPRS before connecting
       SoftwareATCommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); //Configure bearer profile

      SoftwareATCommand("AT+SAPBR=1,1"); //Connect to GPRS

      //FTP Connection
      SoftwareATCommand("AT+FTPCID=1");
      SoftwareATCommand("AT+FTPSERV=127.189.249.205"); //Not real IP
      SoftwareATCommand("AT+FTPPORT=21");
      SoftwareATCommand("AT+FTPUN=user");
      SoftwareATCommand("AT+FTPPW=pass");

      //FTP Upload
      uploadFTP();

     }

    void loop()
    {
    }

    void uploadFTP()
    {
      SoftwareATCommand("AT+FTPPUTNAME=\"test.txt\""); //Filename
      SoftwareATCommand("AT+FTPPUTPATH=/home/arduino/SolarDataLogger/"); //Path
      SoftwareATCommand("AT+FTPPUT=1"); //Start FTP
      delay(10000);
      SoftwareATCommand("AT+FTPPUT=2,100"); //Send 100 bytes of data
      delay(10000);
      SoftwareATCommand("Hello12345"); //Send Data
      SoftwareATCommand("AT+FTPPUT=2,0"); //Close FTP

    }

    String SoftwareATCommand(String strAT)
    {

      String strNotice = "Sending: " + strAT;
      Serial.println(strNotice);
      mySerial.println(strAT);

      delay(500);
      moduleAnswer = "No Response";

      while(mySerial.available())
      {
        moduleAnswer = mySerial.readString();

        char* buf = (char*) malloc(sizeof(char)*moduleAnswer.length()+1);
        moduleAnswer.toCharArray(buf, moduleAnswer.length()+1);
        Serial.write(buf);//Forward what Software Serial received to Serial Port
         - Module answer sent to screen
        free(buf);
       }

       return moduleAnswer;
    }

The serial output where the trouble is:

[![Serial output][1]][1]

I've tried waiting longer for the `+FTPPUT: 1,1,1360` response or sending something twice, but nothing seems to work. The file gets created but no other data is ever sent.

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

body:
Maybe its too late to respond but the line +FTPPUT: 1,65 indicates a server error.

 https://www.elecrow.com/wiki/images/2/20/SIM800_Series_AT_Command_Manual_V1.09.pdf - page 275.

 Please check a sequence of commands , maybe something is missing ?

 I use the following sequence :

    "AT+CREG?"
    "AT+SAPBR=3,1,\"Contype\",\"GPRS\""
    "AT+SAPBR=3,1,\"APN\",\"NAME OF YOUR PROVIDER \""
    "AT+SAPBR=1,1"
    "AT+SAPBR=2,1"
    "AT+FTPCID=1"
    "AT+FTPSERV=\"SERVER ADDRESS\""
    "AT+FTPPORT=21"
    "AT+FTPTYPE=\"I\""
    "AT+FTPUN=\"USERNAME\""
    "AT+FTPPW=\"PASSWORD\""
    "AT+FTPPUTNAME=\"" + NAME OF FILE + "\""
    "AT+FTPPUT=1"
    "AT+FTPPUT=2," + STRING OF BUFFER SPACE ( Get from response of FTPPUT=1 )
    "AT+FTPPUT=2,0"

 Look on the manual for the commands above.

Sorry about my grammar


body:
what I observed in your code-I think you did not follow the proper sequence of connecting the GPRS context mentioned in the [sim800l datasheet][1].
Please follow the section 3.1. bearer configuration. I also attached the screenshot herewith. So you missed setting the Access Point Name(APN). After you query the GPRS context(last step in the image), if you get the proper IP address, then you are sure to send the data over FTP. Please follow the FTP sequence mentioned in the datasheet.
[![enter image description here][2]][2]

  [1]: https://cdn-shop.adafruit.com/datasheets/sim800_series_ip_application_note_v1.00.pdf
  [2]: https://i.stack.imgur.com/x5aln.png


message:
How to Work Two Linear Actuator Synchronously by Using Arduino and VNH5019 Motor Driver?

I am newbie and I want to build a project that contains two linear actuator that move synchronously. Two of them will lift up and down at same time. I use arduino mega and VNH5019 motor driver. I have thompson electrac ELD linear actuator. I have never tried to synchronize two linear actuator. Linear actuator have encoder output ( it is hall effect encoder -( not absolute. So it cannot keep last position in case of power cut )). Encoder type is hall effect type. Encoder output voltage levels low (logical zero), typical / max is 0.1/0.25 Vdc. Also it has output fully extented/retracted signal. I tested it with H-Bridge motor driver made of 4 SSR relays and push button switches to retract and extract. There is a synchronization problem.The system will stop when actuators extracted 500 mm ( actuators have 900 mm stroke length) How should I solve that synchronozation problem could you help me ? What should I do?

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

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

body:
It sounds like you need to watch both encoder outputs and don't let one get ahead of the other. Naturally, they won't sync exactly (i.e., pulse simultaneously) but you can set a limit on how many counts to let them differ by, before pausing the faster actuator while the slower one catches up.

If you need to save positions across a power failure, you'll need to 1) provide enough backup power to keep the system alive past the supply failure to give you time to stop both actuators and store both of their positions in EEPROM; and 2) provide a signal to the Arduino that the supplied power (not the backup) is going down, so it can begin its orderly shutdown.


message:
Charge lipo battery while using

I have a system that uses Arduino and some modules. The system needs 5v dc power with 3A current at maximum(The system needs 3A current for some seconds every 5 minutes and after that the current will get back to 300-400mA) and on the other side i have a 5v dc charger with 400-500 mA current. So my problem is lack of amperage and i can't run correctly Arduino with 5v dc charger. For solving this problem i want to use a Lipo battery to connect to Arduino but the battery will ran out and i can't get energy from battery so i want to connect the battery to my charger while the Arduino uses the battery, How can i do that? Is there any module to do this work? Can i use TP4056 with protection version to do this work?(Note: I can't change charger)

body:
You really shouldn't charge a lithium battery whilst discharging it. The charger may either never know that it has finished charging and overcharge it, or shut off early and never charge it up properly at all.

Instead you should arrange that your MCU is powered directly from the PSU so that it always has stable power, and feed that same power into a normal charger via some form of electronic switch so it can be turned on and off. The output of the battery can then be fed through another switch into your heavy load.

When it comes time for your load to be activated you switch off the power from the charger and switch on the connection from the battery to the load.

What you use to do the switching is entirely up to you - whether you choose P-channel MOSFETs or relays entirely depends on your situation.

Here's a block diagram to better illustrate it to you:

<!-- 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/diFpj.png)

<!-- End schematic -->


message:
Cycling through switch states

I'm making a desk lamp out of 2x WS2811 strips (attached to the triple ports at top right of board below). The brightness of the strips is controlled by a potentiometer, and the colour by a switch. Each press of the switch cycles through red, blue and white:

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

Here's the code I've come up with:

    #include <FastLED.h>

    #define strip_pin     7
    #define NUM_LEDS    15

    CRGB leds[NUM_LEDS];
    int distance;
    int brightness;
    int brightnesspin = 2;
    int pin_switch = 3;

    // variables to hold the new and old switch states
    boolean oldSwitchState = LOW;
    boolean newSwitchState1 = LOW;
    boolean newSwitchState2 = LOW;
    boolean newSwitchState3 = LOW;
    byte state = 0;

    void setup()
    {
      Serial.begin(9600);
      FastLED.addLeds<WS2811, strip_pin, BRG>(leds, NUM_LEDS);
    }

    void loop()
    {
      delay(500);
    //  Colour control
    //##############################################
        newSwitchState1 = digitalRead(pin_switch);
        delay(1);
        newSwitchState2 = digitalRead(pin_switch);
        delay(1);
        newSwitchState3 = digitalRead(pin_switch);
        // if all 3 values are the same we can continue
        if (  (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
        {

            if ( newSwitchState1 != oldSwitchState )
            {

               // has the button switch been closed?
               if ( newSwitchState1 == HIGH )
               {
                    // increase the value of state
                    state++;
                    if (state > 3) { state = 0; }
                    for (int i = 0; i < NUM_LEDS; i++)
                    {
                    if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                    if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                    if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}
                    }
                    FastLED.show();
                }
               oldSwitchState = newSwitchState1;
            }

    //    Brightness control
    //##############################################
      brightness = analogRead(brightnesspin);  brightness = map(brightness, 0, 1024, 0, 255);
        for (int i = 0; i<NUM_LEDS; i++)
          {
            FastLED.setBrightness(brightness);
          }
      FastLED.show();
      Serial.print("Brightness: ");
      Serial.println(brightness);
        }
    }

The brightness control works fine, and the switch cycles through the colours *once*, but the strip stays white once it's there, even though the serial monitor shows the switch changing state. How can I get the strip to cycle back round to red?

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

body:
The problem lies in your for cycle.

 - If `(state == 1)` you are switching the red colour ON.
 - If `(state == 2)` you are switching the blue colour is ON. So at this moment, you have red AND blue colour on, not only blue. I assume the output colour is purple-ish.
 - If `(state == 3)`, you activate red (which is already ON), blue (which is also already ON) and also green (which changes state from OFF to ON) so you get white colour. At this moment you went through all three possible conditions.
 - Then you go back to `(state == 1)`. All colours are already activated, so from this moment you get only white...

Solution:

    for (int i = 0; i < NUM_LEDS; i++) {
      if (state == 1) {
        leds[i].red = 100;
        leds[i].blue = 0;
        leds[i].green = 0;
        Serial.println("Red");
      }
      if (state == 2) {
        leds[i].red = 0;
        leds[i].blue = 100;
        leds[i].green = 0;
        Serial.println("Blue");
      }
      if (state == 3) {
        leds[i].red = 100;
        leds[i].blue = 100;
        leds[i].green = 100;
        Serial.println("White");
      }
    }


body:
In your lines:

                    if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                    if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                    if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}

The LEDs are set on, but are never turned off.

Sequence is:

1: Red leds turn on; strip appears red.

2: Blue leds turn on (the leds will probably actually look purple rather than blue here as the red leds are still on)

3: Green leds turn on (red and blue leds are already on); strip appears white

back to start:

1,2,3: nothing changes as all leds are already on, strip remains white.

I'd suggest adding:

    leds[i].green = 0; leds[i].blue = 0;

to the `state == 1` condition and

    leds[i].green = 0; leds[i].red = 0

to the `state == 2` condition.


message:
Arduino is running as a server, but want to occasionally act as a client to update time

My Arduino (actually an ESP32-based Adafruit HUZZAH32) is running as a wifi server. Its main job is to service GET requests from a user, and to periodically turn devices on and off based on the commands implicit in those GETs.

It needs to keep an accurate time/date - in order to turn devices on/off as directed.   My cheap real-time clock is off a couple seconds or more per day.   So I figure I'll use code such as the example at:

https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/

... in which the Arduino creates a client to get the time from an NTP server.  Once a day (e.g. checking for the RTC time to be 00:00hrs in my "loop"), I'll adjust the RTC using NTP.

Looking around, it sounds like this is ok, for the Arduino to act as a client, as long as it's not actively servicing a client (the user's GET requests).  Do I have that right ?   Need I worry that a user might be sending a GET when that happens ?

body:
There is no problem with running multiple servers and use multiple clients with the WiFi library of the ESP32 core for Arduino as it is not a problem with most of the WiFi libraries for Arduino (some can't run servers (TinyGsm) or can run only one server (WiFiEsp(AT)).

But you don't need a WiFiClient for NTP time. First because NTP runs on UDP and second because the ESP32 SDK provides SNTP and the ESP32 core for Arduino wraps it in functions presented in the ESP32 examples library's [SimpleTime example][1].

  [1]: https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/Time/SimpleTime/SimpleTime.ino


message:
Nano can't get reply from ENC28J60 Ethernet Shield

My Arduino Nano can't get a reply from my new ENC28J60 Ethernet Shield - I can't get any library examples to work. Using the UIPEthernet lib, and running the EchoServer example with logging turned up, I get:

    ENC28J60::init DEBUG:csPin = 10
    ENC28J60::init DEBUG:miso = 12
    ENC28J60::init DEBUG:mosi = 11
    ENC28J60::init DEBUG:sck = 13
    ENC28J60::init DEBUG:Use Native hardware SPI
    Enc28J60Network::writeOp(uint8_t op, uint8_t address, uint8_t data) DEBUG_V3:Function started
    ENC28J60::init DEBUG_V3:Before readOp(ENC28J60_READ_CTRL_REG, ESTAT)
    Enc28J60Network::readOp(uint8_t op, uint8_t address) DEBUG_V3:Function started
    ...

so it gets nicely into the Enc28J60Network::init function. But shortly after, it does a phyWrite, tries to read a response, and then times out.

    ENC28J60::init DEBUG_V3:Before phyWrite(PHCON2, PHCON2_HDLDIS)
    Enc28J60Network::phyWrite(uint8_t address, uint16_t data) DEBUG_V3:Function started
    ... lots of attempts to read
    Enc28J60Network::phyWrite ERROR:TIMEOUT !!

And then it all starts to fail, and it never gets better. I tried the EtherCard lib, too, and it fails in a similar way.

I put the scope on the SPI pins, and I see reasonable stuff: activity on SCK and MOSI, nothing on MISO, and the SS (pin 10) switching ok - and the shield claims to use pin 10 (I briefly tried pin 8 as I flailed in confusion, but no luck there either).

So at this point, either I'm misunderstanding something, or the shield is DOA.

*Update*: Earlier, I strongly suspected the SCK line because it showed a very poor signal on my scope. But it turned out to be poor grounding on the scope probe, and the signal  was actually fine, a red herring. Thanks to @Majenko for drawing my attention to it.

*Update 2*: After getting no SPI response from the shield under any circumstances, my working hypothesis is that it was DOA. I've gone back to my UNO with W5100: all working fine. I have ordered more Nano ethernet shields, to arrive in a week or two, so I'll try with those, and provide updates/answers then.

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

body: The ENC28j60 shield for Nano has reset of the ENC28j60 chip on the pin 7 of the shield/Nano. Try to set the pin 7 HIGH.


body:
Thanks to @Riad, who posted this as a comment. The problem appears to be a design fault in the "DK ectronics" V1.0 Ethernet Shield.

> Perhaps this could bring some solution. https://www.mikrocontroller.net/topic/477142

The site is in German, so here's a brief translation of the key parts:

>I bought an ENC28J60 for the Arduino Nano, but it does not respond from the programmed IP.

>The shield has "NANO Ethernet Shield V1.0 DK ectronics" inscribed on the underside (spelling error in the original). There
there is a via on the bottom between pins D11 and D12,
missing from a (different) working shield. This via connects D12 line to GND from the AMS1117 on the top (easy to check D12 to GND with a multimeter). If that's the case with your shield, then this is the problem: we just have to cut out the via connection. I have
Do this with a 1mm drill by placing the top copper layer in the
via very gently (really gently!) Mill it away. If you drill too deep, you break the D12 connection completely and must possibly
solder on a new wire. Keep checking D12 and GND for continuity to see whether you've milled away enough. Work really carefully!

>After I did that, and tried the TCP Server example in the UIPEthernet
library on the Arduino, the shield was reachable.

>  -- Christoph K

I haven't yet tried to make the changes described above, because they are fiddly and I have a new batch of working shields. But my device is exactly as described by Christoph and his photos, and the fault description matches mine.


message:
How to debug Arduino using Atmel studio?

I have an Arduino Yun board and an Atmel ICE programmer/debugger. There are 6 pins on the Arduino Yun to connect to Atmel ICE for programming only, but I can't find the pins for debugging. Anyway to do so? Which pins on the Arduino should I connect to Atmel ICE?

body:
I found another very easy way to debug the arduino board with atmel studio without even using an external debugeer like the atmel ice debugger. It's an extension called vMicro which can be added within atmel studio (visual studio as well) you connect the arduino board over the micro USB to the computer and specify the parameters in the vMicro toolbar in atmel studio and that's it!
 It's ready to debug! Finally I think atmel ice is thought for other boards maybe, since debugging can be done without it easily!


message:
Problem with powering ublox NEO-6M GPS module

Firstly, I'd like to mention that I'm a beginner. This is the first time I've worked with a GPS module. The serial monitor is completely empty when I upload the following code to my circuit:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>

    // The serial connection to the GPS module
    SoftwareSerial ss(4, 3);

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

    void loop(){
      while (ss.available() > 0){
        // get the byte data from the GPS
        byte gpsData = ss.read();
        Serial.write(gpsData);
      }
    }

![The circuit I used](https://i.stack.imgur.com/7Ghrc.png)

Things I might've done wrong and some things I'd like to mention:

1. As you can see, I connected the module to 5V pin of Arduino but the datasheet says:
![Datasheet says that the maximum voltage that can be used is 3.6 V and the module can't stand overvoltage](https://i.stack.imgur.com/JStxq.jpg)
The reason why I think this might not be the case is that there are multiple projects on the internet that have used a circuit like mine.

2. I've placed my module on the window edge so that it can get a good line of sight. I'm yet to try it outdoors.

3. After reading the datasheet, I tried a potential divider using resistors to get 3.3V and the result is still nothing. I later realized that this was probably a really silly thing to do since I created an unstable supply which is not suitable for the module.

4. For cold-start conditions, how long can it take to lock to a satellite? I've waited several times for half an hour each time only to get no result in the end. Can it take more than that? Should I wait?

5. What can I use to supply constant 3.3V to the module? Are there any special power supplies for GPS modules?

6. Is it possible to tell if my module is damaged just by seeing?

body:
1. The module may very well be dead now, due to giving it 5V.

But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought.

 2. A window means that at least 50% of the sky is blocked by the building. The module might not be able to get a signal from enough satellites for a cold start.

 3. A voltage divider only works if there is constant current. As you've noted, you just created an unstable power supply.

 4. The datasheet says 27 s but that is probably with a clear view of the sky.

 5. Next to the 5V pin on the Uno is a 3.3V pin. How about using that?

 6. Visually, no. But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not.


message:
How come some Arduino Nano pins (D3, D4, A3, A4, A6, A7) cannot be set high?

I made a sketch to switch on all digital and analog pins, and found out several pins did not work as expected. Note: I manually put a jumper wire from each digital and analog pin (one at a time) to a resistor, LED and GND pin.

What I noticed was that some pins did not work (D3, D4, A4, A6 and A7) and pin A3 was only lit about half intensity. I tried two different Nanos and they performed both equally (also pin A3 at half intensity).

I also tried the jumper wires directly touching the pins (without a breadboard in between, to rule out a breadboard problem). Same behavior (so the breadboard is ok).

My questions:

1. How come pins D3, D4, A4, A6 and A7 are not output VCC (3.3V) ?
2. How can I switch pins these pins on?
3. What is the reason pin A3 is blinking at half intensity?
4. How can I switch this pin fully on?
5. Bonus question: I used numbers, why are the pin names A0..A7 and D0..D12 not defined in Arduino IDE?

---

Test sketch:

    const int NR_OF_PINS = 22;

    int pins[NR_OF_PINS]   =
    // 0  1  2  3  4  5  6   7   8   9  10 11   12  13  14  15  16  17  18  19  20  21
    //D0 D1 D2 D3 D4 D5 D6  D7  D8  D9 D10 D11 D12 D13  A0  A1  A2  A3  A4  A5  A6  A7
     { 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26 };

    void setup()
    {
      for (int n = 0; n < NR_OF_PINS; n++)
      {
        pinMode(pins[n], OUTPUT);
        digitalWrite(pins[n], HIGH);
      }
    }

    void loop()
    {
    }

body:
You don't need an array, and your "base" pin is wrong - you start at pin 1, not pin 0. Also pins A6 and A7 can only be analog inputs, not digital outputs.

It's simpler to write:

    void setup() {
        for (uint8_t i = 0; i < NUM_DIGITAL_PINS; i++) {
            pinMode(i, OUTPUT);
            digitalWrite(i, HIGH);
        }
    }

    void loop() {
    }

That will work correctly on all Arduino boards regardless of the number of pins, since the board definition defines how many pins there are, and pins are always contiguously numbered from 0.


message:
Determing approximate bicycle speed for distancemeter

I'd like to build a self-contained bicycle distancemeter similar to those now used by local police, i.e. that measure and display the distance between the bicycle handlebar's end and passing cars and beep when distance is less than 1m on 50-km/h roads. In order to avoid detecting cars when stopped at traffic lights, I need to determine whether the bicycle is moving above a minimum speed, say 10 km/h. How can I do that without having to install additional hardware on the bicyle, like a magnet on the wheel and a sensor on the fork? Accelerometers?

body:
I have built many years ago a device nearly identical to what you describe. I did not have the additional requirement of a minimum speed of 10 kph, however. As noted in the comments, that is likely best resolved with GPS as you are detecting motion, not absolute speed figures.

I used "arduino gps library" as the search terms and found many options. One of them, [TinyGPS++][1] appears to have what you require and much more:

> TinyGPS++ is a new Arduino library for parsing NMEA data streams
> provided by GPS modules.
>
> Like its predecessor, TinyGPS, this library provides compact and
> easy-to-use methods for extracting position, date, time, altitude,
> speed, and course from consumer GPS devices.
>
> However, TinyGPS++’s programmer interface is considerably simpler to
> use than TinyGPS, and the new library can extract arbitrary data from
> any of the myriad NMEA sentences out there, even proprietary ones.

I would definitely appreciate the "considerably simpler" aspect, as well as the "extract arbitrary data" portion, which seems specific to your project.

There may be other libraries that provide your objective, this was the first on the search returns.

The device I constructed used the common ultrasonic detector with a transmitter and receiver pair, coupled to a set of seven-segment LED display blocks. When the slightly-less-than-one-meter distance was presented, my device would trigger a pair of cameras. For your beep purpose, it would be straight-forward to redirect the camera trigger to a piezo speaker module or any other suitable audio device. I did not require GPS or other speed information.

  [1]: http://arduiniana.org/libraries/tinygpsplus/


body:
GPS would be simple in terms of being self-contained, but a GPS module is somewhat expensive, and is also a big power drain.

I'd recommend a wheel sensor. Some modern wireless bike-computers use accelerometer based wheel RPM sensors. You attach them to the spokes and they detect the motion with/against the force of gravity as they travel up and down. They use wireless communication like BLE (Bluetooth Low Energy.) If you added a BLE module to your Arduino you might be able to pair it with a wireless RPM sensor and measure speed that way, with no wires or magnets needed.

## EDIT:

I don't know for sure what wireless protocol these accessories use. If it's not BLE then interfacing them with an Arduino might be harder.


message:
How to access variables by variable? (I.e. variable variables?)

Can Arduino handle variable variables?
<!-- language-all: lang-cpp -->

    function getLetterCode(char input) {
        int letter_a = 17;
        int letter_b = 42;
        int letter_c = 50;
        return letter_$$input$$; //pseudocode
    }

This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.

body:
No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime.  In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.

Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a `struct`) and iterate it looking for the right key to match with your input.  Or, if there aren't too many inputs, simply use a `switch` to select different values:

    int getval(char input) {
        switch (input) {
            case 'a': return 17;
            case 'b': return 42;
            case 'c': return 50;
            default: return 0;
        }
    }


message:
Undocumented industrial servo with 8-wire encoder: how to read this encoder?

I have scavenged an industrial servo with its attached ballscrew linear actuator from an old large format scanner, and I am trying to figure out how to make a 'servo drive' aka 'servo driver' aka 'servo controller'.

I'm a total novice at arduino, and am mostly a copy/paste coder - so of course this makes my goal harder.

I can find a lot of information on how to read a simple AB offset encoder that needs _**four**_ wires to work, but the encoder I have has eight wires:

A+, A-, B+, B-, Z+, Z-, +5v, 0v(aka GND)

With +5v supplied to it's wire and GND connected to 0v, rotating the motor shaft by hand, my meter reads:

 - A+: +3.97v as the 'high' and +.036v as 'low'
 - A-: same
 - B+: same
 - B-:    same
 - Z+: same - but only goes high at one location on the 360 degree
     rotation
 - Z-: same - but only goes high at one location on the 360 degree
   rotation - the same location as Z+

NOTE: Both Z pulses coincide with pulses on A+, B+, and B- ... but those are NOT coincident on A-. So maybe A- has the Z+/- trigger in it's place? I don't know. It was VERY challenging to stop rotating the shaft AT a pulse because of the tiny size of the divisions.

All voltages seen by my digital multimeter were positive voltages.

I do not understand how to properly use the encoder with so many wires. I can sort of understand that the positive and negative are probably opposite signals from each other, sort of error protection or something? I know that the Z= and Z- are roattion counters at either 90, 180, or some other offset angle to allow ticking full rotations. But am unsure about this all and am reading a lot of material that is beyond me. I'm stumped.

I can install the following code on an UNO and the UNO reads the encoder just fine off the A+ and B+ lines, with increasing count for one direction of rotation and decreasing count for the other direction. So it is reflecting the movement as it should...

BUT- I am getting 8000 pulses per shaft revolution rather than the 2000 pulses per revolution in the documentation. So something's not right here. I should see 2000 pulses per revolution... is this because of the lack of use of the other wires? Or something else?

Code i'm using for just A+ and B+:

        /*
    *Quadrature Decoder
    */
    #include "Arduino.h"
    #include <digitalWriteFast.h>

    // Quadrature encoders
    // Left encoder
    #define c_LeftEncoderInterruptA 0
    #define c_LeftEncoderInterruptB 1
    #define c_LeftEncoderPinA 2
    #define c_LeftEncoderPinB 3
    #define LeftEncoderIsReversed

    volatile bool _LeftEncoderASet;
    volatile bool _LeftEncoderBSet;
    volatile bool _LeftEncoderAPrev;
    volatile bool _LeftEncoderBPrev;
    volatile long _LeftEncoderTicks = 0;

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

      // Quadrature encoders
      // Left encoder
      pinMode(c_LeftEncoderPinA, INPUT);      // sets pin A as input
      digitalWrite(c_LeftEncoderPinA, LOW);  // turn on pullup resistors
      pinMode(c_LeftEncoderPinB, INPUT);      // sets pin B as input
      digitalWrite(c_LeftEncoderPinB, LOW);  // turn on pullup resistors
      attachInterrupt(c_LeftEncoderInterruptA, HandleLeftMotorInterruptA, CHANGE);
      attachInterrupt(c_LeftEncoderInterruptB, HandleLeftMotorInterruptB, CHANGE);
    }

    void loop()
    {
      Serial.print("Encoder Ticks: ");
      Serial.print(_LeftEncoderTicks);
      Serial.print("  Revolutions: ");
      Serial.print(_LeftEncoderTicks/2000.0); //2000 Counts Per Revolution, per the engineering manual
      Serial.print("\n");
    }

    // Interrupt service routines for the left motor's quadrature encoder
    void HandleLeftMotorInterruptA(){
      _LeftEncoderBSet = digitalReadFast(c_LeftEncoderPinB);
      _LeftEncoderASet = digitalReadFast(c_LeftEncoderPinA);

      _LeftEncoderTicks+=ParseEncoder();

      _LeftEncoderAPrev = _LeftEncoderASet;
      _LeftEncoderBPrev = _LeftEncoderBSet;
    }

    // Interrupt service routines for the right motor's quadrature encoder
    void HandleLeftMotorInterruptB(){
      // Test transition;
      _LeftEncoderBSet = digitalReadFast(c_LeftEncoderPinB);
      _LeftEncoderASet = digitalReadFast(c_LeftEncoderPinA);

      _LeftEncoderTicks+=ParseEncoder();

      _LeftEncoderAPrev = _LeftEncoderASet;
      _LeftEncoderBPrev = _LeftEncoderBSet;
    }

    int ParseEncoder(){
      if(_LeftEncoderAPrev && _LeftEncoderBPrev){
        if(!_LeftEncoderASet && _LeftEncoderBSet) return 1;
        if(_LeftEncoderASet && !_LeftEncoderBSet) return -1;
      }else if(!_LeftEncoderAPrev && _LeftEncoderBPrev){
        if(!_LeftEncoderASet && !_LeftEncoderBSet) return 1;
        if(_LeftEncoderASet && _LeftEncoderBSet) return -1;
      }else if(!_LeftEncoderAPrev && !_LeftEncoderBPrev){
        if(_LeftEncoderASet && !_LeftEncoderBSet) return 1;
        if(!_LeftEncoderASet && _LeftEncoderBSet) return -1;
      }else if(_LeftEncoderAPrev && !_LeftEncoderBPrev){
        if(_LeftEncoderASet && _LeftEncoderBSet) return 1;
        if(!_LeftEncoderASet && !_LeftEncoderBSet) return -1;
      }
    }

.
.
.
Can someone explain the function of, and how to use, all eight wires? Explain why I'm getting 4X the counts that I should with that code above? PLEASE?
.
.
.

I'm posting images of the pages from the machine's engineering handbook that have info about the servo and encoder. The info there shows that it was more or less controlled like an RC servo from the mainboard's perspective - just PWM. But it had the drive/driver/controller parts right on the mainboard of the machine.

If it will be of use I can post pictures of the encoder board itself, but at this point I did not think that necessary.

[![Piniout of connector][1]][1]
[![Servo encoder resolution][2]][2]
[![Specs part 1][3]][3]
[![Specs part 2][4]][4]

  [1]: https://i.stack.imgur.com/z5FDM.jpg
  [2]: https://i.stack.imgur.com/PsWWz.jpg
  [3]: https://i.stack.imgur.com/DnQAx.jpg
  [4]: https://i.stack.imgur.com/bVwIX.jpg

body:
You have already found out, how the encoder works (basically like any other rotary encoder, only with more outputs for different angle values). That is great work.

You get a value 4 times as big because of 2 little mistakes:

1. When you use `attachInterrupt()`, you set it to trigger on a `CHANGE` of the line. One pulse consists of 2 changes (for example LOW to HIGH and then HIGH to LOW). So the interrupt get's triggered twice per encoder pulse. That's a factor of 2 for the resulting value.

2. You attach an interrupt to both of the lines, but both lines output one pulse per one encoder tick. So the value get's incremented twice per tick, what means another factor of 2. You only need an interrupt on one of the lines. The other line is only there to indicate the direction of the rotation. When the interrupt for the first line triggers, you should check the value of the second line. If it is HIGH, the encoder is rotating in one direction. If it is LOW, it rotates in the oposite direction. The lines are internally connected to little buttons/switches, that are fixed to the casing with a little offset between then. They get activated by little nubs, that are connected to the axis. Depending on from which direction the nub comes during a rotation, the first or the second button/switch will get activated first. A little after that, also the second switch will activate. So you can monitor one line, and if a pulse starts on it, you check if there already is a pulse on the other line. If yes, the other line was activated first.

So all in all this results in the factor 4 in the encoder results.

---

Note, that your `ParseEncoder()` function is a little redundant and overcomplicated. In the inner if statements you check for some values, that cannot happen in there because of the outer if statement. But this function will reduce itself to simply one if statement (or less, if you use the value directly without if), since with the above, you only need to check the value of 1 line.


body:
I had some trouble figuring this out too.
I did some more googling and found this site below via an Arduino forum post:
[8 wire connection for quadrature encoder, differential wiring][1]

Here is what they say:

 > "These terms refer not to the waveforms of signals, but instead to the way the signals are wired.
 >
 > Single-ended wiring uses one signal wire per channel and all signals are referenced to a common ground.
 >
 > [TTL][2] and [Open Collector][3] are types of single-ended wiring.
 >
 > Differential wiring uses two wires per channel that are referenced to each other. The signals on these wires are always 180 electrical degrees out of phase, or exact opposites. This wiring is useful for higher noise immunity, at the cost of having more electrical connections. Differential wiring is often employed in longer wire runs as any noise picked up on the wiring is common mode rejected."

So basically we have our Power supply wire and ground, and 2 wires per signal (A+/A-, B+/B-, Z+/Z-).

2 + 6 wires = 8 wires

Now all I have to figure out is how to connect those 6 wires to an Arduino. I get how to connect the A+, B+, Z+ signals on 3 interrupt pins, now I'm just wondering if the other 3 (A-, B-, Z-) should be connected to 3 more interrupt pins.

  [1]: https://www.eeweb.com/understanding-incremental-encoder-signals/
  [2]: https://en.wikipedia.org/wiki/Transistor-transistor_logic
  [3]: https://en.wikipedia.org/wiki/Open_collector


message:
How to scale a bitmap (uint8_t array) in Arduino?

So I have a project where I send text to an Arduino, which is then printed out as a QR code on a thermal printer that can take a bitmap image with a given width and height.

Is there a way I can "scale up" the "image," making it so one pixel is scaled up to 4 or 8 pixels?

Additionally, would it be possible to add a "quiet zone" of sorts on the left side of the image, as I am not able to offset/justify it to the middle.

QR Code lib: https://github.com/ricmoo/QRCode

Thermal printer lib: https://github.com/adafruit/Adafruit-Thermal-Printer-Library

body:
You didn't tell use the size of your QRCode, nor the type of Arduino you
are using. So I am just going to guess that your problem is that you may
have enough RAM to store the raw QRCode, but not enough to store a
scaled bitmap version.

The [Adafruit tutorial][tuto] for their thermal printer library suggests
printing bitmaps with the method:

```c++
printBitmap(width, height, tablename)
```

where `tablename` is an array holding the bitmap data. This will
obviously not work if you don't have enough RAM to store the array.
Fortunately, there is an overloaded method:

```c++
void Adafruit_Thermal::printBitmap(int w, int h, Stream *fromStream)
```

that allows you to stream the image data instead of preparing it in RAM.
You can create a stream that delivers arbitrary data by writing a class
that derives from `Stream`. Here is a tentative, untested
implementation, that delivers a scaled-up QRCode one pixel at a time:

```c++
// Stream a scaled QRCode one pixel at a time.
class QRCodeStream : public Stream
{
public:
    QRCodeStream(const QRCode &code, uint8_t scale = 1)
    : qrcode(code), scale(scale) {}

    // Output: writing to this stream is a no-op.
    size_t write(uint8_t) {}
    void flush() {}

    // Input delivers the QRCode pixels.
    int available();
    int peek();
    int read();
private:
    QRCode &qrcode;
    uint8_t scale;
    bool done = false;
    uint8_t code_x = 0;  // coordinates of the QRCode module
    uint8_t code_y = 0;
    uint8_t pix_x = 0;  // pixel coordinates within the module
    uint8_t pix_y = 0;
};

int QRCodeStream::available()
{
    // For simplicity, pretend the bytes come one at a time.
    if (done) return 0;
    else return 1;
}

int QRCodeStream::peek()
{
    if (done) return -1;
    if (qrcode_getModule(&qrcode, code_x, code_y)) {
        return 0;  // black
    } else {
        return 255;  // white
    }
}

int QRCodeStream::read()
{
    if (done) return -1;
    int data = peek();

    // Move to the next pixel.
    if (++pix_x >= scale) {
        pix_x = 0;
        if (++code_x >= qrcode.size) {
            code_x = 0;
            if (++pix_y >= scale) {
                pix_y = 0;
                if (++code_y >= qrcode.size) {
                    done = true;
                }
            }
        }
    }

    return data;
}
```

This would be used as

```c++
printer.printBitmap(width, height, QRCodeStream(qrcode, scale));
```

Note that `QRCodeStream` delivers the image data as 8-bit gray scale,
where each pixel is returned as one byte, either 0 (for black) or 255
(for white). This is likely not the format expected by the thermal
printer library, which seems to expect 1-bit black and white data, with
8 pixels packed in each byte. You will have to adapt the code for
the right format, which will likely be tedious, but not overly complex.
I leave that “as an exercise to the reader”.

[tuto]: https://learn.adafruit.com/mini-thermal-receipt-printer?view=all#bitmap-printing


message:
Why do I see error in this code

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_1KHZ);
    AF_DCMotor motor2(2, MOTOR12_1KHZ);
    AF_DCMotor motor3(3, MOTOR34_1KHZ);
    AF_DCMotor motor4(4, MOTOR34_1KHZ);
    Servo myservo;

    boolean goesForward=false;
    int distance = 100;
    int speedSet = 0;

    void setup() {

      myservo.attach(10);
      myservo.write(115);
      delay(2000);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
    }

    void loop() {
     int distanceR = 0;
     int distanceL =  0;
     delay(40);

     if(distance<=15)
     {
      moveStop();
      delay(100);
      moveBackward();
      delay(300);
      moveStop();
      delay(200);
      distanceR = lookRight();
      delay(200);
      distanceL = lookLeft();
      delay(200);

      if(distanceR>=distanceL)
      {
        turnRight();
        moveStop();
      }else
      {
        turnLeft();
        moveStop();
      }
     }else
     {
      moveForward();
     }
     distance = readPing();
    }

    int lookRight()
    {
        myservo.write(50);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(115);
        return distance;
    }

    int lookLeft()
    {
        myservo.write(170);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(115);
        return distance;
        delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if(cm==0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      motor3.run(RELEASE);
      motor4.run(RELEASE);
      }

    void moveForward() {

     if(!goesForward)
      {
        goesForward=true;
        motor1.run(FORWARD);
        motor2.run(FORWARD);
        motor3.run(FORWARD);
        motor4.run(FORWARD);
       for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
       {
        motor1.setSpeed(speedSet);
        motor2.setSpeed(speedSet);
        motor3.setSpeed(speedSet);
        motor4.setSpeed(speedSet);
        delay(5);
       }
      }
    }

    void moveBackward() {
        goesForward=false;
        motor1.run(BACKWARD);
        motor2.run(BACKWARD);
        motor3.run(BACKWARD);
        motor4.run(BACKWARD);
      for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
      {
        motor1.setSpeed(speedSet);
        motor2.setSpeed(speedSet);
        motor3.setSpeed(speedSet);
        motor4.setSpeed(speedSet);
        delay(5);
      }
    }

    void turnRight() {
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(BACKWARD);
      motor4.run(BACKWARD);
      delay(500);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
    }

    void turnLeft() {
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
      delay(500);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
    }

body: All of the errors I got were "NewPing does not name a type", "AF_DCMOtor does not name a type" and "motor<> was not declared in this scope". I don't see library includes; at least one for NewPing is needed. I don't know where AF_DCMotor is supposed to be declared but, as it is not declared as a type, it leaves all of the motor<n> undefined. Those are the bulk (if not all) of the errors as the code stands now. Add the missing NewPing library do whatever you need to to define AF_DCMotor.


body: It probably needs a library. Looks like you have some kind of AFDC library and did not use it.


message:
How long should TinyMPU6050.h calibration run for?

I just found a lightweight library for the MPU6050 gyro. Example below.
mpu.Calibrate() never seems to end. I'm keeping it very still. When I take this out, the rest of the code works fine.

[https://github.com/gabriel-milan/TinyMPU6050/blob/master/examples/ArduinoIDE_All_Gets_Example/ArduinoIDE_All_Gets_Example.ino][1]

  [1]: https://github.com/gabriel-milan/TinyMPU6050/blob/master/examples/ArduinoIDE_All_Gets_Example/ArduinoIDE_All_Gets_Example.ino

body:
I feel so sorry about the previous releases of TinyMPU6050. I've just released v0.5.0 that shall soon be available at the Arduino Library Manager index.

The calibration method indeed was messy, so I decided to keep it simple. I also removed dependencies of String objects and Serial stuff and it seems to work pretty fine now.

If you keep having issues with that, please let me know!

The official link to release 0.5.0 follows:
https://github.com/gabriel-milan/TinyMPU6050/releases/tag/0.5.0


message:
Powering Moisture sensor via arduino pin

Can someone help me. I have this [sensor][1]

  [1]: https://nl.aliexpress.com/item/32962429148.html?spm=a2g0s.9042311.0.0.27424c4dxe6M2j

I just connected it to the 3V pin of my arduino only I read online that its better to connect it to a Arduinopin for power so you can put it off when not measuring. How do I do this? Can I just connect it to, let's say D4 and put this to HIGH and LOW or do I need something more. I googled a bit but found all kinds of different solutions. Some even talked about the need to PULLUP and PULLDOWN. whats the best way to do this.

body:
The entire circuit board, including the LM393, power light and it's resistor, uses 2.2 mA at 3.3 VDC (4.12 mA at 5 VDC). Once the comparator is "triggered", the "D0-LED" and it's associated resistor come in to play which bumps the current up to 3.6 mA at 3.3 VDC (7.82 mA at 5 VDC).

I think it would be OK to use `digitalWrite(pin_number, HIGH)` to power the circuit board, then use `digitalWrite(pin_number, LOW)` to turn the power off.


message:
Waking an ESP8266 from Light-Sleep using a signal from MQTT?

**I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?** I am planning to implement a smart switch that would receive messages from a Raspberry Pi to turn off and on, however, I don't want to have to manually hit a button to trigger an external reset (I've seen this done in many examples already). I also don't think it would be efficient for me to just set a timer and have the ESP wake up in intervals. For instance, if I want to have the smart switch turn on an appliance and the PI sends a request over MQTT when the ESP is sleeping... this will do me no good. Curious if anyone has run into this issue before and what recommendations you have.

body:
> I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?

No. The ESP8266 has to be awake to communicate with the MQTT server.

The best you can hope for is a periodic wakeup to connect to the server and check for any new data.  But of course that relies on the data being set to QOS 2 so it keeps trying to be delivered until the ESP8266 is awake to receive it.


message:
Buzzer interfere with thermistor reading

This is how i wired the thermistor and buzzer:

<!-- 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/X9W9C.png)

<!-- End schematic -->

And the code:

    #define RT0 10000
    #define B 3977
    #define R 10000
    float RT, VR, ln, TX, T0, VRT;

    void setup() {
      T0 = 25 + 273.15;
    }

    void loop() {
      VRT = analogRead(A3);
      VRT = (5.00 / 1023.00) * VRT;
      VR = 3.3 - VRT;
      RT = VRT / (VR / R);
      ln = log(RT / RT0);
      TX = (1 / ((ln / B) + (1 / T0)));
      TX = TX - 273.15;
    }

When i connect the buzzer it causes a bit of voltage drop which messes with temperature reading, How can i get a steady temperature reading while having a buzzer in the circuit?

body: Take the regulator output to another analog input. Read that just before you read the thermistor. Use that voltage in your voltage divider calculation. The buzzer activity should be the same (ideally, off) during both readings.


body:
You can use the output of your regulator as the reference voltage for your analog readings. That way, no matter what the voltage you voltage divider for the thermistor uses, the "upper" voltage that the ADC uses is always the same as the thermistor's voltage.

Simply connect the output of the regulator to the `AREF` pin, and set the ADC to use the external voltage reference:

    analogReference(EXTERNAL);

Now you have the range 0-1023 covering 0-3.3V (or whatever the voltage is the regulator is outputting), and because the output of your voltage divider is just a ratio of that voltage, that ratio will *always* be a ratio of 1023, regardless of what the voltage happens to be.

You have, in effect, removed the voltage from the equation. All you are left with is the value as a fraction of 1023, which is then directly proportional to the resistance of the thermistor.


message:
Arduino Mega's auxiliary serial ports

If I am correct, the first two pins (RX/TX) are connected to the USB, and I cannot use the serial monitor and the first RX/TX serial ports at the same time.

But, what about the other 3 auxiliary serial ports? Are they separated? Do each one of them has it's own buffer?

For example: Is it possible to add, let's say, four Bluetooth modules(Let's say HC-05) and use each of them for a different purpose?

body:
You can indeed use a serial monitor on your PC on the Mega's first serial port, in fact you will have to if you are connecting to one on the PC via USB port.. And just as with the Uno, you can connect a TTL serial device (like RS-232 serial, but using logic levels of 0 and +5v instead of [-3v - -25v] and [+3v - +25v] (which most PCs implemented as -12v and +12v).

If you need to connect to a true RS-232 device, you'll need to convert the TTL logic levels to something within the RS-232 spec; -5v and +5v would probably be the easiest.