body:
I'm trying to develop length measuring system and I'm using a industrial rotary encoder as the sensor.

A have decided to use an Arduino external interrupt for connect the encoder. But, Encoder will rotate very fast. I need to calculate PPR(Pulse per revolution) of the encoder according to maximum interrupt frequency of Arduino MEGA.

So, What is the maximum interrupt frequency of Arduino MEGA?

title: High speed rotary encoder with Arduino MEGA

Answers: 0


body:
I got problem in my result where my ADC read cannot give the biggest and the lowest ADC Value if I am using ADS1115. meanwhile, when I am not using ADS1115 I can get the biggest and the lowest ADC Value using a listing program that I use before. Thank u, need for help.

[![Result with ADS][1]][1]

[![Result without ADS][2]][2]

[![Program with ADS[![\]\[3\]][3]][3]]
[![program without ADS][4]][4]

  [1]: https://i.stack.imgur.com/FwF1J.png
  [2]: https://i.stack.imgur.com/IXTX1.png
  [3]: https://i.stack.imgur.com/xCJwC.png
  [4]: https://i.stack.imgur.com/SEMha.png

title: ADS1115, ZMPT101b and Arduino Uno listing program for AC measurement

Answers: 1

body:
The ZMPT101b is a transformer which converts voltage. You can read the output with analog pin.

The ADS1115 is an analog to digital converter. It reads the analog voltage the same way as the analog pin of your Arduino does. The result then can be read over I2C as a register value. You can't read it with analogRead.

So you can use the ADS1115 to convert the analog output of the ZMPT101b.

To read the digital value from the ADS1115 with Arduino, use the Wire library or find a library for the ADS1115. For example [this one][1].

I use ADC121 with Wire library. I initialize it in setup()

      const byte REG_ADDR_RESULT = 0x00;
      const byte REG_ADDR_CONFIG = 0x02;

      // initialize the Wire library
      Wire.begin();
      Wire.setClock(400000);

      // configure the ADC
      Wire.beginTransmission(I2C_ADC121);
      Wire.write(REG_ADDR_CONFIG);
      Wire.write(REG_ADDR_RESULT);
      Wire.endTransmission();

      // set the 'result' register as default
      Wire.beginTransmission(I2C_ADC121);
      Wire.write(REG_ADDR_RESULT);
      Wire.endTransmission();

and then in code I read the value with this function

    unsigned short adcRead() {
      Wire.requestFrom(I2C_ADC121, 2); // request 2 bytes
      byte buff[2];
      Wire.readBytes(buff, 2); // read 2 bytes
      return (buff[0] << 8) | buff[1]; // get the result as 16 bit number
    }

  [1]: https://github.com/adafruit/Adafruit_ADS1X15


body:
I'm using a NodeMCU in one of my projects. The setup is in a remote location. That place doesn't have WiFi so I'm using GPRS (GSM SIM800V) for sensor data collection to my server. Right now I need to update my new firmware to that NodeMCU.

Is it possible do OTA using GPRS (GSM SIM800V)?

title: How to program the nodeMCU through OTA using GPRS?

Answers: 1

body:
Yes, it is possible, but it takes some work on your part.

I recently had to implement OTA updates for the ESP32 over an RS-485 link, and it's actually pretty simple to manage. The hard part (for you) is the communication connection.

Performing an update (assuming the flash is already partitioned and set up right for OTA updates) is a case of "starting" the update, passing the update manager the flash data, then "ending" the update:

1. `Update.begin(size)` - This starts the upgrade process. You need to provide the expected size of the flash data at this point.
2. `Update.write(*data, length)` - Pass a block of flash data to the updater for writing.  An alternative is to read directly from a `Stream` class, which will try and read the number of bytes specified in the `size` parameter to `begin`.
3. `Update.end()` - This will finish it all off and switch the bootloader to load from the new flash. If it worked fine it will return `true`, otherwise, it will return `false`.

Assuming the above worked, you can no reset the board with `ESP.restart()`

For added security you can also pass an MD5 hash of the data to `Update.setMD5(md5)` and the updater will check that the uploaded data matches that MD5 hash.

Of course, all this needs implementing in your program that is running on the target device *before* you try and do any OTA updates. And, of course, you need to arrange the actual upgrade channel to get the commands and data through to the target in the first place.

So:

1. Implement a method of getting the data to the target
2. Implement the updater code
3. Go to the device and upgrade the firmware
4. From that point on you should be able to use OTA updates through your own chosen mechanism.


body:
Im trying do a circuit to measure resistance between Neutral and ground, for this I tried ohm law method i.e., to obtain R = (V/I). Voltage is known value 25 Vac, Current value is measured using ACS712 and tried the coding is given below, I'm getting current value from it, but when I apply ohms law I'm not getting resistance value.Please guide me

    /*
    Measuring AC Current Using ACS712
    */
    const int sensorIn = A0;
    int mVperAmp = 185; // use 100 for 20A Module and 66 for 30A Module

    double Voltage = 0;
    double VRMS = 0;
    double AmpsRMS = 0;

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

    void loop(){

     Voltage = getVPP();
     VRMS = (Voltage/2.0) *0.707;
     AmpsRMS = (VRMS * 1000)/mVperAmp;
     Serial.print(AmpsRMS);
     Serial.println(" Amps RMS");

    }

    float getVPP()
    {
      float result;

      int readValue;             //value read from the sensor
      int maxValue = 0;          // store max value here
      int minValue = 1024;          // store min value here

       uint32_t start_time = millis();
       while((millis()-start_time) < 1000) //sample for 1 Sec
       {
           readValue = analogRead(sensorIn);
           // see if you have a new maxValue
           if (readValue > maxValue)
           {
               /*record the maximum sensor value*/
               maxValue = readValue;
           }
           if (readValue < minValue)
           {
               /*record the maximum sensor value*/
               minValue = readValue;
           }
       }

       // Subtract min from max
       result = ((maxValue - minValue) * 5.0)/1024.0;

       return result;
     }

title: Resistance measurement using loop resistance technique

Answers: 0


body:
this is my very first post in here so I apologise if I am not giving you all the information that I should.

I am creating this topic to ask you help regarding how to control and use the v3 output of my Nodemcu.

I have a script which is working fine to power on and off a led by using one of the GPIO and the ground. However, my project requires to power on a small motor for about 2 seconds and then stop it. If I connect this motor to one of the GPIO and the ground I can control it but it runs very slow. If I connect the motor to the 3V output it goes fine but I can't turn it on or off. The motor requires 3V to run properly. How can I turn it on and off by powering it from that 3V output?

What am I missing?

I have a 4n25 chip which I saw in a video that has been used for a similar project however the vide is in Portuguese and I am not able to follow it properly.

Can please someone advice?

Thank you for your time,

Ade

title: ESP8266 NODEMCU V3, HOW TO USE AND CONTROL V3 OUTPUT POWER

Answers: 1

body:
You cannot control the "V3" output. It's a 3.3V power supply output. Think of it like a battery. It's always on and always giving power.

Instead, you need to add a "switch" to control that power that the ESP8266 can itself control, such as a MOSFET or a motor driver (H-Bridge).


body:
I cannot understand the code of controlling the speed of brushless dc motor using ESP8266 WiFi Module.

 I found it in- https://ubidots.com/blog/speed-control-for-brushless-motors-with-an-esp8266-2/

The part that I cannot understand is-
```arduino

float btof(byte * payload, unsigned int length) {

  char * demo = (char *) malloc(sizeof(char) * 10);

  for (int i = 0; i < length; i++) {

    demo[i] = payload[i];

  }

float value = atof(demo);

  free(demo);

  return value;
}

// Callback to handle subscription

void callback(char* topic, byte* payload, unsigned int length)

{

    value = btof(payload, length);

      value = map(value, 0, 1023, 0, 180);

//Map the 0-100 values from the slider to the 0-180 to use the servo lib.

 ESC.write(value);

//Send the value (PWM) to the ESC

}
```
Please help me with the code!

title: Speed Control of Brushless DC Motor

Answers: 1

body:
 1. `Callback function` must be data send from server to the ESP.
 2. `Payload` is the data byte sent from server.
 3. `Length` is the size of data in bytes.
 4. `BTOF` is basically byte to float converter which converts all the data byte received into single floating variable and return that floating point value.
 5. `ECS.write` must be the function that write the value to the servo motor controller H-bridge IC. It belongs to servo library.
 6. Value range that can be mapped into this ECS.write is between 0-180 so `map` function will use that will convert the `floating point data` received from `btof` function.
 7. Basic definition of `map()` function:

`Map function` maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers.

Syntax:

    map(value, fromLow, fromHigh, toLow, toHigh)

Then `ECS.write(value)` will write that mapped value to servor motor controller H-Bridge.


body:
I'm working on a project where I need 7 analog pins.
I read the datasheet of Ardnuino Uno : 6 analog pins available.
So I decided to use an arduino mega with 16 analog pin available.
Then I saw the arduino nano had 8 analog pins.
But when I read the datasheet, both arduino uno and nano use Atmega328
In my final project, I will not use the board but only the pdip chip (analog pins are from pin number 23 to 28).
Is it possible to "convert" another pin of the pdip to be an analog pin ?

Thank you

title: Arduino nano / uno analog pin

Answers: 2

body:
No, this is not possible. The [datasheet of the ATmega328P][datasheet]
states it has:

> * 8-channel 10-bit ADC in TQFP and QFN/MLF package
> * 6-channel 10-bit ADC in PDIP Package

If you want to use a bare chip, it won't be possible with a PDIP
package.

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf

body: A Nano and some ProMinis have all 8 analog input pins available from the 32-pin TQFP Atmega328P package. An Uno only has 6 of the 8 available in the 28-pin DIP package. Instead of the bare 28-pin DIP, use one of the 32-pin TQFP parts, on a breakout board, or as a packaged 'system' board; a Promini is the 328P with resonator and voltage regulator, connect to it with external FTDI module for programming/debugging; the Nano which goes a step further and adds a USB interface chip.


body:
I got this small code I'm trying things on for like an hour.

    int receivers = 0;
    #if defined(PPM_RECEIVER)
      receivers++;
    #endif

And I just cannot get it working, It keeps returning a "'receivers' does not name a type" on line 4.

title: Basic if endif not working and I'm puzzled

Answers: 1

body: You can't use commands like `receivers++` outside of a function.  That is runtime executable code, and has to be run from inside a function. Global scope doesn't get executed in the same way as code in a function.


body:
Overview:
I am trying to use a switch statement to run different tests. A main menu is displayed on the serial monitor, and then the user is given the option to enter their menu choice in the serial monitor. The menu choice entered in the serial monitor should subsequently run the appropriate case statement.

