message:
Menu with switch case not behaving correctly

I hope this the right place to post this question :)

I'm trying to display a menu on a SSD1351 OLED display, to which I communicate with U8glib. I'm trying to obtain an Init screen, then, with a long press on a button (Menu), get in to a menu with 3 options (let's say option1, option2 and back). I got it working this way:

    #include <Button.h>  // https://github.com/JChristensen/Button.git
    #include "U8glib.h"
    #include <Wire.h>

    #define PULLUP true
    #define INVERT true
    #define DEBOUNCE_MS 20

    Button ok(2, PULLUP, INVERT, DEBOUNCE_MS);
    Button menu(5, PULLUP, INVERT, DEBOUNCE_MS);
    Button down(3, PULLUP, INVERT, DEBOUNCE_MS);
    Button up(4, PULLUP, INVERT, DEBOUNCE_MS);
    U8GLIB_SSD1351_128X128_332 u8g(8, 9, 7);
    uint8_t screen = 0;
    uint8_t menu_current = 0;
    void setup() {
      u8g.setFont(u8g_font_unifont);
      u8g.setDefaultForegroundColor();
      drawScreen();
    }

    void loop() {
      ok.read();
      menu.read();
      up.read();
      down.read();
      if (menu.pressedFor(1000) && screen == 0) {
        screen = 1;
        menu_current = 0;
        drawScreen();
      }
      if (screen == 1) {
        if (up.wasReleased()) {
          if (menu_current > 0) {
            menu_current--;
            drawScreen();
          }
        }
        if (down.wasReleased()) {
          if (menu_current < 2) {
            menu_current++;
            drawScreen();
          }
        }
        if (ok.wasReleased()) {
          switch (menu_current) {
            case 0:
              screen = 2;
              break;
            case 1:
              screen = 3;
              break;
            case 2:
              screen = 0;
              break;
              break;
          }
          drawScreen();
        }
      }
      if (screen == 2 || screen == 3) {
        if (menu.wasReleased()) {
          screen = 1;
          menu_current = 0;
          drawScreen();
        }
      }
    }

    void drawScreen() {
      u8g.firstPage();
      do {
        whatToDraw();
      } while (u8g.nextPage());
    }

    void whatToDraw() {
      switch (screen) {
        case 0: {
            u8g.drawStr(0, u8g.getFontLineSpacing(), F("Init"));
          } break;
        case 1: {
          const char *menu_strings[3] = { "option1", "option2", "Back" };
          uint8_t i, h;
          u8g_uint_t w, d;
          u8g.setFontRefHeightText();
          u8g.setFontPosTop();
          h = u8g.getFontAscent() - u8g.getFontDescent();
          w = u8g.getWidth();
          for ( i = 0; i < 3; i++ ) {
            d = (w - u8g.getStrWidth(menu_strings[i])) / 2;
            u8g.setDefaultForegroundColor();
            if ( i == menu_current ) {
              u8g.drawBox(0, i * h + 1, w, h);
              u8g.setDefaultBackgroundColor();
            }
            u8g.drawStr(d, i * h, menu_strings[i]);
          }
        }
        break;
        case 2: {
          u8g.drawStr(0, u8g.getFontLineSpacing(), F("Option1"));
        }
        break;
        case 3: {
          u8g.drawStr(0, u8g.getFontLineSpacing(), F("Option2"));
        }
        break;
        break;
      }
    }

Everything seems to be working except the back option: when I select it, the display gets blanked instead of visualizing screen 0 ("Init"). Variables seem to be set correctly. Does anybody have an idea why this isn't working?

Thank you :)

Dario

EDIT: copied the whole sketch as requested :)

body:
Summary: I tested @noospy project (with some modifications) and it works flawlessly.

[![Menu and buttons][1]][1]

I had to rename Button.h to ButtonM.h due name conflict with another button library. Also, I'm using new version U8g2, so I had to change some types and eliminate some calls. Finally, I used the I2C version of the OLED screen.

This is my adapted code:

    #include <ButtonM.h>  // https://github.com/JChristensen/Button.git
    #include "U8g2lib.h"
    #include <Wire.h>

    #define PULLUP true
    #define INVERT true
    #define DEBOUNCE_MS 20

    Button ok(2, PULLUP, INVERT, DEBOUNCE_MS);
    Button menu(5, PULLUP, INVERT, DEBOUNCE_MS);
    Button down(3, PULLUP, INVERT, DEBOUNCE_MS);
    Button up(4, PULLUP, INVERT, DEBOUNCE_MS);

    //U8GLIB_SSD1351_128X128_332 u8g(8, 9, 7);
    // Screen
    U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

    uint8_t screen = 0;
    uint8_t menu_current = 0;

    void setup() {
        u8g.begin(); // Added
        u8g.setFont(u8g_font_unifont);
    //  u8g.setDefaultForegroundColor();

        drawScreen();
    }

    void loop() {
        ok.read();
        menu.read();
        up.read();
        down.read();

        if (menu.pressedFor(1000) && screen == 0) {
            screen = 1;
            menu_current = 0;
            drawScreen();
        }

        if (screen == 1) {
            if (up.wasReleased()) {
                if (menu_current > 0) {
                    menu_current--;
                    drawScreen();
                }
            }

            if (down.wasReleased()) {
                if (menu_current < 2) {
                    menu_current++;
                    drawScreen();
                }
            }

            if (ok.wasReleased()) {
                switch (menu_current) {
                    case 0:
                        screen = 2;
                        break;
                    case 1:
                        screen = 3;
                        break;
                    case 2:
                        screen = 0;
                        break;
                    break;
                }
                drawScreen();
            }
        }

        if (screen == 2 || screen == 3) {
            if (menu.wasReleased()) {
                screen = 1;
                menu_current = 0;
                drawScreen();
            }
        }
    }

    void drawScreen() {
        u8g.firstPage();
        do {
            whatToDraw();
        } while( u8g.nextPage() );
    }

    void whatToDraw() {
        switch (screen) {
            case 0: {
                u8g.drawStr(0,getFontLineSpacing(),"Init");
            } break;
            case 1: {
                const char *menu_strings[3] = { "option1", "option2", "Back" };
                uint8_t i, h;
                int w, d;

                u8g.setFontRefHeightText();
                u8g.setFontPosTop();

                h = u8g.getFontAscent()-u8g.getFontDescent();
                w = u8g.getWidth();
                for( i = 0; i < 3; i++ ) {
                    d = (w-u8g.getStrWidth(menu_strings[i]))/2;
    //                u8g.setDefaultForegroundColor();
                    if ( i == menu_current ) {
                        u8g.drawBox(0, i*h+1, w, h);
    //                    u8g.setDefaultBackgroundColor();
                    }
                    u8g.drawStr(d, i*h, menu_strings[i]);
                }
             } break;

             case 2: {
                 u8g.drawStr(0,getFontLineSpacing(),"Option1");
             } break;

             case 3: {
                 u8g.drawStr(0,getFontLineSpacing(),"Option2");
             } break;

             break;
        }
    }

    int getFontLineSpacing() {
      return 24;
    }

**Hardware**

 1. Arduino Pro Mini 3.3v 8MHz
 2. 1306 0.96 inch White Color I2C IIC Communication 128 * 64 OLED Display.
 3. 4x push buttons with 1K pullup resistors.

So, I don't know what your problem is, but your code is impecable.

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


sender: user

sender: assistant

body:
You can consider using one of the existing menu libraries, there are some available on github. Just pick the one that best fits your needs

https://github.com/search?utf8=✓&q=arduino+menu&type=


message:
Change Token authentication method to MQTT authentication method(username, password, client_id, ssid, passwd)

I have a mq135 sensor abd nodemcu ESP-12E module to calculate air quality and monitor it via Cayenne platform.

How can I edit this below code to add and connect my Nodemcu ESP-12E module to cayenne with MQTT authentication(username, password, client_id, ssid, passwd) method?

We can’t add Nodemcu with token method, we should use MQTT authentication instead to add and connect nodemcu module to cayenne.

     #include “MQ135.h”
     #include “CayenneDefines.h”
     #include “CayenneWiFi.h”
     #include “CayenneWiFiClient.h”
     #define CAYENNE_DEBUG
     #define CAYENNE_PRINT Serial
     #define VIRTUAL_PIN 5
     #define ANALOGPIN A0

    char token[] = “”; // Insert your token here
    char ssid[] = “”; // Insert your SSID here
    char pwd[] = “”; // Insert your SSID password here
    MQ135 gasSensor = MQ135(ANALOGPIN);

    void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Cayenne.begin(token, ssid, pwd);
    }

    void loop() {
    // put your main code here, to run repeatedly:
    Cayenne.run();
    // float rzero = gasSensor.getRZero(); //this to get the rzero value, uncomment this to get ppm value
    // float ppm = gasSensor.getPPM(); // this to get ppm value, uncomment this to get rzero value
    // Serial.println(rzero); // this to display the rzero value continuously, uncomment this to get ppm value
    // Serial.println(ppm); // this to display the ppm value continuously, uncomment this to get rzero value
    // Cayenne.virtualWrite(VIRTUAL_PIN,ppm); // uncomment after rzero define and get your ppm calculation
    }

body:
You could have readily answered this question for yourself merely by looking at the [example][1] for the [Cayenne-MQTT-ESP8266][2] library.

The key part being:

    // Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
    char username[] = "MQTT_USERNAME";
    char password[] = "MQTT_PASSWORD";
    char clientID[] = "CLIENT_ID";

 Cayenne.begin(username, password, clientID, ssid, wifiPassword);

  [1]: https://github.com/myDevicesIoT/Cayenne-MQTT-ESP8266/blob/master/examples/ESP8266/ESP8266.ino
  [2]: https://github.com/myDevicesIoT/Cayenne-MQTT-ESP8266

It is not readily possible to know if this is the same Cayenne library you were using before, as you neglected to specify what you were using.  The includes are different, but that could be a version difference, or it could be evidence of an entirely different approach.


message:
Arduino and 2 MOSFETs

I want to turn on 2 bulbs using 2 MOSFETs. The problem is that they both turn on when it should turn up just one light.

Code:

    void setup() {
      pinMode(13, OUTPUT);
      pinMode(7, OUTPUT);
    }

    void loop() {
      digitalWrite(13,1);
      digitalWrite(13,0);
    }

See circuit below:

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

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

body:
Try adding a delay into your loop. In your code pin 13 will toggle very rapidly, much too fast to see it. For example:

    void loop() {
      digitalWrite(13,HIGH);
      delay (1000);
      digitalWrite(13,LOW);
      delay (1000);
    }

---

It doesn't look wired correctly. For an N-channel MOSFET the Source should go to ground, like this:

[![Low-side driver][1]][1]

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


body:
The following circuit diagram works perfectly.

[![Mosfet circuit][1]][1]

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