Issues:
 1. When I enter a choice the case statement for that choice does not run
 2. When I enter a choice my the serial monitor scrolls through my menu 3 times displaying 49, then 13, then 10.

Questions:

 1. Why are my case statements not executing?
 2. Why does the serial monitor scroll three times displaying these random numbers?

    ```
    //////////////PREPROCESSOR DIRECTIVES/////////

    #include <Wire.h>

    /////////////GLOBAL VARIABLES////////////////

    int ADDRESS_SLAVE = 0x08;
    int ADDRESS_VERSION = 0x00;
    int ADDRESS_STATUS = 0x01;
    int ADDRESS_ENABLE = 0x02;
    int ADDRESS_CONFIG = 0x03;
    int ADDRESS_RESTART = 0x04;
    int ADDRESS_STARTUP_STATE = 0X05;
    int ADDRESS_COMPENDISREG1 = 0X07;
    int ADDRESS_COMPENDISREG2 = 0X08;
    int ADDRESS_COMPENDISREG3 = 0X09;
    int ADDRESS_COMPENDISREG4 = 0X0A;
    int ADDRESS_FAULT = 0X0B;
    int ADDRESS_FAULTMASK = 0X0C;
    int ADDRESS_TEST_MODE = 0X0D;

    ////////////SETUP CONDITIONS/////////////////

    void setup()
    {
     Wire.setClock(100000);
     Wire.beginTransmission(byte(ADDRESS_SLAVE));
     Serial.begin(9600);
    }

    ////////////MAIN FUNCTION///////////////////

    void loop()
    {

      int choice = 0;

      int const
                //Clock 100
                CLOCK_FREQ_P = 101,
                CLOCK_FREQ_DIV4 = 102,
                CLOCK_FREQ_DIV8 = 103,
                CLOCK_FREQ_DIV16 = 104,
                CLOCK_FREQ_DIV32 = 105,
                CLOCK_INT_SUPPLY_IBIAS = 106,
                CLK_OK = 107,

                //Bandgap 200
                BG_2p5V = 200,
                BG_MAX_LOAD = 201,
                BG_VBE = 202,
                BG_VP = 203,
                BG_VGATE = 204,
    mainMenu();

       choice = menuChoice();

       switch(choice)
       {
        case CLOCK_FREQ_P :
        {
          Serial.println(F("CLOCK_FREQ_P Not yet built out"));
          while(Serial.available() > 0)
            {
               int choice = Serial.read();
            }

          delay(10000);
        }
        break;

        case CLOCK_FREQ_DIV4:
        {
          Serial.println(F("CLOCK_FREQ_DIV4 Not yet built out"));
        }
        break;

        case CLOCK_FREQ_DIV8:
        {
          Serial.println(F("FREQ_DIV8 Not yet built out"));
        }
        break;

        case CLOCK_FREQ_DIV16:
        {
          Serial.println(F("CLOCK_FREQ_DIV16 Not yet built out"));
        }
        break;

        case CLOCK_FREQ_DIV32:
        {
          Serial.println(F("CLOCK_FREQ_DIV32 Not yet built out"));
        }
        break;

        case CLOCK_INT_SUPPLY_IBIAS:
        {
          Serial.println(F("CLOCK_INT_SUPPLY_IBIAS Not yet built out"));
        }
        break;

        case CLK_OK:
        {
          Serial.println(F("CLK_OK Not yet built out"));
        }
        break;

        case BG_2p5V:
        {
          Serial.println(F("BG_2p5V Not yet built out"));
        }
        break;

        case BG_MAX_LOAD:
        {
          Serial.println(F("BG_MAX_LOAD Not yet built out"));
        }
        break;

        case BG_VBE:
        {
          Serial.println(F("BG_VBE Not yet built out"));
        }
        break;

        case BG_VP:
        {
          Serial.println(F("BG_VP Not yet built out"));
        }
        break;

        case BG_VGATE:
        {
          Serial.println(F("BG_VGATE Not yet built out"));
        }
        break;

        delay(500);
    }

    ////////////////FUNCTIONS/////FUNCTIONS/////FUNCTIONS/////FUNCTIONS///////////////////////////

    //*******************************************
    //**      Function: Main Menu Display
    //**      Passes: nothing
    //**      Returns: nothing
    //*******************************************

    void mainMenu()
    {
      //Prints main menu to the serial monitor
      Serial.println();
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       **         MAIN MENU        **"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println();
      Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
      Serial.println(F("\t\t\t\t\t\t **   Please type in the number of the test you want to run in the command line window at the top of the screen.   **"));
      Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
      Serial.println();
      Serial.println();
      //                                        ******************
      //                                        ***  TOP MENU  ***
      //                                        ******************

      Serial.print(F("\t\t\t CLOCKGEN \t\t\t\t BANDGAP \t\t\t GPIO "));
      Serial.println();
      Serial.print(F("\t\t\t   (1) CLK_FREQ_P \t\t\t   (8) BG_2p5V \t\t\t   (13) GPIO0_PD \t (21) GP1_N_Buff \t (29) GP2_Buff_Max \t  "));
      Serial.println();
      Serial.print(F("\t\t\t   (2) CLK_FREQ_Div_4 \t\t\t   (9) BG_MAX_LOAD \t\t   (14) GPIO0_PU \t (22) GP1_W_Buff \t (30) GP2_Buff_Min "));
      Serial.println();
      Serial.print(F("\t\t\t   (3) CLK_FREQ_Div_8 \t\t\t   (10) BG_VBE \t\t\t   (15) GP0_N_Buff \t (23) GP1_Buff_Max \t (31) GPIO3_PD ") );
      Serial.println();
      Serial.print(F("\t\t\t   (4) CLK_FREQ_Div_16 \t\t\t   (11) BG_VP \t\t\t   (16) GP0_W_Buff \t (24) GP1_Buff_Min \t (32) GPIO3_PU "));
      Serial.println();
      Serial.print(F("\t\t\t   (5) CLK_FREQ_Div_32 \t\t\t   (12) BG_VGATE \t\t   (17) GP0_Buff_Max \t (25) GPIO2_PD \t\t (33) GP3_N_BUFF "));
      Serial.println();
      Serial.print(F("\t\t\t   (6) CLK_INT_Supply_(IBias)\t\t\t\t\t\t   (18) GP0_Buff_Min \t (26) GPIO2_PU \t\t (34) GPIO3_W_BUFF "));
      Serial.println();
      Serial.print(F("\t\t\t   (7) CLK_OK \t\t\t\t\t\t\t\t   (19) GPIO1_PD \t (27) GP2_N_Buff \t (35) GP3_BUFF_Max "));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t\t\t   (20) GPIO1_PU \t (28) GP2_W_Buff \t (36) GP3_BUFF_Min "));
      Serial.println();
      Serial.println();
      //                                        *********************
      //                                        ***  CENTER MENU  ***
      //                                        *********************

      Serial.print(F("\t\t\t VBUS COMPARITOR \t\t\t\t\t\t\t VAC COMPARITOR \t\t ISNS COMPARITOR \t\t TSNS COMPARITOR"));
      Serial.println();
      Serial.print(F("\t\t\t   (37) CLK_FREQ_P \t(47) BG_2p5V \t(57) GPIO0_PD \t\t\t   (61) GP1_N_Buff \t\t  (68) GP2_Buff_Max \t\t   (74) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (38) CLK_FREQ_P \t(48) BG_2p5V \t(58) GPIO0_PD \t\t\t   (62) GP1_N_Buff \t\t  (69) GP2_Buff_Max \t\t   (75) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (39) CLK_FREQ_P \t(49) BG_2p5V \t(59) GPIO0_PD \t\t\t   (63) GP1_N_Buff \t\t  (70) GP2_Buff_Max \t\t   (76) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (40) CLK_FREQ_P \t(50) BG_2p5V \t(60) GPIO0_PD \t\t\t   (64) GP1_N_Buff \t\t  (71) GP2_Buff_Max \t\t   (77) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (41) CLK_FREQ_P \t(51) BG_2p5V \t\t\t\t\t   (65) GPIO0_PD \t\t  (72) GP1_N_Buff \t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (42) CLK_FREQ_P \t(52) BG_2p5V \t\t\t\t\t   (66) GPIO0_PD \t\t  (73) GP1_N_Buff \t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (43) CLK_FREQ_P \t(53) BG_2p5V \t\t\t\t\t   (67) GPIO0_PD \t\t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (44) CLK_FREQ_P \t(54) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (45) CLK_FREQ_P \t(55) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (46) CLK_FREQ_P \t(56) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
      Serial.println();
      Serial.println();
      Serial.println();
      //                                        *********************
      //                                        ***  BOTTOM MENU  ***
      //                                        *********************

      Serial.print(F("\t\t\t QR COMPARITOR \t\t\t ADC \t\t\t MS Driver \t\t\t AC Driver \t\t\t Active Clamp FET \t\t  V10"));
      Serial.println();
      Serial.print(F("\t\t\t   (78) CLK_FREQ_P \t\t  (84) BG_2p5V \t\t  (87) GPIO0_PD \t\t  (96) GP1_N_Buff \t\t  (100) AC_FET_LEAKAGE \t\t   (1400) V10MIN_V10_OK_FAL"));
      Serial.println();
      Serial.print(F("\t\t\t   (79) CLK_FREQ_P \t\t  (85) BG_2p5V \t\t  (88) GPIO0_PD \t\t  (97) GP1_N_Buff \t\t  (101) AC_FET_LEAKAGE_SWEEP"));
      Serial.println();
      Serial.print(F("\t\t\t   (80) CLK_FREQ_P \t\t  (86) BG_2p5V \t\t  (89) GPIO0_PD \t\t  (98) GP1_N_Buff \t\t  (102) AC_FET_RDS_ON"));
      Serial.println();
      Serial.print(F("\t\t\t   (81) CLK_FREQ_P \t\t\t\t\t  (90) BG_2p5V \t\t\t  (99) GPIO0_PD"));
      Serial.println();
      Serial.print(F("\t\t\t   (82) CLK_FREQ_P \t\t\t\t\t  (91) BG_2p5V"));
      Serial.println();
      Serial.print(F("\t\t\t   (83) CLK_FREQ_P \t\t\t\t\t  (92) BG_2p5V"));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (93) CLK_FREQ_P"));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (94) CLK_FREQ_P"));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (95) CLK_FREQ_P"));
      Serial.println();
      Serial.println();
      Serial.println();
      Serial.println();
      Serial.println();
      Serial.println();

    }

    //*******************************************
    //**      Function: menuChoice
    //**      Passes: nothing
    //**      Returns: integer for menu choice
    //*******************************************

    int menuChoice()
    {
      int selection = 0;

      while (Serial.available() == 0);
      {
      selection = Serial.read();
      Serial.print("You entered: ");
      (int)Serial.println(selection, DEC);
      }
      return selection;
    }
    ```

title: Switch statement cases not executing

Answers: 1

body:
I think the issue is with the `menuChoice()` function. Try replacing it with this:
<!-- language-all: lang-cpp -->

    int menuChoice()
    {
      int selection = 0;
      const byte bufferSize = 16;
      char inputBuffer[bufferSize + 1];

      if(Serial.available() > 0){
        // 50 bytes more in compile size using parseInt() vs
        // char buffer and atoi().
        // selection = Serial.parseInt();
        Serial.readBytesUntil('\n', inputBuffer, bufferSize);
        selection = atoi(inputBuffer);
        memset(inputBuffer, 0, sizeof(inputBuffer));
        Serial.print("You entered: ");
        Serial.println(selection, DEC);
      }

      return selection;
    }

Of course, you could use `parseInt()` instead of the `char` buffer and `atoi()`, but the compile size is 50 bytes more.


body: So I want to set up a network of outdoor sensors (temperature and humidity) connected to an Arduino (and at some point a second or third Arduino further away with its own sensors). Then I'd like this Arduino to wirelessly transmit this data to a Raspberry Pi running some sort of server that can receive the data and then upload it to the cloud. I'm assuming WiFi is the best method to do this because of range and the number of devices at once? Would I just have to get each Arduino a WiFi module and what kind of range can I expect from this setup?

title: WiFi or Bluetooth to communicate between several Arduinos and a Raspberry Pi

Answers: 1

body: I would also suggest using WIFI (ESP8266) as you need to create a local network in which all devices will communicate to single host connected to the same network. If range will be issue you can use LORAWAN network for the same. LORAWAN provide high network range and if industrial gateway is used you can connect 10000 nodes(arduino in your case) communicating to the single server at a time.Else WIFI will the good.


body:
I'm trying to connect my NodeMCU to wifi. It isn't finishing because software serial is interrupting it.

Sort of like https://arduino.stackexchange.com/questions/60175/software-serial-conflict-with-wifi-on-esp8266.

Here's my code:
``` lang-c#
#include <SoftwareSerial.h>
#include "ESP8266WiFi.h"

const char* ssid     = "mywifi";
const char* password = "password123";

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

        connectWifi();

        SoftwareSerial pinSerial(1, 3);
        pinSerial.begin(9600);
}

void loop() {
    // send data received from serial port
}

// in separate function so I can reconnect in the loop
bool connectWifi() {
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
                delay(500);
                Serial.print(".");
        }
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println(WiFi.localIP());
        if( WiFi.status() == WL_CONNECTED) {
                return true;
        } else {
                Serial.println("wifi connection failed");
        }
}
```

The console outputs the periods as it's connecting but never prints the IP and instead prints the serial data it received while trying to connect.

Can I delay the activation of the software serial port? Should I use another serial library?

Please don't focus on basic code errors, I'm still learning.

title: Software Serial blocking Wifi Connection

Answers: 0


body:
I am using PT100 (3 Wire) to measure the temperature with Arduino Uno and MAX31865.
I have connected everything perfectly.
Configuration in the code i am using is :

    max1.begin(MAX31865_3WIRE);

And the output is:

**output**

    RTD value: 0
    Ratio = 0.00000000
    Resistance = 0.00000000
    Temperature = -242.02

I am testing it in a room temperature.

My question is , is there any settings or calibration that i need to do, or any other way to test the PT100 sensor, because the temperature is showing correct readings ?

title: PT100 and MAX31865 readings showing wrong

Answers: 1

body:
I nearly have the same problem. I use five of the MAX31865-Boards with 2-Wire Termocouples on an Arduino Nano. Two of the five boards are working perfectly. The other 3 boards show exactly the same wrong behaviour you described. My temperature readings are exactly like yours (-242.02).

But I think I found the reason for the not working ones: The two working boards I bought on Amazon. The other three not working boards I bought on AliExpress. Maybe I (and maybe you too) got really bad fakes from China and they are simply dead :(

*(BTW: If I remove one working board from the SPI bus and read out the temperature with the arduino, I get also the value of -242.02. This value seems to be an error value in the Adafruit MAX31865 library)*

**EDIT: Fixed it with a workaround!Like shown in the picture below, simply remove the wrong component (SMD Capacitor) and create a solder bridge . See comments for more informations!**

Here is a picture of my modification of one chinese board as requested by the comments:

[![Modification of the chinese MAX31865 driver board][1]][1]

(It's not the best solution, but it works. For final using you should get the right filter ferrite and solder it on the board!)

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


body: Let's say we have two buttons - button 1 and button 2. What I need to do is to do something (like turn LED on) when button 1 is press, then button 2 is pressed. I can do it realy simple by just using two boolean variables, but how can we tell button 1 was the first pressed button?

title: Press one button then another?

Answers: 1

body:
A nice solution is to use a state variable. In C/C++ (thus Arduino) you can use an enum variable for that.

    enum EState
    {
      // Button 1 and 2 are not pressed
      NoButtonsPressed,

      // Button 1 is pressed, button 2 is not pressed
      FirstButtonPressed,

      // Both buttons are pressed
      BothButtonsPressed
    };

    EState _state;

    void setup() {
      // put your setup code here, to run once:
      _state = NoButtonsPressed;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      switch (_state)
      {
      case NoButtonsPressed:
        if (digitalRead(1) == HIGH)
        {
          _state = FirstButtonPressed;
        }
        break;

      case FirstButtonPressed:
        if (digitalRead(1) == HIGH)
        {
          // Button 1 is still pressed, ignore second button.
        }
        else if (digitalRead(2) == HIGH)
        {
          // Button 1 is not pressed, button 2 is pressed.
          _state = BothButtonsPressed;
        }
        break;

     case BothButtonsPressed:
       // Switch on LED
       digitalWrite(2, HIGH);

       // Reset state.
       _state = NoButtonsPressed;
       break;

     default:
       // Other state, illegal.
       break;
      }
    }

In every state you can define exactly what needs to be done. Because of the loop function being ran continuously, you just need to handle one state (change) at a time.

Additional notes:

- Your requirements are not fully complete (like when to switch off the LED), probably when button 2 is released (which I don't check for), you can add a new state for this.
- I did not take debouncing of buttons into account; you might need to do this especially if you check for releasing buttons. On the official Arduino website there is a good article about it.
- I haven't tested the sketch.


body:
I'm making a project for school where I'm using flex sensors and converting that into words on an LCD (similar to the signing glove if you're familiar with that).
I ran into a problem since the Arduino I'm using doesn't have enough pins for all of my flex sensors and my LCD monitor.

I'm considering getting another Arduino with more pins but I might not have time to order it since my project is due in a couple of days. I was thinking about connecting two arduinos but I'm not sure if that would work (first year coding/engineering student) Any other suggestions as to how I can create more pins?

Your input is greatly appreciated!

The Arduino I'm using is a sparkfun redboard (it only has 6 analog pins and a separate place to plug in the LCD monitor which I connected to where it says ISP f you look on the link you will see what I'm talking about [SparkFun RedBoard - Programmed with Arduino][1]).

I'm using four flex sensors

[LCD][2]:

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

  [1]: https://www.sparkfun.com/products/13975
  [2]: https://learn.adafruit.com/assets/2358
  [3]: https://i.stack.imgur.com/HBsrR.jpg

title: Ways to add pins in an arduino

Answers: 2

body:
This can be done with the existing board. LCD can be driven by only with the digital pins. Check the below link for the wiring diagram.

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

Since there are 6 Analog pins available, all flex sensors can be easily connected.

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

body:
This seems like a 1602 display. Note there are also I2C modules that connect to a 1602 making it possible to use it with only I2C wires (and VCC/GND).

See [I2C-LCD-interface][1] for a description, although there are many (similar) ones.

For the flex sensors you have 6 analog pins (hope that is enough). If not, than you need an external ADC (analog digital converter). Or connect a second Arduino and use I2C/SPI/Serial to transport the information from one Arduino to Another.

  [1]: https://opencircuit.nl/ProductInfo/1000061/I2C-LCD-interface.pdf


body: I have some issues with network and would like to work with arduino everywhere. I use Tinkercad which is great, but I would like to installit to my laptop and work without using WiFi. I couldn't find any "offline tinkercad" but maybe there are any similar programs where you can program AND write code inside.

title: Tinkercad but offline?

Answers: 1

body:
The best replacement (but keep in mind that Tinkercad is prob the best for code AND hardware sim) would be Yenka. They offer a "block style" language but you can go in depth with the hardware more than most programs.

Here is a ref image:
[![enter image description here][1]][1]

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


body:
I was testing and debugging a code I wrote for a robot with 3 stepper motors on  (**Arduino Uno + CNCShield V3 + a4988 stepper drivers**). I want to disable drivers at will. so I bypassed EN pin on 2 of a4988s to pin12 and pin13 of Arduino. (by defalut all EN pins of drivers are are connected to pin8 ) everything was ok but suddenly the Reset button is not working and I can't upload new codes to Arduino! I get this error:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
    .
    .
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83
    Problem uploading to board.

but Arduino still is working with the last code that was uploaded to it!!! have I fried my Arduino? and Why is this happening?[![enter image description here][1]][1]

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

title: Reset Button not working + Can't Upload code , What is wrong?

Answers: 1

body:
Try manually resetting the board:

 - Before uploading, run Verify.
 - Hold the reset button and click Upload.
 - Release the reset button.

If that worked, your board's reset isn't fried, it just isn't receiving a reset via the serial cable. If it failed, either part of the board or MCU may be damaged; something attached to the board may be inhibiting the reset signal; or the software may have disabled the board's reset pin. In the latter case, see the Arduino StackExchange article, [How do I repurpose Arduino's reset button][1], for how this can happen and how to undo it if it has.

> Is here anything wrong with using pins 12 and 13?

I'm not familiar with stepper driver, but at a quick glance at its data sheet, and it's logic being 3.3v & 5 v compatible, I don't see any problem with connecting any of its logic to any of Arduino's logic pins (almost all of them). Since the driver also has a motor drive-voltage input for driving your motors, accidentally connecting an Arduino pin to a driver pin (or anything else) carrying the drive-voltage could - probably would - damage at least the connected pin driver in the MCU, and possibly other parts of it as well.

If your Arduino has a socketed Atmega chip, and since you already know another Arduino works as you expect it to, replacing the Atmega chip will be the quickest, cheapest & easiest fix. Just go over your wiring and make sure no motor drive voltages are connected to the Arduino board.

  [1]: https://arduino.stackexchange.com/questions/32378/how-do-i-repurpose-arduinos-reset-button


body:
I am very newbie using arduino. I get a EVB SIM7600 TTL 3V and I am trying to test it using a arduino Due.
I need a help please, my simple code doesnt work.
The serial monitor only show zeros. The baudrate default for SIM7600 is 115200bps. I insert a simcard and then write AT command in serial monitor, for example ATI... I received zero

Here is my code and photo of connection.

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

```

void setup() {

  Serial.begin(115200);
  Serial.println("Testing GSM SIM7600");
  Serial1.begin(115200);
  delay(100);

}

void loop() {

  if(Serial1.available())
  {
    Serial.println(Serial1.read());
  }

  if(Serial.available())
  {
    Serial1.write(Serial.read());
  }

}
```

  [1]: https://i.stack.imgur.com/K8ESg.jpg
  [2]: https://i.stack.imgur.com/HT693.jpg
  [3]: https://i.stack.imgur.com/5Qy8F.jpg

title: problem serial hardware sim7600 arduino due

Answers: 0


body:
In my Arduino project I want to compute the SHA256 hash of a string and store the result to a string, and do this recursively many times (i.e. compute hash of hash of hash etc...). So my goal is to have a *reliable* function as follows:
<!-- language-all: lang-cpp -->

    String h(String input) {
    ...
    return output;
    }

where for example h("abc") would return "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".

I downloaded this [library][1]
(from Tools->Manage libraries, it is also in [github][2]) and then ran the example in [TestSHA256.ino][3] which passes all the checks. However I'm stuggling to make my function work since the library doesn't have a specific example on how to compute and return a SHA256 hash.

I have been looking in function testHash_N() in TestSHA256.ino, which appears to create a hash (from struct TestHashVector data) and compare it with the precomputed hash (from struct TestHashVector hash[]).

The hash seems to be computed in lines 89-96 in TestSHA256.ino.  I just want to take the actual hash string result, so for testVectorSHA256_1  in the example, I would need to have a string = "ba7816bf....15ad" as the result.

I understand that this is related to memory referencing in Arduino but I'm not experienced so I'd be grateful if you helped me with this.

EDIT: My code snippet so far is as follows, but it doesn't output the correct hash..

    #include <Crypto.h>
    #include <SHA256.h>
    #include <string.h>

    #define HASH_SIZE 32
    #define BLOCK_SIZE 64

    char hex[256];

    char *hashvalue;

    SHA256 sha256;

    byte buffer[128];

    char *btoh(char *dest, uint8_t *src, int len) {
      char *d = dest;
      while( len-- ) sprintf(d, "x", (unsigned char)*src++), d += 2;
      return dest;
    }

    char* h(Hash *hash, char* hashvalue)
    {
        size_t size = sizeof(&hashvalue);
        size_t posn, len;
        size_t inc = sizeof(&hashvalue);
        uint8_t value[HASH_SIZE];

        hash->reset();
        for (posn = 0; posn < size; posn += inc) {
            len = size - posn;
            if (len > inc)
                len = inc;
            hash->update(&hashvalue + posn, len);
        }
        hash->finalize(value, sizeof(value));

        return(btoh(hex, value, 32));
    }

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

        bool tmp;
        char *testvalue = "abc";
        Serial.println(h(&sha256,*testvalue));

    }

    void loop()
    {
    }

  [1]: https://rweather.github.io/arduinolibs/classSHA256.html
  [2]: https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto
  [3]: https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/examples/TestSHA256/TestSHA256.ino

title: Compute SHA256 of string and output to string

Answers: 2

body:
The main trick is to understand how the Arduino String class works. You can find the source code in your installation of the Arduino IDE or on github.

The basic pattern you are looking for is:

    String h(String& input) {      // Pass String by reference to avoid copying
      char output[OUTPUT_MAX];
      char* data = input.c_str();  // Access to internal buffer
      ...
      return String(output);       // Return a String object of the output
    }

Cheers!

body:
I suggest the following function. That replaces a string by its hash.
It's done in place in order to save memory. Make sure the buffer you
give it is at least 65 bytes long. **Warning**: not tested.

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

    #include <Crypto.h>
    #include <SHA256.h>

    #define HASH_SIZE 32

    SHA256 sha256;

    /*
     * Replace a string by its hash, in place.
     * `data' should point to a buffer at least 65 bytes in length.
     */
    hash_in_place(char *data)
    {
        uint8_t value[HASH_SIZE];

        sha256.reset();
        sha256.update(data, strlen(data));
        sha256.finalize(value, sizeof(value));

        // Convert to hex into the original buffer.
        data[0] = '\0';
        for (size_t i = 0; i < HASH_SIZE; i++) {
            data += sprintf("x", value[i]);
        }
    }


body:
I'm trying to make a quick proof of concept of two trinket M0s talking to each other via their RX and TX pins and I'm not able to get it working.

I uploaded sender and receiver sketches to two trinkets:

```cpp
//sender.ino
char state[10] = "hello";

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

void loop()
{
    Serial.write(state, 5);
    delay(1000);
}

```

```cpp
//receiver.ino
char state[10];

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

void loop()
{
    Serial.println("reading bytes");
    Serial.readBytes(state, 10);
    Serial.println(state);
    delay(1000);
}
```

After the uploads I wired the two trinkets together, jumping the RX of the first to the TX of the other and TX of the first to the RX of the other. I also connected their grounds to have a common ground.

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

I plugged the sender into a battery and the receiver into my computer. The problem I'm running into is that when I look at the serial monitor for the receiver instead of getting the expected "hello" I'm getting broken strings of "TestingOpen":

[![serial output][2]][2]

I double checked [the pinout diagram and guide for the Trinket M0](https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino/pinouts) to make sure I was using the correct RX/TX pins (pin 3 for RX, 4 for TX) and it all seems fine but obviously something is still going wrong.

Anyone know what I'm missing or misunderstanding?

  [1]: https://i.stack.imgur.com/mUW8N.jpg
  [2]: https://i.stack.imgur.com/JyFj6.png

title: Getting two trinkets to talk to each other via the serial pins

Answers: 1

body:
1) you should use `if (Serial.available())` before starting to read with readBytes. now you print random memory

2) readBytes is blocking. it waits for the next character until a timeout. default timeout is 1 second. after "hello" was received it waits a second. you could use readBytesUntil and some 'separator' character for example '\n' (new line)

3) readBytes returns the count of bytes read. you should use it to terminate the buffer

    void loop()
    {
      if (Serial.available()) {
        Serial.println("reading bytes");
        size_t l = Serial.readBytesUntil('\n', state, 10);
        state[l] = 0;
        Serial.println(state);
      }
    }