message:
ATmega328p - ISC00 with INT1?

I was reading about external interrupts using the ATmega328p, and I saw in the chip datasheet under the paragraph "Bits 3:2 – ISC1n: Interrupt Sense Control 1 [n = 1:0]" the following table:

    Value | Description
    ------+------------------------------------------------------------
    00    | The low level of INT1 generates an interrupt request.
    01    | Any logical change on INT1 generates an interrupt request.
    10    | The falling edge of INT1 generates an interrupt request.
    11    | The rising edge of INT1 generates an interrupt request.

From what I understand from the table title and the definition in the datasheet that ISC1n where n=1|0, is dedicated for INT1. And that ISC0n where n=1|0, is dedicated for INT0. However, in the table above, the value 00 is described as "The low level of INT1 generates an interrupt request.".

What I don't understand is how can ISC0n where n=1|0 be dedicated for INT0 but in the table above the value 00 (or ISC00) is used for INT1 ? I could totally be missing something but I would appreciate any guide.

body: It's a typo. My revision of the datasheet (revision G) properly says "INT0".


body:
> From what I understand from the table title and the definition in the
> datasheet that ISC1n where n=1|0, is dedicated for INT1. And that
> ISC0n where n=1|0, is dedicated for INT0.

This is correct.

> [...] in the table above the value 00 (or ISC00) is used for INT1

This is your misunderstanding. The value "00" in the table does not mean
ISC00. The "Value" column of the table is the value you get by
concatenating the bits ISC11 and ISC10. Thus:

* "Value = 00" means ISC11 = 0 and ISC10 = 0
* "Value = 01" means ISC11 = 0 and ISC10 = 1
* "Value = 10" means ISC11 = 1 and ISC10 = 0
* "Value = 11" means ISC11 = 1 and ISC10 = 1


message:
Convert from 3 V to 5 V

I'm new to Arduino, electronics, and this forum.

I have made up a little project that connects an [HC-SR04][1] ultrasonic range detector, and displays the distance on a 4 digit, 7 segment LED display.

When I have it plugged into my laptop for power, it runs beautifully on an Uno board.

But I want to mount all this in a Nerf gun ([Nerf N-Strike Elite Firestrike][2]) using a Nano board.

The Nerf gun has a built in "laser" (red light) that is powered by 2 x AAA batteries, which makes 3 V, I think. I want to rig this up so that pulling the laser/light trigger also triggers the range detector and display.

I want to run the range sensor and the display off the Nerf guns batteries, but they both use 5 V. Is there a way to do this? Or do I need a separate 5 V power supply?

  [1]: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
  [2]: https://www.amazon.com/Nerf-53378F01-N-Strike-Elite-Firestrike/dp/B00JMJS1E2

body:
You may want to use a [boost converter](https://en.wikipedia.org/wiki/Boost_converter) which is a device that can step up voltage.

You can get them from eBay for around $US 2.

---

As Chris Stratton pointed out in a comment, the boost converter may run your batteries down quite quickly. Let's say you need 200 mA for your Uno, sensor and LEDs. At 5V power that is 1W of power (`0.200 * 5`).

However to get 1W from 3V you would consume 333 mA (`0.333 * 3`). Then take into account that the converters are not completely efficient. Let's say the converter has 90% efficiency. Then you need to multiply the current by the inverse of the efficiency, that is: `0.333 mA / 0.9 = 0.37 mA`.

Another factor is the battery type. If you use NiCad batteries their nominal voltage is closer to 1.2V than 1.5V, especially after you have been using them for a bit. Ditto for [NiMh batteries](https://en.wikipedia.org/wiki/Nickel–metal_hydride_battery).

Reworking the above for 2 * 1.2V (2.4V) we see that the current will be:

    1W / 2.4V = 0.4167A
    0.4167A / 0.9 = 0.463A (allowing for 90% efficiency)

Now it potentially draws close to half an amp when active. Your batteries might not be able to handle that for long.


body:
Arduino nano also have 5v-3.3v voltage regulator so you can power all this with only one power supply (power your arduino nano with 6x AAA batteries) and then just connect your nerf gun power with arduino nano 3.3v pin, it will work just fine............
                                      :)


body:
Just to suggest an alternative, and more energy efficient, solution...

There appear to be newer versions of the HC-SR04 on the market that support 3.3V, such as the [HC-SR04 v2 - Low Cost Ultrasonic Sensor (3V to 5V Supply)][1].

So you could use an [Arduino Pro Mini][2] designed to run at 3V in conjunction with the 3.3 V HC-SR04, and run it straight off your nerf gun's power supply.

---

However, it might be worth taking these new versions with a pinch of salt, as modules seem to vary from one to another, see [Re: Do HC-SR04 5V rangefinder sensors work in 3V battery mode?][3]

> I have a MKRFOX1200 working with HC-SR04 and it works fine. It is stated to work only at 5v but its fine with 3V. But I have another one (SF-SR02) with a higher range (6meters) and this one doesnt get any further than 1  or 2 meters under 3V. If I use the 5V for VCC while running on USB, it reaches full range. Digital inputs seem to be more tolerant than they state for 5V signals.. (although I'm not advising to do so!!)

An extremely useful comparison of these modules (the first generation) running at both 3.3 and 5 V can be seen here, [Re: Ultra cheap ultrasonics, and a bit of a challenge][4]:

3V3

[![HC-SR04 running at 3V3][5]][5]

5V

[![HC-SR04 running at 5 V][6]][6]

Notwithstanding, the newer versions of the HC-SR04 may have an improved response.

  [1]: https://www.sgbotic.com/index.php?dispatch=products.view&product_id=1855
  [2]: https://store.arduino.cc/arduino-pro-mini
  [3]: https://forum.arduino.cc/index.php?topic=511439.msg3510930#msg3510930
  [4]: https://www.raspberrypi.org/forums/viewtopic.php?p=183386#p183386
  [5]: https://i.stack.imgur.com/rQlT2.png "HC-SR04 running at 3V3"
  [6]: https://i.stack.imgur.com/v5nnP.png "HC-SR04 running at 5 V"


message:
Arduino Mega Timer1 in pure C problem - doesn't work

Does somebody know what can be wrong in this, where I try to set Timer1 interrupt in Arduino Mega in C code only. I'm trying CTC Mode and the purpose is LED blinking with 1[s] Period.

I work with documentation program doesn't work completely.

     #include <avr/io.h>
     #include <avr/interrupt.h>

     void setup()
     {
       //LED -> PB7 (Digital pin 13
         DDRB |= (1<<PB7);

      //FCPU = 16MHz, Prescaler :256 | CTC
       TCCR1B |= (1<<CS12) | (1<<WGM12);
       TIMSK1 |= (1<<OCIE1A);  // Compare Match A interrupt allowing
         OCR1A = 62500;

        sei();
        }

      void loop()
      {

       }

       ISR(TIMER1_COMPA_vect)
       {
         PORTB ^= (1<<PB7);
        }

body:
> I work with documentation program doesn't work completely.

simple:

1) check out the datasheet;
2) identify those registers needed to get tmr1 to work;
3) set or clear, as appropriate, ***ALL*** bits that are needed. Do NOT rely on default values.
4) done.


message:
Arduino language

I'm learning with my school Arduino and how to use it etc.

I know Swift and a little bit of HTML and I would like to learn Arduino language, because I think it's easy!

What are the best resources for learning Arduino?
What are the best programs to write Arduino?
Thanks!

body:
Best resources:

- Official website: [www.arduino.cc][1]
- This site (duh)

I don't know what you mean with 'best programs' ... that depends on what you want. My 'best program' is probably not your 'best program'

  [1]: https://www.arduino.cc/


body:
>  I would like to learn Arduino language, because I think it's easy!

it is C/C++.


body:
To begin as a newbie get started with the inbuilt examples that are already given.You will learn one by one and its easy to understand anyways.Try few simple codes like LED BLINK,LED WITH SWITCH, SENSOR INPUT AND OUTPUT USING SERIAL MONITOR and you will get used to with the ARDUINO IDE.

Ofcourse the best site is www.arduino.cc but try few pdfs for Arduino beginners which are available on the internet.Try youtube if you are having any trouble working out with just text information.

Go through the book "ARDUINO PROJECTS FOR DUMMIES"
LINK: http://www.dummies.com/store/product/Arduino-Projects-For-Dummies.productCd-1118551478.html

check out this link:
http://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/


body:
I guess Arduino is not the best language to learn as a beginner if you are interested in programming. Try Python, C#, JavaScript. Or directly C++ (which Arduino is actually).

Arduino has too specific usage and is limited. You wont use OOP here very often and will miss a lot of programming principles and practices.


message:
MAX7219 powered on via digital pin set to HIGH is not working good (I < 25mA)

I'm using 7-segment 8-digits MAX7219 eBuy module in my battery-supplied ATMega168P project to output some readings. MAX7219 in powerdown mode draws ~150uA (as stated in the datasheet) which is too much for me, because the rest of the circuit draws less than 1uA is sleep mode. So I decided to power off Vcc line for MAX7219 before entering sleep, and power it on just after wakeup.

Current draw for the software-dimmed display module is only 15..19 mA in my case, which is far less than 40mA pin maximum for ATMega168P, so **I connect display Vcc line to one of digital pins and power it on at setup():**

    void setup()
    {
      pinMode(4, OUTPUT);
      digitalWrite(4, HIGH);
    }
[![schematic][1]][1]

However, display module **works only 1..3 seconds** after starting, then switches off. I checked display Vcc — 4.9V, but the display is off. (I turned off enterng to sleep mode for a while)

This display module doesn't have capacitors C3 and C4 between Vcc and GND (but there's a placeholder for it), recommended in some sources. I solder two capacitors of 100nF and 4,7uF in parallel. It helps only a little: after 1..2 seconds of normal working display shows only digit #0 and in **much higher** brightness than I set (see the photo).

[![enter image description here][2]][2]
I may only suggest my cheap multimeter is wrong and the display draws much more, but I dont know how to check it. Rset is 10k on this module, btw.

1. Why does it happen?
2. Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

EDIT: If the display is powered directly by controller Vcc it works correctly as expected. It's current draw is 15..20mA.

  [1]: https://i.stack.imgur.com/d39H7.jpg
  [2]: https://i.stack.imgur.com/FrTia.jpg

body:
Using a led display in a low current application is an oxymoron. An LCD display is more appropriate.

With that said, you can switch the the 7219 from the high side and turn the pins into input mode to avoid ghost powering.

Od mode works but pull up has to be switched as well.


body:
After some research I eventually solved my problem, so here's the answer.

> 1. Why does it happen?

This LED display draws much more current than I measured on Vcc line between Arduino and display because of **ghost powering** via signal lines (`DIN, LOAD, CLK`). The display (although slightly dimmed) can even run without Vcc line connected! Real current draw was about 30-40 mA with peaks up to 100 mA.