body:
I am new to Arduino prototyping. I bought an Arduino Automatic Smart Plant Watering Kit 2.0 thinking it was a shield to use with my Arduino Uno WIFI Rev 2.  However, it turns out to be a specially designed Arduino board with all of the components integrated together.

While the system works as designed, my goal is to stream the data to IBM Watson Studio, or some other third-party SaaS.

I welcome feedback to understand how it might be possible to integrate the ESP8266 WIFI module using either the I2C or Serial interface. Here is the sample code: [https://www.elecrow.com/download/watering_kit.zip][1] I used a Raspberry Pi to get access to the data and use it in a web/mobile application but I'd like to eliminate this element, if possible. [![enter image description here][2]][2]

  [1]: https://www.elecrow.com/download/watering_kit.zip
  [2]: https://i.stack.imgur.com/6quof.jpg

title: How would you add Arduino WiFi Module using I2C or serial interface?

Answers: 1

body:
You would connect the ESP8266 to the serial port.  The normal way of working with an ESP98266 is to issue AT command (like an old Hayes modem) through a serial connection. Since you have one of those available on your board it is a simple matter to just wire it directly to it.

Just follow any of the myriad of ESP8266 + Arduino tutorials, substituting the pins in the examples for your serial pins, and use the `Serial1` object instead of the `SoftwareSerial` class that you have to use on an Uno that lacks extra serial ports.


body:
So basically I have a circuit with a phototransistor, and want to convert the phototransistor value into a PWM signal that can control the speed of the motor. The code I came up with is below, however it does not work. What have I done wrong in my code? I am using an l293d chip.

    int photoTran = A1;
    int reading = 0;
    int forward=2;
    int backward=3;
    int motorspeed=0;

    void setup(){
      pinMode(photoTran,INPUT);
      Serial.begin(9600);
      pinMode (backward, OUTPUT);
      pinMode (forward, OUTPUT);
    }

    void loop(){
      lcd.setCursor(0,0);
      reading = analogRead(photoTran);
      lcd.print(reading);
      lcd.print("  ");
      delay(100);
    {
      if (reading<30){
        digitalWrite(backward,HIGH);
        digitalWrite(forward,LOW);
        motorspeed = map(reading, 30, 1023, 0, 255);
        analogWrite(backward,motorspeed);
      }
      else {
        digitalWrite(backward,LOW);
        digitalWrite(forward,HIGH);
        motorspeed = map(reading, 30, 400, 0, 255);
        analogWrite(forward,motorspeed);
      }
      }
    }

title: DC motor phototransistor control

Answers: 2

body:
`analogRead()` returns an integer between 0 and 1023. Using 30 and 400 in the `map()` function, then passing in a value outside of that range will cause strange results. Here is a sketch to illustrate my point.

    void setup(){

      Serial.begin(9600);

      // Prints -20 to 684
      for(int i = 0; i < 1024; i++){
        Serial.println(map(i, 30, 400, 0, 255));
      }
      Serial.println();

      // Prints -7 to 255
      for(int i = 0; i < 1024; i++){
        Serial.println(map(i, 30, 1023, 0, 255));
      }
      Serial.println();

      // Prints 0 to 255
      for(int i = 0; i < 1024; i++){
        Serial.println(map(i, 0, 1023, 0, 255));
      }
    }

    void loop(){}

body:
If you are using l293d you must control the voltage on its ENABLE PIN rather than controlling it on other INPUT PINS (l293d). Here is simple tutorial on controlling the Motor using L293d. [here](http://www.ardumotive.com/how-to-use-the-l293d-motor-driver-ic-en.html).

And @VE7JRO is right about `map()` function as your are passing the values that are out of range please take care of that part as well.


body:
I have been playing with this code for some time now, I am able to show the results in an 16X2 LCD display, but I am not able to do it in an OLED.

here is the code

        #include <SPI.h>
        #include <Wire.h>
        #include "U8glib.h"  //Library for display

        U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

        int index = 0; //size of array
        const int number_of_readings = 200; //total number of readings arduino takes before it averages
        const int current_zero = 510; //initial value of current from arduino with 0 amps
        int current_reading[number_of_readings]; //create array for current_reading
        int voltage_reading[number_of_readings]; //create array for voltage_reading

        float R1=30000; //resistance of R1 in voltage sensor
        float R2=7500; //resistance of R2 in voltage sensor
        float current_average = current_zero; //initial value of current average
        float current_total = 0; //initial value of current_total
        float voltage_average = 0; //initial value of voltage_average
        float voltage_total = 0; //initial value of voltage_total

        int x = 0;
        int row = 0;
        float voltage = 0.1;

          void setup() {
           Serial.begin(9600);
           pinMode(A4,INPUT_PULLUP);
           pinMode(A5, INPUT_PULLUP);
          }

          void draw(void) {
           u8g.setFont(u8g_font_fub14r);
           {

           u8g.drawStr(0, 20, "V: ");
       u8g.drawStr(0, 40, "A: ");
       u8g.drawStr(0, 60, "Watt: ");
       u8g.setPrintPos(58,20);
       u8g.print( Bat_Volt,2);
       u8g.println("V");
       u8g.setPrintPos(58,40);
       u8g.print( current,0);
       u8g.println("mA");
       u8g.setPrintPos(58, 60);
       u8g.print( power ,1);

        }
        }

         void loop() {
          voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
          voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
          current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
          current_total = current_total + current_reading[index]; // add current to current_total
          index = index + 1;

          if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
            current_average=current_total/number_of_readings;
            voltage_average=voltage_total/number_of_readings;
            Serial.print("Current average=");
            Serial.print(current_average);
            Serial.print("   Voltage average=");
            Serial.println(voltage_average);
            current_total=0;
            voltage_total=0;
            index=0;

          }

          float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
          float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
          float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
          float power = (voltage*current); //calculate power

         u8g.firstPage();
          do {
            draw();
          } while( u8g.nextPage() );

        }

The function of the code is to read data from a "ACS712 - 30A Range Current Sensor Module" and a "Voltage Detection Sensor Module".
Display is a "0.96 inch 128x64 OLED Display Module - SPI/I2C - 7 Pin ", it is converted to I2C, and working with other codes.
Board : Arduino Uno
Max input voltage will be 12.8V, DC.
The code is supposed to display the voltage on top, ampere in the middle, and watt usage at the bottom.
But it is not working when edited for OLED display.

Someone please make this a working code.
I am new to C+ and coding , so need detailed help.

Here is the code that worked with 16X2 LCD

    #include <LiquidCrystal.h>
    #include <Wire.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    /*The circuits
     * LCD RS pin to digital pin 12
     * LCD enable pin to digital pin 11
     * LCD D4 pin to digital pin 5
     * LCD D5 pin to digital pin 4                                                             21333333
     * LCD D6 pin to digital pin 3
     *
     * LCD D7 pin to digital pin 2
     * LCD R/W pin to ground
     * 10K resistor
     * ends to +5V and ground
     * wiper to LCD VO pin (pin 3)
     */

    byte lightning[8] = {
      B00001,
      B00110,
      B01100,
      B11000,
      B00011,
      B00110,
      B01100,
      };

    int index = 0; //size of array
    const int number_of_readings = 200; //total number of readings arduino takes before it averages
    const int current_zero = 510; //initial value of current from arduino with 0 amps
    int current_reading[number_of_readings]; //create array for current_reading
    int voltage_reading[number_of_readings]; //create array for voltage_reading

    float R1=30000; //resistance of R1 in voltage sensor
    float R2=7500; //resistance of R2 in voltage sensor
    float current_average = current_zero; //initial value of current average
    float current_total = 0; //initial value of current_total
    float voltage_average = 0; //initial value of voltage_average
    float voltage_total = 0; //initial value of voltage_total

    void setup (){
      Serial.begin (9600);
      lcd.begin(16,2); // size of LCD
      lcd.createChar(6,lightning); //create charecter named lightning

      //STARTUP MESSAGE
      lcd.setCursor (3,0); //set cusror to row 0, column 3
      lcd.print(" "); //lcdprint
      lcd.print("Arduino"); //lcdprint
      lcd.setCursor(1,1); //set cursor to row 1, column 1
      lcd.write(6); //lcd write charecter 6 (lightning bolt)
      lcd.print("Power Meter"); //lcd.print
      lcd.write(6); //lcd write charecter 6 (lightning bolt)
      delay(5000); //delay by 5 seconds
      lcd.clear();  //clear lcd screen
      }

    void loop() {
      voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
      voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
      current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
      current_total = current_total + current_reading[index]; // add current to current_total
      index = index + 1;

      if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
        current_average=current_total/number_of_readings;
        voltage_average=voltage_total/number_of_readings;
        Serial.print("Current average=");
        Serial.print(current_average);
        Serial.print("   Voltage average=");
        Serial.println(voltage_average);
        current_total=0;
        voltage_total=0;
        index=0;

      }
      float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
      float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
      float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
      float power = (voltage*current); //calculate power

      lcd.clear(); //print voltage, current, and power values to LCD screen
      lcd.setCursor(0,0);
      lcd.print(voltage);
      lcd.print("V");

      lcd.print (" ");
      lcd.print(current);
      lcd.print("A");

      lcd.setCursor(0,1);
      lcd.print(power);
      lcd.print("W");
      delay(1);

    }