> 2. Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

Yes, by limiting display current draw.

For an unknown reason these cheap MAX7219-driven LED boards has very small current control resistor `RSet` of 10 kOhm, resulting in huge `Iseg` ~= 40 mA. Replacing it by something like 62k will limit per-segment current to ~10 mA.

This is what the datasheet says:
[![typical application circuit][1]][1]

And this is how it can be done:
[![enter image description here][2]][2]

Works perfectly! Now I can power off LED display completely, so it consumes no current when the device is sleeping.

**NOTE**: it's important to properly re-initialize MAX7219 after power on!

In the colorized table above one could find display current draw for different software-set intensity settings in case of using RSet = 62k. GND line values (blue column) seems to be correct as they well correspond with overall device's current draw (the most correct measurement, I suppose).

  [1]: https://i.stack.imgur.com/tVANt.png
  [2]: https://i.stack.imgur.com/8eMcj.jpg


message:
Get hour with ctime (time library with ESP8266)

#include <ESP8266WiFi.h>
    #include <time.h>

    const char* ssid = "";
    const char* password = "";
    int timezone = 3;
    int dst = 0;

    void setup() {
      Serial.begin(115200);
      Serial.setDebugOutput(true);
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      Serial.println("\nConnecting to WiFi");
      while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(1000);
      }
      configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
      Serial.println("\nWaiting for time");
      while (!time(nullptr)) {
        Serial.print(".");
        delay(1000);
      }
      Serial.println("");
    }

    void loop() {
      time_t now = time(nullptr);
      Serial.println(ctime(&now));
      delay(1000);
    }

This is my code, but it shows the time like this: Sun Jul 23 15:21:12 2017. But what I want it to do is to only show the current hour, not everything.
Is it possible to do that?

body:
The easiest way is to use the standard function [localtime()][1] or [gmtime()][2] and the [struct tm][3].

    void loop() {
      time_t now;
      struct tm * timeinfo;
      time(&now);
      timeinfo = localtime(&now);
      Serial.println(timeinfo->tm_hour);
      delay(1000);
    }

  [1]: http://www.cplusplus.com/reference/ctime/localtime/
  [2]: http://www.cplusplus.com/reference/ctime/gmtime/
  [3]: http://www.cplusplus.com/reference/ctime/tm/


message:
Reading values from TTP229 capacitive touch sensor on arduino

I would like to be able to read the raw capacitive sensor values from a TTP229 chip through i2c in Arduino. I have one of these breakout boards to play with :

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

My goal is to get values similar to those of the MPR121 or the Capacitive Sensor Arduino library where the reading changes depending on proximity and how hard you touch the pads. I have tested the following code but I'm only able to detect an on / off reading.

    #include <Wire.h>
    #define ttp229 ( 0xAF>>1 )

    uint16_t data_out = 0;
    uint16_t data1, data2;
    int count = 0;
    boolean count2 = false;
    int button[16];
    int oldata[16];

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

    void loop()
    {
        Wire.requestFrom( ttp229, 2, true );
        //delay(1);
        while( Wire.available() )
        {
            data1 = Wire.read();
            data2 = Wire.read();
            data_out = (data1<<8)|data2;

            for(int i=1;i<17;i++)
            {
                uint16_t contrast = 0x8000;
                if(data_out & contrast)
                {
                    //Serial.println(i);
                    button[count]=i;
                    count++;
                }
                data_out<<=1;
            }
            if(count2)
            {
                switch(count)
                {
                    case 1:
                    if( oldata[0] == button[0] )
                    {
                        Serial.println( button[0] );
                        delay( 20 );
                    }
                    break;
                    case 2:
                    if(oldata[0]==button[0]&&oldata[1]==button[1])
                    {
                        for(int i = 0; i < 2; i++)
                        {
                            Serial.print( button[i] );
                            Serial.print("  ");
                        }
                    }
                    break;
                }
            }
            for( int i = 0; i < 16; i++ )
            {
                oldata[i] = button[i];
            }
            count = 0;
            count2 =! count2;
        }
    }

Even if i just print out data1 and data2 from the example it doesn't seem to produce readings that change with the capacitance. I originally thought this was a hardware limitation but then I came across [this TTP229 product][2] that has a linear touch sensor built into it.

Does anyone have any experience with this sensor and how I can access the raw readings?

  [1]: https://i.stack.imgur.com/tCNKx.jpg
  [2]: https://www.aliexpress.com/item/32787962371.html

body:
mpr121 gives raw values
it has 12 electrodes/capacitance sensing inputs

https://www.sparkfun.com/datasheets/Components/MPR121.pdf
https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/DataStream


message:
What would be the Western / American equivalent of the Troyka Shield and modules?

I'm taking an online course on Arduino robotics, produced by the Moscow Institute of Physics and Technology. The lectures are translated into English, but all of the parts referenced are by the Russian company Amperka.

It seems the key parts I need to follow along are

 - The [Troyka Shield][1]
 - [Troyka modules][2], like the potentiometer, Hall sensor, etc
 - [Matryoshka Z][3] set

As fun as it would be to order from the Russian store, there are several practical reasons I'd prefer an American (or Western) equivalent. If they even ship to the US, payment would be difficult, shipping slow, instructions in Russian, etc, etc.

I've spent time and money shopping around Adafruit and SparkFun, but as an Arduino beginner, I'm not 100% sure which parts are analogous to these Russian ones. If a more experienced hobbyist recognizes any of these and can help me identify it, that would be most appreciated.

I think the Troyka components are a necessity, but the Matryoshka Z is a "nice to have" bundle of components. I'm using Arduino Uno, so compatibility with that would be preferable, but I think one of his Russian controllers is supposed to be a clone of the Leonardo, so if these parts only work with a Leonardo that's fine too.

The shield is shown here:

[![enter image description here][4]][4]

In this view it's combined with its modules using this special snap-together PVC:

[![enter image description here][5]][5]

The instructor said that he helped invent the PVC components, so I guess there may not be an American version of that yet (or is there)?

  [1]: http://amperka.ru/product/arduino-troyka-shield
  [2]: http://amperka.ru/collection/troyka
  [3]: http://amperka.ru/product/matryoshka-z
  [4]: https://i.stack.imgur.com/MDOMJ.png
  [5]: https://i.stack.imgur.com/kYGjF.png

body:
This probably has no complete, general solution.

The Troyka Shield looks to be just a prototype shield with footprints for ground/power/data cables.  Likely you can just use a different mechanism to connect things, solder some additions to an everyday proto shield, or you could relatively quickly duplicate this in a PCB design program and have boards made.

There are probably many alternatives for the mechanical structure, ranging from cardboard and foam tape or hot glue to various toy building block sets, or you could try to duplicate their idea by making some grids on an everyday 3D printer.  Likely none of these satisfy formal ESD concerns - but then, Arduino projects are usually considered disposable enought that people rarely worry about this.

The modules are going to be the most problematic part.  They seem to encompass many of the peripheral parts and chips usually used in Arduino projects, and most of those are already available in canonical modules from a range of vendors like Adafruit, Sparkfun, Seeed, etc on down to clones and simple executions of chipmaker's recommended circuits.  So for most of these, you'll probably have no problem finding a *substitute*, the possible complication is if you have enough understanding of the details of each assignment to make any necessary changes to accommodate for differences in pinouts, components values, etc between the specified Troyka module and the chosen substitute.

You may in the end find it's better to just follow tutorials written around the specific parts and modules you find more readily available for purchase, and thus avoid the needs to translate the details.

Do beware however, that there are some *really bad* tutorials out there on the Internet - some in places like Instructibles are simply terrible engineering to the point where it is a minor miracle if they even worked once for their authors, and even some on the Arduino site cut corners in ways that can't be recommended.


message:
Can't manually connect HC-05 master to slave

Using [this][1] as a tutorial, I've tried to connect the master Bluetooth module from my Nano to the slave module in my Mega. After following the steps in the tutorial, when I enter the command to my serial monitor:

    AT+BIND=98d3,31,30690

I receive:

    ERROR:(7)

After looking up the error, I only get results for ERROR:(0)

Does anyone know what the error means or how to fix it?

  [1]: http://howtomechatronics.com/tutorials/arduino/how-to-configure-pair-two-hc-05-bluetooth-module-master-slave-commands/

body:
I found the solution.

Apparently, both of my modules were at `9600` baud rate when the optimal rate is of `38400`. I had to use `AT+ORGL` in command mode to reset both slave and master. Afterwards I was able to connect them manually.

So apparently `ERROR:(7)` represents a failed connection? Just don't forget to make sure everything is exactly like the tutorial that's teaching you.


body:
You need to add zeros to your address.

For example my address of slave is "FCA8:A7:A134"

So command to bind it to master will be "AT+BIND=FCA8,7A,00A134"

XXXX:XX:XXXXXX


message:
Is it possible to run two for loops separated?

I have three funtion which describe the brightness of three LEDs. I want the seconde loop run 1 second after the first one and the third 1 second after the second one. One loop needs approximately 5 seconds. So basically I need to run three loops separated. How is this possible?

Update:
So I have this code running which I can compile but does not work:

    int LED = 3;
    int LED2 =10;
    int LED3 = 9;

    bool loop1state, loop2state, loop3state; // True if running, false if off
    int  loop1index, loop2index, loop3index; // Iterator values
    int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

    void loop()
    {
    // Update loop enablers.
    switch(periodIndex)
    {
    case 0:
     loop1state = true;
     loop1index = 0;
     break;

    case 1000:
     loop2state = true;
     loop2index = 0;
     break;

    case 1500:
     loop3state = true;
     loop3index = 0;
     break;

    case 4000:
     periodIndex = 0;
     break;
    }

    if (loop1state)
    {
     for (loop1index = 0; loop1index<255; loop1index++){
      analogWrite(LED,loop1index);
     }

     loop1state = loop1index < 256;
     }

     if (loop2state)
     {
     for(loop2index = 0; loop2index<255; loop2index++)
     {
      analogWrite(LED2,loop2index);
     }

     loop2state = loop2index < 256;
    }

     if (loop3state)
     {
     for(loop3index = 0; loop3index<255; loop3index++)
     {
      analogWrite(LED3,loop3index);
     }
     loop3state = loop3index < 256;
     }
     delay(10);
     }

body:
No, but there is a solution to put the action in one loop (main loop).

If I understand you well, you have the following scheme:

Time[s]
0..1     Loop 1
1..2     Nothing
2..3     Loop 2
3..4     Nothing
4..5     Loop 3