title: Display not showing output - Arduino Wattmeter

Answers: 1

body:
In your Sketch

    void draw(void)
    {
       u8g.setFont(u8g_font_fub14r);
       u8g.drawStr(0, 20, "V: ");
       u8g.drawStr(0, 40, "A: ");
       u8g.drawStr(0, 60, "Watt: ");
       u8g.setPrintPos(58,20);
       u8g.print( Bat_Volt,2);
       u8g.println("V");
       u8g.setPrintPos(58,40);
       u8g.print( current,0);
       u8g.println("mA");
       u8g.setPrintPos(58, 60);
       u8g.print( power ,1);
    }

**current**, **power**, **Bat_Volt** are local variables define in `loop` function. **Bat_Volt** in not even defined in your sketch that's why they are not printing anything in `draw` function.

Initialize then as `global variable` in your sketch and in place if **Bat_Volt** you had use voltage here ` float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read` in your sketch.

Correct that to.

Your code after edit:

    #include <SPI.h>
    #include <Wire.h>
    #include "U8glib.h"  //Library for display

    U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

    int index = 0; //size of array
    const int number_of_readings = 200; //total number of readings arduino takes before it averages
    const int current_zero = 510; //initial value of current from arduino with 0 amps
    int current_reading[number_of_readings]; //create array for current_reading
    int voltage_reading[number_of_readings]; //create array for voltage_reading

    float R1=30000; //resistance of R1 in voltage sensor
    float R2=7500; //resistance of R2 in voltage sensor
    float current_average = current_zero; //initial value of current average
    float current_total = 0; //initial value of current_total
    float voltage_average = 0; //initial value of voltage_average
    float voltage_total = 0; //initial value of voltage_total
    float voltage = 0.0,current_mV = 0.0,current = 0.0,power = 0.0;

    int x = 0;
    int row = 0;
    float voltage = 0.1;

      void setup() {
       Serial.begin(9600);
       pinMode(A4,INPUT_PULLUP);
       pinMode(A5, INPUT_PULLUP);
      }

      void draw(void) {
       u8g.setFont(u8g_font_fub14r);
       u8g.drawStr(0, 20, "V: ");
       u8g.drawStr(0, 40, "A: ");
       u8g.drawStr(0, 60, "Watt: ");
       u8g.setPrintPos(58,20);
       u8g.print( voltage,2);
       u8g.println("V");
       u8g.setPrintPos(58,40);
       u8g.print( current,0);
       u8g.println("mA");
       u8g.setPrintPos(58, 60);
       u8g.print( power ,1);
    }

     void loop() {
      voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
      voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
      current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
      current_total = current_total + current_reading[index]; // add current to current_total
      index = index + 1;

      if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
        current_average=current_total/number_of_readings;
        voltage_average=voltage_total/number_of_readings;
        Serial.print("Current average=");
        Serial.print(current_average);
        Serial.print("   Voltage average=");
        Serial.println(voltage_average);
        current_total=0;
        voltage_total=0;
        index=0;

      }

      voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
      current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
      current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
      power = (voltage*current); //calculate power

     u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );

    }


body:
Sorry if this is a dumb question, I'm new to Arduinos. I'm planning to use a MOVI voice shield with SparkFun's RedBoard Turbo (3.3v). The RedBoard Turbo requires a power supply under 6VDC, but the MOVI website recommends a power supply of 9VDC to the Arduino, because the MOVI can't have its own power supply. Will this destroy my RedBoard? Or is this safe and just something you have to do when using shields? Thank you.

The product website says: "A 7V to 16V 500mA external power supply that powers MOVI™ through the Arduino board. The power consumption of both boards is just above what the USB port can provide. If you don't have already one, this 9V adapter from Adafruit will work perfectly."

title: Power supply while using a shield

Answers: 1

body:
Although I have not used either SparkFun's RedBoard Turbo or the MOVI voice shield, reading the specifications, which you can find on their respective web sites, it would appear that they have incompatible power requirements.
The SparkFun's RedBoard Turbo board web page says

*The barrel jack connection on the RedBoard Turbo has a lower input voltage than most Arduino development boards. Make sure that you are using a power supply below 6V. Please be aware that the RedBoard Turbo is also a 3.3V device and not a 5V one like the original RedBoard.*

Whilst the MOVI voice shield PDF manual (page 7) says

*What you don’t see in Figure 1 is a power supply jack. MOVI is powered through the
Arduino board that needs to be powered using an external power supply. The external
power supply should provide between 7V and 16V and at least 500mA current. During tests
we usually used either 9V or 12V. Battery packs with this specification work as well.*

So the one needs less than 6V whilst the other more than 7V. I don't know if you can break the power connection between the two boards and feed the MOVI from a separate supply (9V is very common in the Arduino world) or you may have to swap your SparkFun for an Arduino that runs on 5V and uses a 9V supply.

The gotcha is that Arduino boards, their clones and code compatible boards such as the ESP32 etc fall into 2 different groups, those that run on 3.3V and those that use 5V, and you must be very careful you don't over voltage the latter.

I haven't delved into the specifications further, but you will almost certainly find that the logic levels used by the two boards are also incompatible. One will be using 0 & 5V whilst the other 0 & 3.3V. Connecting a 5V logic output to a 3.3V logic input is not conducive to long life and happiness for the latter.


body:
I started a project where I wanted to send sensor data from one arduino to another and let this 2nd Arduino send the data to a tablet to visualize sensordata like speed, temperature etc.

I wanted to send this in intervalls so UDP would be my way to go. I used the sketches which were provided from the Arduino software which worked well for a while. But after relocating to a new place it doesn't seem to work and I do not know why - I readjusted IP's, Ports and resetted my router.

This is my UDPWrite

    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    #include "dht.h"
    #define dht_apin A0 // Analog Pin sensor is connected to
    dht DHT;
    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 178);
    IPAddress IP_Remote(192, 168, 1, 177);
    IPAddress Port_Remote(8887);

    unsigned int localPort = 8887;      // local port to listen on

    // An EthernetUDP instance to let us send and receive packets over UDP

    EthernetUDP Udp;

    void setup() {

      // start the Ethernet and UDP:
      Serial.begin(9600);
      Ethernet.begin(mac,ip);

      Udp.begin(localPort);

      Serial.println(Ethernet.localIP());

    }

    void loop() {

      DHT.read11(dht_apin);

      Udp.beginPacket(IP_Remote, Port_Remote);
        Udp.write("hello");
        Udp.write("Current humidity");
        Udp.endPacket();

             Serial.println("Test");

        delay(2000);//Wait 2 seconds before accessing sensor again.

    }

This is my UDPRead

    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 177);

    unsigned int localPort = 8887;      // local port to listen on

    // An EthernetUDP instance to let us send and receive packets over UDP
    EthernetUDP Udp;

    char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

    void setup() {
      // start the Ethernet and UDP:

      Serial.begin(9600);
      Ethernet.begin(mac,ip);
      Udp.begin(localPort);
      Serial.print(Ethernet.localIP());
    }

    void loop() {

      int packetSize = Udp.parsePacket();
      if(packetSize)
      {
          Serial.println("Test");
    Serial.print("Received packet of size ");
        Serial.println(packetSize);
        Serial.print("From ");
        IPAddress remote = Udp.remoteIP();
        for (int i =0; i < 4; i++)
        {
          Serial.print(remote[i], DEC);
          if (i < 3)
          {
            Serial.print("Test");
          }
        }
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        // read the packet into packetBufffer
        Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
        Serial.println("Contents:");
        Serial.println(packetBuffer);
    }
    }

This is what Wirehsark shows:
[![enter image description here][1]][1]

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

eceived.

The Arduinos are connected to my Switch Port5 and Port6 which are mirrored to Port8 to which I am connected via Notebook.

After a few tests, I do not seem to get into my

    int packetSize = Udp.parsePacket();

    if(packetSize) {

statement for a reason I cannot yet grasp. Udp.parsePacket should receive the UDP package from 192.168.1.178

I can Ping the .178 but not the .177.
I changed cables, ports, IPs, Switch and even the Arduinos. So I would think that the problem is code based.

Thank you very much for your help.

title: UDP Packet not receiving

Answers: 0


body:
I am building a weather station with an Arduino slave (dedicated to a rain gauge - depicted below as a reed switch) and a NodeMCU master with some additional sensors.

[![Arduino slave NodeMCU master][1]][1]

One such sensor, a BMP280 uses D1 and D2 as SCL and SDA, while slave control is using D3 and D4 for communication with Arduino.

When I enable `Wire.begin` for slave communication, my BMP280 readings go nuts
<!-- language-all: lang-cpp -->

 #include <Adafruit_BMP280.h>

 #define BMP_SCK 13
 #define BMP_MISO 12
 #define BMP_MOSI 11
 #define BMP_CS 10

 Adafruit_BMP280 bmp;

 // masterSlave
 #include <Wire.h>
 #define I2CAddressESPWifi 8
 ...

 void setup() {

  if (!bmp.begin()) {
   Serial.println("Could not find a valid BMP280 sensor, check wiring!");
   while (1);
  }

  // masterSlave - generates problem with BMP280...
  Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

> BMP280 Temp = -136.42 *C

> Pressure = 125136.25 Pa

as opposed to this reading when Wire.begin is commented out.

  // COMMENTED OUT FOR DEBUGGING
  //masterSlave - generates problem with BMP280...
  //Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

> BMP280 Temp = 20.01 *C

> Pressure = 93464.36 Pa

I attempted setting D3 and D4 to LOW while reading from BMP280, but it had no effect on readings.

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

title: I2C interference SENSOR(SCL+SDA) and MasterSlave comm

Answers: 3

body:
The Adafruit BMP280 library uses the Wire library. It calls begin() at default pins (D1, D2). And then you begin() the same Wire object at different pins. From that moment the BMP280 library can't communicate with the sensor.

The I2C (a.k.a. TwoWire or Wire) is a bus. Many devices can be wired to the same pair of pins. They must listen on different addresses. So wire both devices to the D1, D2 and use in slave Arduino an address different then the address of the sensor.

The esp8266 and the sensor are 3.3 V devices. The Uno is a 5 V device. You should use logic level conversion on SDA/SCL to Uno.

body: As per your descriptions, I'm answering here. There is a fact we forget about the load capacitance calculation for selecting I2C pull-ups. It's calculated when more than one slave and variant to distance. Check the jumpers and for pullups try 10k or 4.7K or better you can calculate. It's better to provide a small delay after the wire.begin() function to stabilize the module

body:
The solution I implemented uses the BMP280 sensor in SPI mode, connected as follows:

[![Breadboard scheme][1]][1]

with this code before `setup`

    #include <Adafruit_BMP280.h>
 #define BMP_SCK D5
 #define BMP_MISO D8
 #define BMP_MOSI D6
 #define BMP_CS D7

 //Adafruit_BMP280 bmp; // I2C
 //Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
 Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

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


body:
I am trying to make an DFRobot Wifi Bee sleep periodically. The first run executes fine, but after the wakeup a lot of gibberish is shown in the serial monitor. I changed to baud rate to 74880 to see what was going on.

    void setup() {
      Serial.begin(74880);
      Serial.setTimeout(2000);
      while (!Serial) { }
      Serial.println("Started.");
      delay(5000);
      Serial.println("Going to sleep.");
      delay(10);
      ESP.deepSleep(10e6);
    }
    void loop() { }

If I short-circuit D0 and RST, I get the following output

    18:28:25.250 -> Going to sleep.
    18:28:54.197 ->
    18:28:54.197 ->  ets Jan  8 2013,rst cause:5, boot mode:(3,7)
    18:28:54.197 ->
    18:28:54.197 -> ets_main.c

Indicating that both GPIO0 and GPIO2 are high (which they should) and the cause of reset is power on and hardware watchdog reset.

A similar question has already been asked and answered https://arduino.stackexchange.com/questions/61770/esp-01-not-waking-correctly-up-after-deep-sleep, but my issue is different, since I get the correct first boot parameter = 3 (both GPIO0 and GPIO2 are high)

I read here https://www.esp8266.com/viewtopic.php?f=6&t=8386#sthash.82ae9lvh.dpuf that the second boot parameter means

    7 SDIO HighSpeed V2 IO Uart1 Booting
    6 SDIO LowSpeed V1 IO Uart1 Booting
    5 SDIO HighSpeed V1 IO Uart1 Booting
    4 SDIO LowSpeed V2 IO Uart1 Booting
    3 FLASH BOOT
    2 Jump Boot
    1 UART Boot
    0 Remapping

I believe that I must change something to receive `boot mode:(3,3). If I remove the wire from GPIO16 to RST, I get almost the same result

    18:41:25.250 -> Going to sleep.
    18:41:54.197 ->
    18:41:54.197 ->  ets Jan  8 2013,rst cause:5, boot mode:(3,0)
    18:41:54.197 ->
    18:41:54.197 -> ets_main.c

So now a Remapping occurs (or?).

I am running the module using an FDTI USB connector from SparkFun.

Any help is appreciated.

title: ESP8266 remapping or UART boot

Answers: 0


body:
The [`hid_keyboard`][1] example sketch shows how to send ASCII characters, but how can I send non-ASCII codes like the `F1` key, or keys with shift/control modifiers?

  [1]: https://github.com/adafruit/Adafruit_nRF52_Arduino/tree/master/libraries/Bluefruit52Lib/examples/Peripheral/hid_keyboard

title: How do I send non-ASCII keys over the BLE HID connection using an Adafruit nRF52 Feather?

Answers: 1

body:
Yo can use the `keyboardReport()` function to send key-codes with modifiers. Here is an example that will send an `!` by sending the keycode for `1` plus a shift key modifier...

        // The keyboardReport() function takes an array of 6 keycodes. From what I can tell, it does not
        // press the keys consecutively,. it presses them simultainiously.

        // Here we only want to send one code, so we back-fill the array with HID_KEY_NONE

        uint8_t keycodes[6] = { HID_KEY_1, HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE };
        blehid.keyboardReport( KEYBOARD_MODIFIER_LEFTSHIFT , keycodes );

        // This release seems to be required. Without it, the last pressed key just repeats forever.
        blehid.keyRelease();

The possible modifiers are listed here...
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L188

...and the possible keyscodes are listed here..
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L212

Unfortunately the `hid_keycodes` example does not compile, but bere is a ready-to-run example sketch showing how to send keycodes directly...

https://gist.github.com/bigjosh/5d8575f26988228dcf9d40c3795d0928


body:
I am missing something fundamental using RTClib.
When I use the rtc.adjust function to change the time in the RTC, I cannot get the updated time from the RTC, just increments a fixed time. I have searched for examples for what I need, and the same few samples of code keep getting quoted.

I want my code to set the RTC at compile to the system time, which it does,
then in the Loop I want to increment the hour.  In reality I will use a button for this, but for now I am just trying to understand how DateTime now = rtc.now and rtc.adjust work.  How to write to the RTC, how to read it back. I am missing something regarding these variables.

Two version of my code.  One with output showing the clock working, and one where the output is static, just increments the hour.

**This one works:**

    #include <RTClib.h>
    #include <Wire.h>
    int ArduinoHour;
    int ArduinoMin;
    int ArduinoSec;
    RTC_DS1307 rtc;

    void setup()
    {
      Serial.begin(250000);
      Wire.begin();  //sets up the I2C
      rtc.begin();   //initializes the I2C to the RTC

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
      }
        if (rtc.isrunning()) {
        Serial.println("RTC IS running!");
        rtc.adjust(DateTime(__DATE__, __TIME__));
      }
    }
    void loop()
    {
      DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

      ArduinoHour = now.hour();
      ArduinoMin = now.minute();
      ArduinoSec = now.second();

      Serial.print("AT TOP");
      Serial.println();
      Serial.print("RTC Time");
      Serial.println();
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      Serial.print("Arduino Time");
      Serial.println();
      Serial.print(ArduinoHour, DEC);
      Serial.print(':');
      Serial.print(ArduinoMin, DEC);
      Serial.print(':');
      Serial.print(ArduinoSec, DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      //RTC increments when these are commented out. Does not when active
      //ArduinoHour = ArduinoHour +1;
      //rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

    }

Here is the output.  Looks fine:

    RTC IS running!
    AT TOP
    RTC Time
    11:38:3

    Arduino Time
    11:38:3

    AT TOP
    RTC Time
    11:38:5

    Arduino Time
    11:38:5

    AT TOP
    RTC Time
    11:38:7

    Arduino Time
    11:38:7

    AT TOP
    RTC Time
    11:38:9

    Arduino Time
    11:38:9

***This one does not Work:***
Now I try to simply increment variable ArduinoHour and then write it to the RTC using rtc.adjust. ***The only change are the two lines at the bottom are uncommented.***

    #include <RTClib.h>    //https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code
    #include <Wire.h>

    int ArduinoHour;
    int ArduinoMin;
    int ArduinoSec;

    RTC_DS1307 rtc;

    void setup()
    {
      Serial.begin(250000);
      Wire.begin();  //sets up the I2C
      rtc.begin();   //initializes the I2C to the RTC

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
      }
        if (rtc.isrunning()) {
        Serial.println("RTC IS running!");
        rtc.adjust(DateTime(__DATE__, __TIME__));
      }
    }

    void loop()
    {
      DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

      ArduinoHour = now.hour();
      ArduinoMin = now.minute();
      ArduinoSec = now.second();

      Serial.print("AT TOP");
      Serial.println();
      Serial.print("RTC Time");
      Serial.println();
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      Serial.print("Arduino Time");
      Serial.println();
      Serial.print(ArduinoHour, DEC);
      Serial.print(':');
      Serial.print(ArduinoMin, DEC);
      Serial.print(':');
      Serial.print(ArduinoSec, DEC);
      Serial.println();
      Serial.println();
      delay(1000);

      //RTC increments when these are commented out
      ArduinoHour = ArduinoHour +1;
      rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

    }

Here is the output, RTC time is not changing. I know I am doing something basically wrong with how I am updating the variables writing/reading from the RTC.  Can't figure it out.

    RTC IS running!
    AT TOP
    RTC Time
    11:41:54

    Arduino Time
    11:41:54

    AT TOP
    RTC Time
    12:41:54

    Arduino Time
    12:41:54

    AT TOP
    RTC Time
    13:41:54

    Arduino Time
    13:41:54

    AT TOP
    RTC Time
    14:41:54

    Arduino Time
    14:41:54

title: Aruino RTC using rtclib not understanding functions

Answers: 2

body:
If by "RTC time is not changing" you mean minutes and seconds frozen at the same value, then this is entirely of your doing.

Your sketch spends 99% of the time between the initial `rtc.now()` request

     DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

and the final `rtc.adjust()` call

    rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

This period is the period when your RTC is supposed to be "ticking", progressing forward.

But you actually store the original minutes and seconds values in `ArduinoMin` and `ArduinoSec` at the beginning of this period. And later, at the end of this period, you bash these values back into the clock. By doing this you forcefully *erase* whatever progress the clock made between these two lines. No wonder your minutes and second do not change.

This problem actually has no perfect solution. `RTC_DS1307` class (and, I suspect, the underlying RTC hardware) provide no means to change just the hours value without disrupting minutes and seconds. When you call `adjust()`, you have to set everything, which means that you will always somehow "disrupt" the whole clock.

In your sketch you can *minimize* the adverse effects by re-requesting the minutes and seconds values right before doing `adjust()`:

    //RTC increments when these are commented out
    ArduinoHour = ArduinoHour +1;
    now = rtc.now();
    rtc.adjust(DateTime(now.year(), now.month(), now.day(), ArduinoHour, now.minute(), now.second()));

Note, that I'm using your updated `ArduinoHour` values, but everything else comes from a just-refreshed `now` object.

This is still not perfect, since it still suffers from a race condition against a real-time clock, but it is better than what you had originally.

body:
This is the content of `ajust` method:
```
void RTC_DS1307::adjust(const DateTime& dt) {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)0); // start at location 0
  Wire._I2C_WRITE(bin2bcd(dt.second()));
  Wire._I2C_WRITE(bin2bcd(dt.minute()));
  Wire._I2C_WRITE(bin2bcd(dt.hour()));
  Wire._I2C_WRITE(bin2bcd(0));
  Wire._I2C_WRITE(bin2bcd(dt.day()));
  Wire._I2C_WRITE(bin2bcd(dt.month()));
  Wire._I2C_WRITE(bin2bcd(dt.year() - 2000));
  Wire.endTransmission();
}
```
You can write new `Hour` value directly to the clock without erasing other clock data:
```
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)2); // Hour location
  Wire._I2C_WRITE(bin2bcd(ArduinoHour));
  Wire.endTransmission();