Define a variable that keeps track of the time.
Check against the current time (millis) and when within the correct 'range' perform an action.
After 5 seconds start over again.

    uint32_t lastTime = -1;

    void loop()
    {
        if (lastTime == -1)
        {
            lastTime = currentTime; // Initialization, can be done in setup too
        }

        uint32_t diffTime = millis() - lastTime;

        if (diffTime < 1000) // 0..1 sec
        {
            DoLoop1();
        }
        else if (diffTime < 2000)
        {
             // Do nothing();
        }
        else if (diffTime < 3000)
        {
           DoLoop2();
        }
        else if (diffTime < 4000)
        {
            // Do nothing
        }
        else if (diffTime < 5000)
        {
           DoLoop3();
        }
        else // diffTime >= 5000
        {
             lastTime == currentTime; // Reset after 6 s
        }
    }

Update
------

Since you need all three loops together (and mixed), it's easier to define some variables.

    bool loop1state, loop2state, loop3state; // True if running, false if off
    int  loop1index, loop2index, loop3index; // Iterator values
    int  periodIndex = 0; // starting with 0, increasing every 10 ms

Too bad I don't know the conditions when a loop starts, but let's say each iteration is 10 ms, and loop 1 starts immediately, loop 2 after 1000 ms, loop 3 after 1500 ms. After 3000 ms it starts all over.

    void loop()
    {
      // Update loop enablers.
      switch(periodIndex)
      {
      case 0:
         loop1state = true;
         loop1index = 0;
         break;

      case 1000:
         loop2state = true;
         loop2index = 0;
         break;

      case 1500:
         loop3state = true;
         loop3index = 0;
         break;

      case 4000:
         periodIndex = 0;
         break;
      }

      if (loop1state)
      {
         DoLoop1(loop1index++);
         loop1state = loop1index < 256;
      }

      if (loop2state)
      {
         DoLoop2(loop2index++);
         loop2state = loop2index < 256;
      }

      if (loop3state)
      {
         DoLoop3(loop3index++);
         loop3state = loop3index < 256;
      }

      delay(10); // 10 ms
    }

Note, not tested, but the idea shold be clear

New update
==========

You should not do a full loop during each switch, but only one iteration of the loop.

I did not run the sketch, just out of my head.

Some tips: print out the variables during each loop, so you get a clear idea what is happening (so all loop states and indices, and the periodIndex).

    int LED = 3;
    int LED2 =10;
    int LED3 = 9;

    bool loop1state, loop2state, loop3state; // True if running, false if off
    int  loop1index, loop2index, loop3index; // Iterator values
    int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

    void loop()
    {
      // Update loop enablers.
      switch(periodIndex)
      {
      case 0:
        loop1state = true;
        loop1index = 0;
        break;

      case 1000:
        loop2state = true;
        loop2index = 0;
        break;

      case 1500:
        loop3state = true;
        loop3index = 0;
        break;

      case 4000:
         periodIndex = 0;
         break;
      }

      if (loop1state)
      {
        analogWrite(LED,loop1index++);
        loop1state = loop1index < 256;
      }

      if (loop2state)
      {
        analogWrite(LED2,loop2index++);
        loop2state = loop2index < 256;
      }

      if (loop3state)
      {
        analogWrite(LED3,loop3index++);
        loop3state = loop3index < 256;
      }

      periodIndex++;
      delay(10);
    }


body:
Let me see if I understand correctly what you want... You want to ramp
up the brightnesses of 3 LEDs, one step every roughly 10 ms, and
you want the brightness ramps to start at different times. If this is
the case, I would start by writing a function that handles one LED,
increases its brightness by one step, and tells the caller whether the
ramp is done or not:

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

    // Update the LED.
    // Returns true if there are brightness steps left,
    // false if we have finished the brightness ramp.
    bool update_led_1()
    {
        static uint8_t level = 0;  // brightness level
        analogWrite(LED1, level);
        level++;  // wraps to zero when we are done
        return level != 0;
    }

This stores the brightness level as a single byte, rather than a
two-byte `int`, because I am cheap. ;-) Notice that on the last step of
the ramp, the value 255 is sent to the LED, then `level++` wraps the
level to zero, then the function returns false to tell us the ramp is
finished. At this point, since `level` is zero, the function is ready
for the next ramp.

You can copy and paste this function three times, for each of the three
LEDs. Name them `update_led_1()`, `update_led_2()` and `update_led_3()`.
The main loop can then go along these lines:

    void loop()
    {
        static int periodIndex = 0;  // increasing every 10 ms

        static bool led1active = false;
        if (periodIndex == 0)
            led1active = true;
        if (led1active)
            led1active = update_led_1();

        static bool led2active = false;
        if (periodIndex == 1000)
            led2active = true;
        if (led2active)
            led2active = update_led_2();

        static bool led3active = false;
        if (periodIndex == 1000)
            led3active = true;
        if (led3active)
            led3active = update_led_3();

        if (++periodIndex == 4000)
            periodIndex = 0;
        delay(10);
    }

Notice the idiom `if (led1active) led1active = update_led_1();`. This
will be executed on every loop iteration, it will increase the LED
brightness if the LED is supposed to be active, and it will set
`led1active` to false when the brightness ramp is complete.

There is something I do not like in the solution I am suggesting here:
the copy-and-paste programming paradigm. If I am allowed to use C++
constructs, then I would encapsulate the ramp logic in a C++ class:

    class RampingLed {
        const uint8_t pin;
        bool active;
        uint8_t level;
    public:
        RampingLed(uint8_t pin)
            : pin(pin), active(false), level(0) {}
        void start() {
            active = true;
            level = 0;
        }
        void update() {
            if (!active) return;
            analogWrite(pin, level++);
            if (level == 0)
                active = false;
        }
    };

Then the logic of the main program would appear more straightforward:

    RampingLed led1(LED1), led2(LED2), led3(LED3);

    void loop()
    {
        static int periodIndex = 0;  // increasing every 10 ms

        // Start the LEDs at the appropriate times.
        if (periodIndex == 0)
            led1.start();
        if (periodIndex == 1000)
            led2.start();
        if (periodIndex == 1500)
            led3.start();

        // Update every LED.
        led1.update();
        led2.update();
        led3.update();

        if (++periodIndex == 4000)
            periodIndex = 0;
        delay(10);
    }


message:
How to store/get MIDI SystemExclusive data?

In the MIDI library from the Arduino (FourtySeven MIDI library), there exist a function to get the length and bytes of a System Exclusive message:

[Functions][1]

    getSysExArray()
    template<class SerialPort , class Settings >
    const byte * MidiInterface< SerialPort, Settings >::getSysExArray

    getSysExArrayLength to get the array's length in bytes.

However, since the Arduino Mega (in my case) has only 8 KB of memory, how can I get a MIDI SysExclusive message which is longer?

Also, I even have added a 128 KB SRAM (23LC1024), but that doesn't help me if I cannot store it in pieces.