```


body:
Could someone give me some advice related to building a menu for a 128x64 LCD using 5 pushButtons?
i have 5 screens.
btn1 is for display MainMenu and Selection.
btn2 and btn3 is for up and down scrolling
btn 4 and btn4 is for switching on/off and increase decrease values.

the problem which i encounter is related to btn2 and btn3.
i don;t know how to use them for scrolling in in another screen except screen1 (MainMenu).
~~~

#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(13,12,11); //Enable, RW, RS, RESET

int selectionButton = A1, selectionButtonState, selectionButtonLastState = 0, cntSelectionButtonPressed = 0, cntSelectionButtonPressed2ForMenu2 = 0;
int menuButton = A0, menuButtonState, menuButtonLastState = 0;
int scrollDownButton = A3, scrollDownButtonState, scrollDownButtonLastState = 0;
  boolean mainMenu = false;

void setup()
{
    Serial.begin(9600);
    if ( u8g.getMode() == U8G_MODE_R3G3B2 )
    u8g.setColorIndex(255);     // white
    else if ( u8g.getMode() == U8G_MODE_GRAY2BIT )
    u8g.setColorIndex(3);         // max intensity
    else if ( u8g.getMode() == U8G_MODE_BW )
    pinMode(selectionButton,INPUT);
    pinMode(menuButton,INPUT);
    pinMode(scrollDownButton,INPUT);

}

void loop()
{

 scrollDownButtonState = digitalRead(A3);
 selectionButton = digitalRead(A1);
 menuButton = digitalRead(A0);

//pin A1 = RiGHT
 if(selectionButton != selectionButtonLastState)
 {
  if(digitalRead(A1) == HIGH)
  {
    cntSelectionButtonPressed += 1;
    if(cntSelectionButtonPressed == 4)
    {
      cntSelectionButtonPressed = 0;
    }
  }
  selectionButtonLastState = selectionButton;
 }

////////////////////////
 if(menuButton != menuButtonLastState)
  {
    if(cntSelectionButtonPressed == 1 && digitalRead(A0) == HIGH)
    {
         cntSelectionButtonPressed2ForMenu2 += 1;
    }
      if(cntSelectionButtonPressed2ForMenu2 == 4)
      {
        cntSelectionButtonPressed2ForMenu2 = 0;
      }
       u8g.firstPage();
       do{
           Menu2();
         }while(u8g.nextPage());

       menuButtonLastState = menuButton;
  }
 else
 {
 u8g.firstPage();
  do{
    MainMenu();
  }while(u8g.nextPage());
 }

}

void MainMenu(){
switch(cntSelectionButtonPressed)
{

  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("> Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("> Exterior casa");
           break;
}
}

void Menu2()
{

  switch(cntSelectionButtonPressed2ForMenu2)
{
  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("> Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("> Stil3");
           break;
}
}
~~~

title: 128x64 and pushButtons

Answers: 1

body:
First, I'm a bit surprised you use analog pins for button checks, instead of digital pins.

About the code, without analyzing it completely, the easiest way is to make a state diagram in pseudo code first.

E.g.suppose you want to have the following screens(a screen 'title/content' is shown in[], a button transition with ---(key)-->

    InitScreen--- (right)--> MenuOption1Highlight---(right)-->MenuOption1Items
                                  |       ^     \---(left)----+
                               (down)    (up)
                                  v       |
                            MenuOption2Highlight---(right)-->MenuOption2Items
                                               \---(left)----+

To program this (roughly), create an enumeration for each menu page :

    enum EMenuPage
    {
   None,
     InitScreen,
     MenuOption1Highlight,
     MenuOption1Items,
     MenuOption2Highlight,
     MenuOption2Items
    };

Than create a current state for it as global variable:

    EMenuPage _eMenuPage;

And initialize it in Setup:

    _eMenuPage = None;

Create an enum for the keys :

    enum EKey
    {
  None,
     Up,
     Down,
     Right,
     Left
    };

It is easier to create a function that reads keys, and returns one key, maybe one key has priority over another,
or you can combine keys (in that case add in EKey e.g. UpAndDown). If no key has been pressed, None is selected.

In the loop, use a state transition diagram to program out the options :

    EKey pressedKey = GetPressedKey(); // This is for yourself to implement, it updates _pressedKey;

 switch (_eMenuPage)
 {
 case None:
  InitScreen();
  break;

 case InitScreen:
  ProcessInitScreenKeys();
  break;

 case MenuOptions1HighLighted:
  ProcessMenuOptions1HighLightedKeys();
  break;

 ...
 default:
  // Illegal key
  break;
 }

For each page you make a function (e.g. InitScreen) which updates the state and shows the content on the display:

    void InitScreen()
 {
  _eMenuPage = InitScreen;

  // Show content on display.
 }

Also, you create a Process...Keys function to handle the keys. Like:

 void InitScreen()
 {
  EKey pressedKey = GetPressedKey();
  switch (pressedKey)
  {
  case Right:
   MenuOptions1HighLighted();
   break;

  default:
   // Ignore other keys
   break;
  }
 }

For another function it would look like:

    void ProcessMenuOptions1HighLightedKeys()
    {
  EKey pressedKey = GetPressedKey();
  switch (pressedKey)
  {
  case Down:
   MenuOptions1HighLighted();
   break;

  case Right:
   MenuOption1Items();
   break;

  default:
   // Ignore other keys
   break;
  }
 }

(Btw I did not check neither compiled the code).

Probably there is a nicer more object oriented way to do this, but it costs more memory and is more advanced. This is to create an abstract Page class, which has two virtual methods (one to show and one to handle keys), and create a derived class for each page implementing the two functions from the base class.


body:
I spent the last two days to find a way to set up a basic communication between a nodemcu amica and an arduino nano with a nrf24l01 module; all of this without success..

Here the code uploaded on my nodemcu:

```c
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(D4, D8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

void setup()
{
  Serial.begin(115200);
  delay(2000);

  radio.begin();

  //set the address
  radio.openWritingPipe(address);

  //Set module as transmitter
  radio.stopListening();

  Serial.println("inizio ad trasmettere");
  Serial.println(radio.isChipConnected());
}
void loop()
{
  Serial.println("qui");
  const char text[] = "Hello World";
  bool ret = radio.write(&text, sizeof(text));
  Serial.print("Write ret: ");
  Serial.println(ret);
  delay(1000);
}
```

and here the code on the arduino side
```c
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(5, 6);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

void setup()
{
  Serial.begin(115200);
  delay(2000);

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);

  //Set module as receiver
  radio.startListening();

  Serial.println("inizio ad ascoltare");
  Serial.println(radio.isChipConnected());
}