Ignacio Vazquez-Abrams mentioned I should 'read' the message, however what message do I get if the system exclusive message is too large to be stored in (internal) SRAM? The read message (see [here][2] also does not have a partial read.

Update:

After a test with a large message, it seems the message is not received by the Arduino MIDI library.

  [1]: http://arduinomidilib.fortyseveneffects.com/a00042.html#gaed0ea7484ddde16f22f6fb5220696946
  [2]: http://arduinomidilib.fortyseveneffects.com/a00042.html#ga77b72b026ff0096aa7157d012405e365

body:
This library tries to make its programming interface as simple as possible, which means that SysEx messages are put completely into a buffer in the internal memory, which means that larger messages cannot be handled.

The only way to handle larger messages is to read the bytes directly from the serial port, and parse the MIDI messages yourself. (The [MIDI specification](https://www.midi.org/specifications/item/the-midi-1-0-specification) has a helpful flowchart about MIDI parsing in the first appendix.) When you have detected the start of your large SysEx, you can then do whatever you want with the following bytes, e.g., handling them as a stream, or write them to external RAM)^.


message:
How to map sensor analog output voltage

My sensor output voltage values ranges from 0.6 V - 3 V. How can I convert this voltage values to ppm in the range 0-1000? Upon exposure to CO gas: 0 ppm = 0.6 V , 500 ppm = 1.52 V and 1000 ppm = 3.01 V. Which means that the sensor cannot detect under 214 ppm (approx). Can you please help with mapping the sensor output values as ppm in the serial monitor? thnk u

    // the setup routine runs once when you press reset:
        void setup() {
          // initialize serial communication at 9600 bits per second:
          Serial.begin(9600);
        }

        // the loop routine runs over and over again forever:
        void loop() {
          // read the input on analog pin 0:
          int sensorValue = analogRead(A0);
          // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
          float voltage = sensorValue * (5.0 / 1023.0);

          // print out the value you read:
          Serial.println(voltage);

        }

body:
On page 4 of the datasheet,

> Left side value of detection range (zero point) is corresponding to left side value of voltage output range,but right side value of detection(max detection value) is not corresponding to the right side value of voltage output range.

Thus, 0ppm would correspond to 0.6V, for CO. And 1000ppm *does not* necessarily correspond to 3V.

Assuming that 500ppm = 1.52V was obtained from the "inspection report", you now have two reference points, (0, 0.6) and (500, 1.52).

Further below on the same page, a formula for `N` is given, which, points towards a linear response of Vo with respect to ppm. Thus, you can use the [`map()`][1] function to do the linear mapping from voltage to ppm.

Note that `map()` only works with integers, so instead of mapping voltage (0.6 - 1.52) to ppm, you should directly map the analogRead value (123 - 311) to ppm to get better accuracy. Other wise, implement your own mapping using floats.

  [1]: https://www.arduino.cc/en/Reference/Map


body:
This Codes works for you :)

    int SensorPin = A0;
    int Readings;
    int Min = 0;    // This is the Min reading of the sensor
    int Max = 614; // This is the Max reading of the sensor
    int Desired_Min = 0; // this is the desired number that you want converted with min reading of the sensor
    int Desired_Max = 1000; // this is the desired number that you want converted with max reading of the sensor

    void setup(){
     Serial.begin(9600);
     pinMode(SensorPin, INPUT);
     }

    void loop(){
      Readings = analogRead(SensorPin);
      Readings = map(Readings, Min , Max, Desired_Min, Desired_Max);
       Serial.println("Mapped Value:"+Readings);

    }

I Strongly prefer you to note the min and max reading Value of your sensor with arduino and replace the 'Min' and 'Max' according to that in the programm....


body:
In the main loop, `sensorValue` is assigned to store the raw analog value read from the potentiometer. Arduino has an `analogRead` range from 0 to 1023, and an `analogWrite` range only from 0 to 255, therefore the data from the potentiometer needs to be converted to fit into the smaller range before using it to dim the LED.

In order to convert this value, use a function called `map()`:

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

    outputValue = map(sensorValue, 0, 1023, 0, 255);

`outputValue` is assigned to equal the scaled value from the potentiometer. `map()` accepts five arguments: The value to be mapped, the low range and high values of the input data, and the low and high values for that data to be remapped to. In this case, the sensor data is mapped down from its original range of 0 to 1023 to 0 to 255.

The newly mapped sensor data is then output to the `analogOutPin` dimming or brightening the LED as the potentiometer is turned. Finally, both the raw and scaled sensor values are sent to the Arduino Software (IDE) serial monitor window, in a steady stream of data.

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

    // These constants won't change. They're used to give names to the pins used:
    const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
    const int analogOutPin = 9; // Analog output pin that the LED is attached to

    int sensorValue = 0;        // value read from the pot
    int outputValue = 0;        // value output to the PWM (analog out)

    void setup() {
      // initialize serial communications at 9600 bps:
      Serial.begin(9600);
    }

    void loop() {
      // read the analog in value:
      sensorValue = analogRead(analogInPin);
      // map it to the range of the analog out:
      outputValue = map(sensorValue, 0, 1023, 0, 255);
      // change the analog out value:
      analogWrite(analogOutPin, outputValue);

      // print the results to the Serial Monitor:
      Serial.print("sensor = ");
      Serial.print(sensorValue);
      Serial.print("\t output = ");
      Serial.println(outputValue);

      // wait 2 milliseconds before the next loop for the analog-to-digital
      // converter to settle after the last reading:
      delay(2);
    }

Few useful commands while mapping any analog output values:

- map()
- analogRead()
- analogWrite()
- serial()
- AnalogInput - Use a potentiometer to control the blinking of an LED.
- AnalogWriteMega - Fade 12 LEDs on and off, one by one, using an Arduino or Genuino Mega board.
- Calibration - Define a maximum and minimum for expected analog sensor values.

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

        /*
          Calibration

         Demonstrates one technique for calibrating sensor input. The sensor readings
          during the first five seconds of the sketch execution define the minimum and
          maximum of expected values attached to the sensor pin.

          The sensor minimum and maximum initial values may seem backwards. Initially,
          you set the minimum high and listen for anything lower, saving it as the new
          minimum. Likewise, you set the maximum low and listen for anything higher as
          the new maximum.

          The circuit:
          - analog sensor (potentiometer will do) attached to analog input 0
          - LED attached from digital pin 9 to ground

          created 29 Oct 2008
          by David A Mellis
          modified 30 Aug 2011
          by Tom Igoe

          This example code is in the public domain.

          http://www.arduino.cc/en/Tutorial/Calibration
        */

        // These constants won't change:
        const int sensorPin = A0;    // pin that the sensor is attached to
        const int ledPin = 9;        // pin that the LED is attached to

        // variables:
        int sensorValue = 0;         // the sensor value
        int sensorMin = 1023;        // minimum sensor value
        int sensorMax = 0;           // maximum sensor value

        void setup() {
          // turn on LED to signal the start of the calibration period:
          pinMode(13, OUTPUT);
          digitalWrite(13, HIGH);

          // calibrate during the first five seconds
          while (millis() < 5000) {
            sensorValue = analogRead(sensorPin);

            // record the maximum sensor value
            if (sensorValue > sensorMax) {
              sensorMax = sensorValue;
            }

            // record the minimum sensor value
            if (sensorValue < sensorMin) {
              sensorMin = sensorValue;
            }
          }

          // signal the end of the calibration period
          digitalWrite(13, LOW);
        }

        void loop() {
          // read the sensor:
          sensorValue = analogRead(sensorPin);

          // apply the calibration to the sensor reading
          sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

          // in case the sensor value is outside the range seen during calibration
          sensorValue = constrain(sensorValue, 0, 255);

          // fade the LED using the calibrated value:
          analogWrite(ledPin, sensorValue);
        }

- Fading - Use an analog output (PWM pin) to fade an LED.
- Smoothing - Smooth multiple readings of an analog input.


message:
Issues uploading to atmega324pb w/ adruino as ISP

I've been having some issues programming a new atmega324pb I have on a custom board. I set up an old adruino UNO as an ISP by uploading the ArduinoISP sketch, setting the programmer to "Arduino as ISP" and then using the "Upload using programmer" option but to no avail. Here is the verbose error message that the console logs:

    System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

 avrdude: AVR device initialized and ready to accept instructions

 Reading | ################################################## | 100% 0.03s

 avrdude: Device signature = 0x000000 (retrying)

 Reading | ################################################## | 100% 0.02s

 avrdude: Device signature = 0x000000 (retrying)
I think it might be an issue with Arduino possibly targeting a chip other than atmega324pb that I'm using, but I'm not sure. I don't know of any official arduino boards that utilize the 324pb. The main issue that I see is that avrdude can't find the device signature. I've see others mention it might be faulty wiring, but I made sure all connections are intact.

body:
In case anyone was wondering, I solved the problem.
Unfortunately I wasn't able to figure out how to upload it using Arduino as ISP, but I was able to get it to work with an [AVR Pocket Programmer][1] from Sparkfun. If you decide to use this, check out [this drivers guide.][2] It will It'll save massive headache getting the usb device to be recognized.

**IMPORTANT FOR ATMEGA324PB USERS!!!**
The atmega324pb is apparently not a default microcontroller in avrdude. You need to add it to the toolchain manually. You can do this by following this blog:
https://hackaday.io/project/9313-uino-mini-super-atmega328pb/log/31003-easy-way-to-a-toolchain-for-the-atmega328pb
It is the same process to add any Microchip microcontroller to avrdude, so this guide will work for the atmega324pb (did it firsthand). From there, you can also add a custom entry to Arduino's boards.txt config file if you'd like to use the Arduino IDE for development. I didn't mind working the command line, but having it in Arduino definitely streamlines the proccess of compiling the .hex and uploading it in one go.

Here is the custom entry I added to Arduino's boards.txt file for the Atmega324pb. All the data was gathered from the datasheet:

    ####   ATmega324PB    ####
    m324p.name=Atmega324pb
    m324p.upload.via_ssh=true

    m324p.vid.0=0x0424
    m324p.pid.0=0x2740

    m324p.upload.tool=avrdude
    m324p.upload.protocol=usbtiny
    m324p.upload.maximum_size=28672
    m324p.upload.maximum_data_size=2560
    m324p.upload.speed=57600
    m324p.upload.disable_flushing=true
    m324p.upload.use_1200bps_touch=true
    m324p.upload.wait_for_upload_port=true

    m324p.bootloader.tool=avrdude
    m324p.bootloader.low_fuses=0x62
    m324p.bootloader.high_fuses=0xD9
    m324p.bootloader.extended_fuses=0x0f

    m324p.build.mcu=atmega324pb
    m324p.build.f_cpu=1000000L
    m324p.build.vid=0x0424
    m324p.build.pid=0x2740
    m324p.build.usb_product="Arduino m324pb"
    m324p.build.board=AVR_m324pb
    m324p.build.core=arduino
    m324p.build.variant=standard
    m324p.build.extra_flags={build.usb_flags}

Note that I set the upload.tool to avrdude, and the upload.protocol to usbtiny since I was using the pocket AVR programmer.

**IMPORTANT!!!**  The high fuse bit in this config also is 0xD9, instead of the default 0x99. I changed one fuse bit to disable JTAG and regain access to GPIO pins. To my knowledge Arduino wasn't setting fuse bits when uploading with the programmer, but this is an important note to take. If you need to use GPIO pins that share JTAG functionality, run the avrdude command line to set the high fuse bit appropriately. (0xD9 for me).

  [1]: https://www.sparkfun.com/products/9825
  [2]: https://learn.sparkfun.com/tutorials/pocket-avr-programmer-hookup-guide#installing-drivers


message:
ESP32 wifi module

I want to connect my arduino uno rev3 to wifi. The best option I found was esp8266. After searching about it I found that it is succeeded by esp32. But I am not able to find much information about it. So I just wanted to ask if esp32 module exists as a addon to arduino or is it a board on its own. It will be really helpful if somebody can send the link from where I can buy this module(and not the board) and how to connect it to arduino.

body:
ESP32 is not a replacement for the ESP8266.  There is quite a bit of info out there, but mostly in Chinese.  If you were to use an ESP32 to provide WIFI its like using a Formula 1 car as a mobility scooter (Rascal in American?) It will do the job, but its really not suitable.

You can buy ESP32 on eBay or AliExpress, but really you shouldn't for this task.  Stick with an ESP8266.

BTW People will mark this as off topic, because it isn't strictly Arduino related.


message:
Only 2 decimal places in printed float

There was a similar thread before but it didn't solve my problem. I had an issue with sending GPS data, which is float, and I couldn't receive the float with the same amount of significant figures as I was sending. I always received a number with 2 digits after a decimal point. So I started debugging and wrote this simple code just to check if floats work as intended:

    #include <SoftwareSerial.h>
    void setup() {
    Serial.begin(9600);
    }
    void loop() {
    float number1;
    number1=1.45436;
    Serial.print(number1);
    delay(200);
    }
And the serial monitor showed 1.45 as an output. How can increase the precision of the float I am saving in memory?

body:
Multiply your float by 10000 (or whatever number you wish), send it as an integer, and convert the received integer back to float.

Alternatively change the library or write your own.


body:
By default, [`Serial.print()`][1] prints floats with two decimal digits.

    float num = 7.875;
    Serial.println(num, 4);
will print `num` with 4 decimal digits, thus: 7.8750.

The precision of float is not decreased in the way you think it decreases. [See this answer for a better explanation][2].

  [1]: https://www.arduino.cc/en/Serial/Print
  [2]: https://arduino.stackexchange.com/a/10037/17164


body:
By default, the Serial print function shows only 2 decimals, however I'm sure the float has the full (unrounded) value, even if it does not show it.

You can read about it in the official documentation [here][1]

With the following code you can use more decimals (fragment from the official documentation):

    -Serial.println(1.23456, 0) gives "1"
    -Serial.println(1.23456, 2) gives "1.23"
    -Serial.println(1.23456, 4) gives "1.2346"

Also, probably the next link (PrintFloat) will help:

[PrintFloat][2]

It works roughly by iterating through the digits and printing them.

  [1]: https://www.arduino.cc/en/Serial/Print
  [2]: http://playground.arduino.cc/Code/PrintFloats


message:
Receiving Multiple data on Arduino Serial

I am writing a very simple code in Arduino Nano, in which I am reading data that I send on Serial. Here is the code snippet.

    int incomingByte ;

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

    void loop() {

        if (Serial.available() > 0) {

                incomingByte = Serial.read();

                Serial.print("I received: ");
                Serial.println(incomingByte);
        }
}

When I send 'A' , I receive the following output:

I received: 65

I received: 13

I received: 10

What is wrong with the working of Serial Port here?

body:
You send a string "A"

However, to denote the end, a carriage line (code 13) + line feed (code 10) is sent.

So what is sent is actually an 'A' character followed by a return.
This way you also know when a new line starts

Just strip off the return (13,10) items if you do not need them.

If you do not want to send the return, try sending 'A' (which is the character A, and not the string A.

Update

You can ignore them by:

         if ((incomingByte != 10 && (incomingByte != 13))
         {
            Serial.print("I received: ");
            Serial.println(incomingByte);
         }

If you only want printable characters, check if you can use the isprint function ([isprint function][1]

so it should look like

        if (isprint(incomingByte))
        {
            Serial.print("I received: ");
            Serial.println(incomingByte);
        }

  [1]: http://www.cplusplus.com/reference/cctype/isprint/


body:
nothing is wrong, it's to do with operator overloading and the print function trying to be helpful.

if you change this line:

    int incomingByte ;

to this:

    char incomingByte ;

it should display correctly

And the extra characters are because the software on the computer is sending line endings. these may be a linefeed with or without a carriage return. you could either just ignore them, or make use of them to create multi character commands (if you need them)


body:
this is just because you are typing a letter i  the serial monitor ans in your code your are declaring it as a integer 'int' so you not need to worry about that just try the following code

    int incomingByte ;

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

    void loop() {

        if (Serial.available() > 0) {

                incomingByte = Serial.read();
                Serial.write(incomingByte);
        }
    }
--------------------------------   OR    ---------------------------------------

    char incomingByte ;

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

    void loop() {

        if (Serial.available() > 0) {

                incomingByte = Serial.read();
                Serial.print(incomingByte);
        }
    }

Both of the programs will work try that.......


message:
Arduino Leonardo(Atmega32u4) - Detecting if USB is connected to a computer?

The closest thing I can find is if(Serial) but that only returns true if there's a serial port open.

The function I want, ideally, should:

Return true if plugged into a computer

Return false if plugged into a USB power bank

Return false if not plugged in at all(Running off of its own lithium cell)

body:
`ADDEN` of `UDADDR` is set if the '32U4 has been assigned a USB address by the host and the firmware wants to enable USB connectivity.

    UDADDR & _BV(ADDEN)


message:
Check to see that String only contains .csv style numbers

I'm looking to determine if an Arduino **S**tring contains any other character than those that would be in the `[number],[number]'\r''\n'`where `[number]` could be positive or negative.

I know I can run a for down the entire string and use `if(isDigit([char]) || isWhitespace([char])||[char]=='-')` however, I imagine there's a better way to do this.

Could I (for example) convert the String to an array of values and search the array for any value that doesn't correspond to the characters I'm looking for? Or is there a better way to check this out?

body:
There is a better way, which is called regular expressions (or regexp). However, afaik these are not supported by Arduino by default.

However, I'm sure you can find some 'generic C++' class that can handle them.

For that, it's best to check on StackOverflow.com probably.

After a short check, on the Arduino forum there is a library available for regexp:

[library][1]

It is created by Nick Gammon, so all credits are for him.

  [1]: http://forum.arduino.cc/index.php?topic=59917.0


message:
How can I control the speed and direction of dc motor at the same time (through Bluetooth

I am working on a project of an arduino car it's simple really i know how to control the speed and direction using simple button but I was looking for an upgrade so I add a virtual joystick in my app now It can send 2 values first is the angle where the pointer of the joystick is which will be used to control the direction. And the distance between the center of the joystick and the pointer will be used to control the speed, problem is they are both int values how can I make the arduino differentiate between both values ? also they would be sent simultaneously over Bluetooth which might be a problem as well

body:
Use delimiters to separate the two values you are sending over bluetooth.

Something like

    "30,5\n"

instead of

    "30\n"
    "5\n"

On the Arduino side, read the the incoming string into a `char` array and add a `\0` after the last read character to make it a C string. The use [`strtok()`][1] to parse the C string and [`atoi()`][2] or [`atof()`][3] to convert the parsed C strings to an `int ` or `float`.

See [this answer][4] for more information about parsing a string.

  [1]: http://www.cplusplus.com/reference/cstring/strtok/
  [2]: http://www.cplusplus.com/reference/cstdlib/atoi/
  [3]: http://www.cplusplus.com/reference/cstdlib/atof/
  [4]: https://arduino.stackexchange.com/a/1033/17164


body:
I would say it would be the best way to use a H-bridge motor driver such as L293N. With it you can simply drive a DC motor both ways and even control it's speed.

Make the connection as shown on picture below, but connect wires of both motors to the same motor and PWM_SPEED_CTRL are channels connected to the Arduino. Don't forget to add relays between pins: 3-1, 6-2 and 11-1, 14-2, which would determine the turning direction.

If you don't understand certain thing, just ask and I'll try to reply ASAP.

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

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


message:
Convert int to char[]

I'm looking to convert an int value to a char array. currently I've found the following will return `[number]`

    int num = [number]
    str = String(num);
    str.toCharArray(cstr,16);
    Serial.println(cstr);

However, per [Majenko's The Evils of Arduino Strings](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/) I feel like this code would make my Arduino's heap look like swiss cheese. Is there a better way to change an `[int]` into a `char[n]` array that avoids the **S**tring class?

body:
`itoa` is the best route:

    int num = 1234;
    char cstr[16];
    itoa(num, cstr, 10);
    -> "1234"
You can read more about using it [here](http://www.cplusplus.com/reference/cstdlib/itoa/).

If you want more control over the format of the number (and don't mind the increased PROGMEM usage) you can use `sprintf` (or the more secure `snprintf`) to format it:

    sprintf(cstr, "d", num);
    -> "01234"

Or with PROGMEM string constant:

    sprintf_P(cstr, (PGM_P)F("d"), num);
    -> "01234"

Or with more values:

    sprintf_P(cstr, (PGM_P)F("d:d:d"), hours, minutes, seconds);
    -> "03:23:11"


message:
How do I prevent Arduino from running on startup?

I just uploaded a sketch to my Arduino Leonardo, which presses a key on the keyboard. The code was unfortunately bugged and now as soon as the Arduino is powered on, the key is being pressed.

When I try to upload a new sketch that fixes the issue, I am unable to do so as the Arduino is executing the sketch, preventing the new sketch from being uploaded.

How can I prevent the Arduino from executing the sketch once powered on? Pressing the reset button or wiring it in does not work...

body:
The Leonardo should wait a couple of seconds after resetting to see if a new sketch arrives.

* Power off the board completely (remove the USB cable).

* Hold down the Reset button, and *keep it held down* (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting.

* Still holding down Reset, reconnect the USB cable.

* Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).


message:
5V and Vin pins on Arduino

I am working on connecting two Arduino boards (Arduino Uno & Arduino Nano). I am trying to run a stepper motor  connected to Arduino Nano with two digital Pins on Arduino Uno to alter the direction of the stepper motor(BYJ48) connected to the arduino Nano.
While making connections I attached the pins as:

1] 5V  (UNO) -> 5V (NANO) & GND (UNO) -> GND (NANO)

2] 5V (UNO)  -> 5in (NANO) & GND (UNO) -> GND (NANO)

Both [1] & [2] worked fine initially but I kept the arduino powered and tried toggling the Vin with 5v. Nothing went wrong in the beginning but later fumes started coming out and I dont know the reason why?
Was that because I kept the power on while toggling between Vin & 5v ?
NOTE: besides the code and success in running the possible reason of fumes is much important here.

body:
You can try software serial communication between the two boards. Any two digital pins of one board can be used as Rx and Tx, and make sure the roles of Rx and Tx are reversed on the other board. See the Software Serial library:
https://www.arduino.cc/en/Reference/SoftwareSerial


message:
DFRobot GPS init error [Arduino Uno, SIM808]

i have problem with initialization DFRobot SIM808 actually when i try to recieve gps data by SoftwareSerial only it does works (i mean examples based on sending and reading command to and from serial's), and recieve data but very long string of data and i need only **Latitude** and **Longitude** and i think using DFRobot will be the easiest way to extract the data i need. So the simple test program like this one is not working:

        /*
    ### Get GPS data
    1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
    2. Open the SIM808_GetGPS example or copy these code to your project
    3. Download and dial the function switch to Arduino
    4. open serial helper
    4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

    create on 2016/09/23, version: 1.0
    by jason

    */
    #include <DFRobot_sim808.h>
    #include <SoftwareSerial.h>

    #define PIN_TX    7
    #define PIN_RX    8
    SoftwareSerial mySerial(PIN_TX,PIN_RX);
    DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

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

      //******** Initialize sim808 module *************
      while(!sim808.init()) {
          delay(1000);
          Serial.print("Sim808 init error\r\n");
      }

      //************* Turn on the GPS power************
      if( sim808.attachGPS())
          Serial.println("Open the GPS power success");
      else
          Serial.println("Open the GPS power failure");

    }

    void loop() {
       //************** Get GPS data *******************
       if (sim808.getGPS()) {
        Serial.print(sim808.GPSdata.year);
        Serial.print("/");
        Serial.print(sim808.GPSdata.month);
        Serial.print("/");
        Serial.print(sim808.GPSdata.day);
        Serial.print(" ");
        Serial.print(sim808.GPSdata.hour);
        Serial.print(":");
        Serial.print(sim808.GPSdata.minute);
        Serial.print(":");
        Serial.print(sim808.GPSdata.second);
        Serial.print(":");
        Serial.println(sim808.GPSdata.centisecond);
        Serial.print("latitude :");
        Serial.println(sim808.GPSdata.lat);
        Serial.print("longitude :");
        Serial.println(sim808.GPSdata.lon);
        Serial.print("speed_kph :");
        Serial.println(sim808.GPSdata.speed_kph);
        Serial.print("heading :");
        Serial.println(sim808.GPSdata.heading);
        Serial.println();

        //************* Turn off the GPS power ************
        sim808.detachGPS();
      }

    }

[![error][1]][1]

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

body: We had the same error in the code. But we managed to solve it! You have to insert the SIM CARD to work. We do not know why, but it works!


body:
{Original answer by [Onuralp Arslan](https://arduino.stackexchange.com/users/67787/onuralp-arslan)}

gps function of sim808 does not require sim card you only need 9v source with enough current and 1575.42 mHz gps antenna
use this code it will help

    #include <DFRobot_sim808.h>
    #include <SoftwareSerial.h>
    #define PIN_RX 11
    #define PIN_TX 10
    SoftwareSerial mySerial(PIN_TX,PIN_RX);
    DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

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

    //************* Turn on the GPS power************
    if( sim808.attachGPS())
    Serial.println("Open the GPS power success");
    else
    Serial.println("Open the GPS power failure");

    }

    void loop() {
    //************** Get GPS data *******************
    if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
    Serial.print("/");
    Serial.print(sim808.GPSdata.month);
    Serial.print("/");
    Serial.print(sim808.GPSdata.day);
    Serial.print(" ");
    Serial.print(sim808.GPSdata.hour);
    Serial.print(":");
    Serial.print(sim808.GPSdata.minute);
    Serial.print(":");
    Serial.print(sim808.GPSdata.second);
    Serial.print(":");
    Serial.println(sim808.GPSdata.centisecond);

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat,6);

    sim808.latitudeConverToDMS();
    Serial.print("latitude :");
    Serial.print(sim808.latDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.latDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.latDMS.seconeds,6);
    Serial.println("\"");
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon,6);
    sim808.LongitudeConverToDMS();
    Serial.print("longitude :");
    Serial.print(sim808.longDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.longDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.longDMS.seconeds,6);
    Serial.println("\"");

    Serial.print("speed_kph :");
    Serial.println(sim808.GPSdata.speed_kph);
    Serial.print("heading :");
    Serial.println(sim808.GPSdata.heading);

    //************* Turn off the GPS power ************
    sim808.detachGPS();
    }

    }

try this, worked for me without sim card
connect rx of sim808 to arduino 11
tx to 10
and connect grounds of arduino and sim808


message:
Why is a delay(1) necessary before Wire.requestFrom?

I had a problem communicating an nodeMCU with an Arduino Pro Mini with I2C.

To find the culprit, I finally wrote an Echo Server in Arduino: it receives a byte and responds the same byte. In the nodeMCU I wrote a test program: it sends bytes to the Echo Server and verifies the response, in addition to any error conditions in the `Wire` methods.

Both processors are connected GND-GND, VCC-VCC, SDA-SDA and SCL-SCL. SDA and SCL have 10K pull-up resistors. Both are connected via USB to my PC, and I have two serial monitors to trace the execution.

In the tester program line 38 there is a `delay(1)`. If you comment it out, some `requestFrom()` fails randomly with return value != 1, but the Echo Server still received the byte.

As ATmega328 included TWI in the silicon, I can't understand what is failing here and why `delay(1)` seems to solve the problem. What I'm missing here?

**The tester program**

    /*
     * Echo Server Test
     * Send one byte to the Echo Server and read it back.
     * Do it for bytes from 0x01 to 0xDD
     */
    #include <Wire.h>

    #define SLAVE_ADDRESS  42
    byte car = 1; // car to be send to the Echo Server.

    void setup() {
     Serial.begin(9600);
      // We have a nodeMCU con I2C on pins D5 and D6.
     Wire.begin(D5, D6);
     delay(1000);
      Serial.println("");
     Serial.println(" Echo Server Tester");
     Serial.println("---------------------");
     Serial.println("###  Sent   Received");
     delay(1000);
    }

    /*
     * Send one byte in each loop().
     */
    void loop() {
     byte status;

     if(car > 0) {
      do {
       Wire.beginTransmission(SLAVE_ADDRESS);
       int written = Wire.write(car);
       status = Wire.endTransmission();

       switch(status) {
       case 0:
            delay(1); // Comment this out and watch requestFrom() fails.
        if(Wire.requestFrom(SLAVE_ADDRESS, 1) == 1) {
         byte r = Wire.read();
         printChar(car, r);
         car++;
        } else {
         Serial.println("error in return");
         status = 4;
        }

        break;

       case 1:
        Serial.println("Data too long");
        break;

       case 2:
        Serial.println("NACK on address");
        break;

       case 3:
        Serial.println("NACK on data");
        break;

       case 4:
        Serial.println("Some error");
        break;
       }
      }

      while(status != 0);
     }
    }

    /*
     * Utility: print in bytes sent and received
     */
    void printChar(byte s, byte r) {
     Serial.print(s);
     Serial.print(" ");
     printBits(s);
     Serial.print(' ');
     printBits(r);

     if(r != s) {
        //  Mark invalid responses.
      Serial.print(" *");
     }

     Serial.println();
    }

    /*
     * Print a simple byte in binary
     */
    void printBits(int car) {
     byte bit = 0x80;

     for(int i = 0; i < 8; i++) {
      int digit = car & bit;
      Serial.print(digit ? '1' : '0');
      bit >>= 1;
     }
    }

**The Echo Server program**

    /*
     * I2C Echo Server
     * Receive one byte from Master, echo the same byte to Master.
     */
    #define MY_ADDRESS  42

    #include <Wire.h>

    volatile byte received;
    volatile int count = 0;

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

      Wire.begin(MY_ADDRESS);
      Serial.println("--- Echo Server ---");

      Wire.onReceive(receiveCommand);
      Wire.onRequest(sendAnswer);
    }

    void loop() {
      static int lastCount = 0;

      if (count != lastCount) {
        Serial.print(lastCount + 1); Serial.print(" ");
        printChar(received);
        lastCount++;
      }
    }

    /*
     * Receive a byte from Master
     */
    void receiveCommand(int howMany) {
      received = Wire.read();
      count++;
    }

    /*
     * Send a byte to Master
     */
    void sendAnswer() {
      Wire.write(received);
    }

    /*
     * Utility print byte received/sent
     */
    void printChar(byte car) {
      Serial.print("Char ");
      byte bit = 0x80;
      for (int i = 0; i < 8; i++) {
        byte digit = car & bit;
        Serial.print(digit ? '1' : '0');
        bit >>= 1;
      }
      Serial.println();
    }

body:
The 1 millisecond is not needed, try delayMicroseconds with 50 or maybe 20 µs.

The Arduino as a slave is totally different than for example a sensor. The Arduino as a slave uses a combination of hardware and software. The onRequest and onReceive functions are executed while the Arduino keeps the SCL line low. That is called clock pulse stretching.

With an Arduino **Uno** (ATmega328P microcontroller) connected to an Arduino Uno, this delay problem between a write and read on the I2C bus existed for a long time. A few years ago it was solved. It was a bug, a real bug. That delay is no longer needed.
There are still ways to make it unreliable, for example by disabling the interrupts for too long in the slave.

I read that is still exists with the Arduino **Due**. With the Due as a master and for example an ATmega328P (at 3.3V) as a slave, the Due still needs a delay.

The **nodeMCU** and the Raspberry Pi might still have some problems when an Arduino is used as a slave. The Arduino as a slave should at least run at 3.3V or a I2C level shifter should be used.
I don't know if the nodeMCU Wire library supports clock pulse stretching.
That delay might still be needed. Even then, I don't know how reliable the communication will be.

The Wire.endTransmission is the function that transmits the data (not the Wire.write). If that is followed too soon by a Wire.requestFrom and there is a bug in the Wire library, that can cause troubles.


message:
Use 5V pH sensor with 3.3V NodeMCU

I'm trying to use a pH probe with NodeMCU, the problem is that NodeMCU is 3.3V and the pH analog sensor requires 5V, at first I thought using the VIN pin but didn't work, then I used the VU pin from NodeMCU V3 (by Lolin) but it didn't give me the right values, like if it missed more power. Is there any other way? Or any esp8266 board which supports 5V into it's analog input?

body:
Depending on your specific sensor and power supply setup you have following options:

 1. **Change supply voltage**
Most resistive sensors don't have to power anything and will function just fine when supplied with less than 5V. Study the datasheet and make test measurements to find out whether this is suitable.

 2. **Use a voltage divider**
Supply the sensor with 5V and use a simple [voltage divider][1] before    connecting to your MCU and therefore measure 0-3.3V.

 3. **Interface another IC**
Get a small external ADC that can handle 5V readings and may be interfaced by any serial protocol supported by your esp8266 (namely UART and I2C).
[![][3]][3]

  [1]: https://en.wikipedia.org/wiki/Voltage_divider
  [3]: https://i.stack.imgur.com/elOoV.png


body:
The simplest method is just a voltage divider - just as if you were interfacing a 5V logic signal output with a 3.3V input. However it may not work.

A voltage divider will only really be of use if the output of the pH sensor is low impedance. If it's not then you will need a very high impedance voltage divider, and the analog input of the ESP8266 isn't high enough impedance to support a very high impedance voltage divider - it will skew the results horribly.

So you may need to buffer the output of the pH sensor through an op-amp first.

If you use a unity gain non-inverting buffer you can then use a voltage divider to reduce the output voltage.

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

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

<!-- End schematic -->

Alternatively, as others have suggested, use an external 5V ADC chip and logic level conversion to communicate with the ESP8266.


body:
Old topic, but in case it shows up in searches, like the one I was just doing ... I run a 5v ultrasonic SR04 off a Lolin nodemcu, and if you connect to "VU" on the Lolin nodemcu, you will get 5v.

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

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


body:
Have you guys checked the specification of the AiThinker's ESP-12s? There's a piece of description in its Chinese edition document that says if you are hooking up other devices which work in 5v, you have to use the Level converter circuit in between.
[![enter image description here][1]][1]

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


message:
Help What am I doing wrong? Matrix Led

I'm new and im trying out the Matrix LED
heres my code

    #include <LedControl.h>

    LedControl lc = LedControl(12, 11, 10, 1);

    unsigned long delayime = 100;

    void setup()
    {
      lc.shutdown(0, false);
      lc.setIntensity(0, 8);
      lc.clearDisplay(0);
    }

    void writeArduinoOnMatrix()
    {
      byte H[10] = {8, 8, B01100110, B01100110, B01100110, B01111110, B01111110, B01100110, B01100110, B01100110};
      byte E[10] = {8, 8, B01111110, B01111110, B01100000, B01111110, B01111110, B01100000, B01111110, B01111110};
      byte L[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};
      byte O[10] = {8, 8, B01100000, B01100000, B01100000, B01100000, B01100000, B01100000, B01111110, B01111110};

      lc.setRow(0, 0, H[0]);
    }

I keep on getting this error no matter what.
collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

Help What am I doing wrong?

body:
A ld error normally means a link error, i.e. you call a function that is not defined.

Are you sure it is the complete error? That it does not show which function you miss?

Also, I notice:

- function writeArduinoOnMatrix never seems to be called, or you didn't post the full code?
- In writeArduinOnMatrix, you declare 4 arrays, but you use only one (H).
- Typo in: unsigned long delayime = 100;  ... this should be delayTime


body:
Unfortunately I think you are missing the actual error message and have just copied the result.  I suspect if you scroll back up through the output it will say loop is missing.

All Arduino sketches (well almost all) have to have `setup()` and `loop()` functions.  The underlying 'stuff' will call `setup()` once and `loop()` repeatedly.

I hate global variables, but in this case I would be tempted to move those arrays out of the function and make the constant global values.  That way they will be in memory as the Arduino boots and you won't have to waste processor cycles setting them up.

It may be a silly question, but are you using the right hardware?  This might help check that http://playground.arduino.cc/Main/LedControl


message:
(ESP8266) Check if a SSID is in range

I need to check if a given SSID is in range. Would be good if it didn't disconnect from the current wifi network that it's connected to, but it doesnt matter, i just need to see if a SSID is in range, whether it does disconnect or not.
It should be something like this:

    if(WiFi.SSID(checkforthisSSID)) {
      //do something
    }
Thanks.

body:
Not so tough it is possible just try the bellow code :)

    void loop() {
      Serial.println("scan start");

      // WiFi.scanNetworks will return the number of networks found
      CheckPossibility();
      }

     CheckPossibility(){
     int n = WiFi.scanNetworks();
      Serial.println("scan done");
      if (n == 0)
        Serial.println("no networks found");
      else
      {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i)
        {
          // Print SSID and RSSI for each network found
          if(WiFi.SSID(i) == "REPLACE THIS WITH YOUR SSID"){ //enter the ssid which you want to search
          Serial.println("The network you are looking for is available");
          }
        }
      }
      Serial.println("");

      // Wait a bit before scanning again
     // delay(5000);
    }


message:
Reliably measuring the energy consumption of arduino running sketch

I would like to know if there is a programmatic way of measuring the energy consumption of a sketch or at least if this is possible via external devices.

My aim is to compare the energy consumption of two devices, connected to usb, running slightly modified versions of the same sketch e.g., one using crypto and one without using crypto.

body:
> programmatic way of measuring t

Not sure what you meant by that but typically you can use a high side current sense amplifier to get a measurement of the current. Then adv a known voltage to get vcc. That known voltage could be the internal reference, if available

In some cases a resistor on vcc can be used to measure current, together with two dividers.


message:
Error running the code

The error I get is as follows:

    F:\Josh\GIZDUINO PROJECT\Joshua\arduino-1.8.3\libraries\arduino-ledcube-master\examples\ledcube\ledcube.pde: In function 'void loop()':

    ledcube:49: error: taking address of temporary array
             cube.createFrame((byte[]) {0,6, 1,6, 2,6}, 6, 80),
                                                             ^
    ledcube:50: error: taking address of temporary array
             cube.createFrame((byte[]) {0,7, 1,7, 2,7}, 6, 70),
                                                             ^
    ledcube:51: error: taking address of temporary array
             cube.createFrame((byte[]) {0,8, 1,8, 2,8}, 6, 60),
                                                             ^
    ledcube:52: error: taking address of temporary array
             cube.createFrame((byte[]) {0,5, 1,5, 2,5}, 6, 50),
                                                             ^
    ledcube:53: error: taking address of temporary array
             cube.createFrame((byte[]) {0,2, 1,2, 2,2}, 6, 40),
                                                             ^
    ledcube:54: error: taking address of temporary array
             cube.createFrame((byte[]) {0,1, 1,1, 2,1}, 6, 30),
                                                             ^
    ledcube:55: error: taking address of temporary array
             cube.createFrame((byte[]) {0,0, 1,0, 2,0}, 6, 20),
                                                             ^
    ledcube:56: error: taking address of temporary array
             cube.createFrame((byte[]) {0,3, 1,3, 2,3}, 6, 10)
                                                             ^
    F:\Josh\GIZDUINO PROJECT\Joshua\arduino-1.8.3\libraries\arduino-ledcube-master\examples\ledcube\ledcube.pde:115:38: warning: narrowing conversion of '(((int)cube.LedCube::getLevels()) + 1)' from 'int' to 'byte {aka unsigned char}' inside { } [-Wnarrowing]
         byte planes[] = {cube.getLevels()+1,cube.getLevels(),cube.getLevels()*2,1};
                                          ^
    F:\Josh\GIZDUINO PROJECT\Joshua\arduino-1.8.3\libraries\arduino-ledcube-master\examples\ledcube\ledcube.pde:115:74: warning: narrowing conversion of '(((int)cube.LedCube::getLevels()) * 2)' from 'int' to 'byte {aka unsigned char}' inside { } [-Wnarrowing]
         byte planes[] = {cube.getLevels()+1,cube.getLevels(),cube.getLevels()*2,1};
                                                                              ^

    exit status 1
    taking address of temporary array

body:
You have to declare your array by itself, with a name, like this:

    void fcn(byte p[]) {
      Serial.print("p[1]=");
      Serial.println(p[1]);
    }

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

      byte ar[] = {0, 6, 1, 6, 2, 6};
      fcn( ar);
      }

    void loop() {
    }

And the warning are for using a `int` where a `byte` is expected. It's just a warning. There is no problem as long the values are between 0 and 255.


body:
Three remarks to your question.

1. Avoid using UPPERCASE as that is considered to be a typographical notation for shouting. See http://practicaltypography.com/all-caps.html

2. The compiler error is due to that you are using a temporary byte vector as parameter. You should declare the vector as a local or global variable and pass the reference. See https://stackoverflow.com/questions/42332229/how-to-pass-a-temporary-array or web-search for more info.

3. The compiler warning is due to an implicit conversion from int to byte. The conversion may result in a loss of precision thus the warning. You can use a type cast to avoid this. The type case will tell the compiler that you know what you are doing.

Cheers!


message:
Call class B from Class A

I have two classes in my sketch that are independent of each other (a serial output and an LCD display) A simplified structure of my code is as follows:

    class A
    {
      public:
       int x;
       void afoo()
       {
         x=1;
       }
       void afoo2
       {
         x=ClassB.bfoo+1;
       }
    };

    A ClassA;

    class B
    {
      public:
        int y;
        void bfoo()
        {
          y=ClassA.afoo+2;
        }
    };
    B ClassB;

However, if I don't comment out  `class afoo2` I get the following error:
>exit status 1
>
>`'ClassB' was not declared in this scope`

I'm guessing that this is because I haven't yet created `B ClassB` while class is being defined. Is there a way I can do what I'm intending here?

body:
What you are trying to do is call class A from B and vice versa.

What you could try, is remove one of the functions out of the class, possibly to a third class, so class A and B depend on a class C and not on each other.

However, if they are really depend, you can split up the files in header/implementation files.

Instead of using two classes directly, pass them as a parameter (reference).

Somewhat like this (not tested)

File A.h:

    class A
    {
      public:
       int x;
       void afoo();
       void afoo2(B& b);
    };

File A.cpp:

    #include "A.h"
    #include "B.h"

    void A::afoo()
    {
      x=1;
    }

    void A::afoo2(B& b)
    {
      x=b.bfoo+1;
    }

file B.h:

    class B
    {
      public:
        int y;
        void bfoo(A& a);
    }

file B.cpp:

    #include "A.h"
    #include "B.h"

    B::void bfoo(A& a)
    {
      y=a.afoo+2;
    }

And your ino file you declare A and B.

    #include "A.h"
    #include "B.h"

    A ClassA;
    B ClassB;

    ClassA.afoo(ClassB);
    ClassB.bfoo(ClassA);


body:
You can't see non-static member variables in a class like that.  The closest is to make it `static`, which means you get one and only one copy of the variable across all instances of your class:

    class ClassB;
    class ClassA {
        public:
            int x;
            void foo();

    };
    class ClassB {
        public:
            static int bfoo;
    };

    void ClassA::foo() {
        x = ClassB::bfoo + 1;
    }

However I suspect that isn't what you want. I suspect you actually want to see the `bfoo` value stored in class instance `B` - so you need to tell you `classA` instance `A` what and where `B` is. To do that you will have to pass it when constructing or during some other setup phase.  If you want A to know B and B to know A you can't easily do it during construction, so you will have to do it at a later stage:

    class ClassB;

    class ClassA {
        public:
            ClassB *B;
            int fooa;
            void begin(ClassB *b) {
                B = b;
            }
            void foo();
    };
    class ClassB {
        public:
            ClassA *A;
            int foob;
            void begin(ClassA *a) {
                A = a;
            }
            void foo();
    };

    void ClassA::foo() {
        fooa = B->foob + 1;
    }

    void ClassB::foo() {
        foob = A->fooa + 1;
    }

    ClassA A;
    ClassB B;

    void setup() {
        A.begin(&B);
        B.begin(&A);
    }

    void loop() {

    }


message:
FPC1020 + WeMos D1 Mini

I have a [FPC1020am][1] that work perfectly with arduino and a [ESP8266 D1 Mini V2 NodeMcu 4MB Lua][2] that can connect to server.

How can I connect the **FPC1020** direcetly to **ESP8266 D1 Mini** to scan finger and send matched id to server?

here is my code and error:

    #include <NewSoftSerial.h>
    #include <ESP8266WiFi.h>
    #include <WiFiClientSecure.h>
    #include <FPC1020.h>

    extern unsigned char l_ucFPID;
    extern unsigned char rBuf[192];  //Receive return data
    #define sw_serial_rx_pin 2 //  Connect this pin to TX on the FPC1020
    #define sw_serial_tx_pin 3 //  Connect this pin to RX on the FPC1020

    const char* ssid = "-------";
    const char* password = "-------";

    const char* host = "-------";
    String url = "-------?id=";

    NewSoftSerial swSerial(sw_serial_rx_pin, sw_serial_tx_pin); // Fingerprint serial (RX, TX)
    FPC1020 Finger(&swSerial);

    void setup() {
      Serial.begin(115200);
      Serial.print("connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      pinMode(4, INPUT);
    }

    void loop() {
      Serial.println("Please put your finger on the Sensor.");
      while(Serial.available()<=0);

      if( Finger.Search()){
        Serial.print("Success, your User ID is: ");
        url = "-------?id=" + l_ucFPID;
        Serial.println( l_ucFPID, DEC);

        WiFiClient client;
        if (!client.connect(host, 80)) {
          Serial.println("connection failed");
          return;
        }

        client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                     "Host: " + host + "\r\n" +
                     "User-Agent: BuildFailureDetectorESP8266\r\n" +
                     "Connection: close\r\n\r\n");

        String line = "";
        while (client.connected()) {
          line = client.readString();
        }

        Serial.println(line);

      }
      else {
        Serial.println("Failed, please try again.");
      }
    }

And the error is:

    C:\Program Files (x86)\Arduino\libraries\NewSoftSerial\NewSoftSerial.cpp:41:27: fatal error: avr/interrupt.h: No such file or directory

     #include <avr/interrupt.h>
                               ^
    compilation terminated.

    exit status 1
    Error compiling for board WeMos D1 R2 & mini.

  [1]: http://www.shenzhen2u.com/FPC1020-Fingerprint-touch-sensor-kit
  [2]: https://www.ebay.co.uk/i/391803724654?chn=ps&dispItem=1&adgroupid=41767405657&rlsatarget=pla-327666159789&abcId=1129006&adtype=pla&merchantid=7275934&poi=&googleloc=2826&device=c&campaignid=861364981&crdt=0

body:
I have never tried this, but a D1 Mini has 2.5 serial ports.

 - The Tx and Rx pins are Serial0.
 - Digital pin 4 is TX1 - There appears to be no RX pin.
 - D7 and D8 are Rx2 and Tx2.

So rather than using SoftwareSerial or NewSoftwareSerial try using Serial2.  It might work.