void loop()
{
  //Read the data if available in buffer
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}
```

Following my wiring config of
[nodemcu][1]
and
[arduino nano][2]

Can anyone see something that I don't see?
I'm really frustrated

My nrf24l01 module is this [https://www.amazon.it/gp/product/B06WD17WLS][3], not the module in the fritzing scheme.

  [1]: https://i.stack.imgur.com/C3zWN.png
  [2]: https://i.stack.imgur.com/DoeRH.png
  [3]: https://www.amazon.it/gp/product/B06WD17WLS

title: Basic communication with nrf24l01 between nodemcu and arduino nano

Answers: 0


body:
I have been trying to get TCS34725 color sensor working with LilyPad Arduino USB - ATmega32U4 Board but with no success. I am wondering if it possible? I have been using the following Sketch to try and get a reading but nothing appears in the monitor:
<!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include "Adafruit_TCS34725.h"

    /* Example code for the Adafruit TCS34725 breakout library */

    /* Connect SCL    to analog 5
       Connect SDA    to analog 4
       Connect VDD    to 3.3V DC
       Connect GROUND to common ground */

    /* Initialise with default values (int time = 2.4ms, gain = 1x) */
    // Adafruit_TCS34725 tcs = Adafruit_TCS34725();

    /* Initialise with specific int time and gain values */
    Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

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

      if (tcs.begin()) {
        Serial.println("Found sensor");
      } else {
        Serial.println("No TCS34725 found ... check your connections");
        while (1);
      }

      // Now we're ready to get readings!
    }

    void loop(void) {
      uint16_t r, g, b, c, colorTemp, lux;

      tcs.getRawData(&r, &g, &b, &c);
      // colorTemp = tcs.calculateColorTemperature(r, g, b);
      colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
      lux = tcs.calculateLux(r, g, b);

      Serial.print("Color Temp: "); Serial.print(colorTemp, DEC); Serial.print(" K - ");
      Serial.print("Lux: "); Serial.print(lux, DEC); Serial.print(" - ");
      Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
      Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
      Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
      Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
      Serial.println(" ");
    }

title: Can I use TCS34725 Color Sensor with Lilypad?

Answers: 1

body:
> Can I use TCS34725 Color Sensor with Lilypad?

Yes but please note that the I2C pins are D2 (SDA) and D3 (SCL). No extra components are required when connecting to the Adafruit TCS34725 breakout board. It contains pull-up resistors, and voltage/signal level converters (if needed).

Cheers!

Ref. https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad_Arduino_USB_v12.pdf


body:
I'm doing a project using an ESP32 TTGO with LoRa, the Max485 and a WELLPRO ADAM 8082 for Modbus communication. I'm trying to use the ESP32 as a master to and the ADAM as a slave.
I'm also using Node-RED to send the input signals (reading the digital inputs on the ADAM or sending signals to the digital outputs).
Whenever I send a signal there's no problem, the ADAM receives it correctly and sends the answer. But when my ESP32 receives the answer, I get the following error:
```
Stack smashing protect failure!

abort() was called at PC 0x400dc860 on core 1
```

I tried debugging my program and the error happens when my program comes back from the function that has my reading modbus loop.
I'm pretty new to Arduino, so I don't really understand what could be causing this stack overflow.

Here's my code.

My global variables:
```c
unsigned char ucSt[N_MAX];
int delayTime;

HardwareSerial modbusData(2);

WiFiClientSecure espClient;
PubSubClient client(espClient);
boolean bWifiConnected = false;

const byte button = PRG_BUTTON;
```

Modbus reading with loop:
```c
void vReadingModBus()
{
  int i, nCmpt = 0;
  unsigned int uiCRC;

  while (modbusData.available() > 0)
  {
    Serial.print("nCmpt: ");
    Serial.println(nCmpt);
    ucSt[nCmpt] = (unsigned char)modbusData.read();
    nCmpt++;
    delay(delayTime - 2);
  }
  if (nCmpt)
  {
    Serial.print("He llegit aquests ");
    Serial.print(nCmpt);
    Serial.println(" bytes: ");
    char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
    client.publish(TEMA_RESPOSTA_MODBUS, szResposta);
    uiCRC = uiModRTU_CRC(ucSt, nCmpt - 2);
    if ((byte)(uiCRC >> 8) == ucSt[nCmpt - 1] && (byte)(uiCRC & 0xFF) == ucSt[nCmpt - 2])
    {
      Serial.println("Trama amb CRC correcte");
    }
    else
    {
      Serial.println("Trama amb CRC incorrecte");
    }
  }
  nCmpt = 0;
}
```

Modbus transmission:
```c
void vModbusTx(unsigned char *uc, int nLen)
{
  int i;

  Serial.print("Enviat: ");
  for (i = 0; i < nLen; i++)
  {
    Serial.print(uc[i], HEX);
    Serial.print(" ");
  }
  Serial.println();

  vModeTxRxRS485(RS485Transmit);
  delay(1);
  for (i = 0; i < nLen; i++)
  {
    modbusData.write(uc[i]);
  }
  delay(delayTime);

  vModeTxRxRS485(RS485Receive);
}
```

My setup:
```c
void setup() {
  Serial.begin(115200);    // U0_RXD:GPIO3, U0_TXD:GPIO1 (UART0)
  modbusData.begin(9600); // U2_RXD:GPIO16, U2_TXD:GPIO17 (UART2)

  pinMode(PRG_BUTTON, INPUT_PULLUP);
  pinMode(GPIO_R2, INPUT); // 39
  pinMode(SSerialTxControl, OUTPUT); // hardwired to GPIO_R2
  pinMode(LED, OUTPUT);

  vModeTxRxRS485(RS485Receive); // RS485Receive is a 0, and vModeTxRxRS485 controls the DE/RE bits for the Max485

  delayTime = 0;

  //Wire.begin(I2C_SCL_OLED);

  delay(1000); // give me time to bring up serial monitor
}
```

My loop:
```c
void loop() {
  boolean bButtonState = !digitalRead(button);
  static boolean bLastButtonState = bButtonState;

  // MODBUS READING LOOP
  vReadingModBus();

  if (!client.connected())
  {
    reconnect();
  }

  // BUTTON STATE CHECK
  if (bButtonState != bLastButtonState)
  {
    bLastButtonState = bButtonState;
    vDelayESP(50);
    if (!bButtonState)
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "UNPRESSED");
    else
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "PRESSED");
  }

  client.loop();
}
```

And finally here's an example of my program running and giving the error mentioned:

```
Connecting to WiFi network
Waiting for WIFI connection...
..............................................
Attempting MQTTS connection...connected
Message arrived [/clot/dam/biel/esp32/escriuModbus] 010F000000080111
Petició a ModBus:
010F000000080111
Mida: 8
ucSt[0] = 1
ucSt[1] = F
ucSt[2] = 0
ucSt[3] = 0
ucSt[4] = 0
ucSt[5] = 8
ucSt[6] = 1
ucSt[7] = 11
Enviat: 1 F 0 0 0 8 1 11 3E 99
He llegit aquests 8 bytes:
1 F 0 0 0 8 54 D
Trama amb CRC correcte

Stack smashing protect failure!

abort() was called at PC 0x400dc7d8 on core 1

Backtrace: 0x4008c800:0x3ffb1ef0 0x4008ca31:0x3ffb1f10 0x400dc7d8:0x3ffb1f30 0x400d1eed:0x3ffb1f50 0x400d23c0:0x3ffb1f90 0x400d513d:0x3ffb1fb0 0x4008879d:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x17 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:928
ho 0 tail 12 room 4
load:0x40078000,len:8424
ho 0 tail 12 room 4
load:0x40080400,len:5868
entry 0x4008069c

```

title: Stack smashing protect failure ESP32 with Modbus RTU

Answers: 1

body:
tl;dr: The message probably means your function is overwriting its array:

A stack overflow is caused by a stack that grows downward into the allocated heap space, either causing damage to data within the heap, or code using that heap space causing damage to the contents of the stack.

But "stack smashing" refers to damage caused by function code writing past the bounds of an automatic local variable and damaging the stack contents, typically including the function's return address.

[Feel free to skip rather long explanation:]

A function's stack-frame begins with the return address - the address following the instruction that calls the function, i.e., the address of the next instruction to be executed after the function returns. Then, building downwards, the call parameters are put on the stack and become local variables. Then any variables allocated during the function execution are allocated, still building downward.

Assume one of those allocated variables is an array. Its zero-th element is in the lowest address of the allocated space, and subsequent elements are at successively higher addresses. If I start writing into the array, and continue past its length, I'll eventually overwrite other automatic locals, my parameters, and and my return address. Then, when the function tries to return, instead of jumping to the code that called the function, the MCU uses the damaged return address and jumps to ... ????

To catch this error, the compiler can insert code that 1) allocates and writes a "canary" - a known value - just after the return address, and 2), checks the canary for damage just before the function returns. If the canary has been altered, you get the message you saw, because it's likely that the return address will have been altered also. But regardless, the canary isn't part of your code and isn't accessible to it. Thus, it detects *writing-out-of-bounds errors*.

[End of wordy explanation]

Check the code in your function 'void vReadingModBus()' - my money is on the loop that writes into `szResposta[]`:

      char szResposta[N_MAX] = "", szByte[3];
        for (i = 0; i < nCmpt; i++)
        {
          sprintf(szByte, "X", ucSt[i]);
          strcat(szResposta, szByte);
          Serial.print(ucSt[i], HEX);
          Serial.print(" ");
        }

Update:

> If I understood correctly, it means szResposta must be overwriting the
> function's return address? How should I avoid this?

The short answer is make your array big enough for what you're going to put in it. But that's probably not a satisfying answer though, so let's take a closer look. I'm not sure exactly what your intent is in that loop, but since you print the `strcat()` result at every iteration and you don't seem to use `szResposta` after that, perhaps you meant to call `strcpy()` (replace the contents of the array) instead of `strcat()` (extend the contents of the array). If so, `strcat()` would quite likely write past the array bounds.