message:
NodeMCU ESP-12e - Timing errors

I'm using the **ESP-12e** with **Arduino IDE**. With that I'm trying to build a clock with a **WS2812B LED strip** matrix that I've build.
When I try to display the **seconds** on my matrix there are strange timing problems. It shows me the numbers how I should, the LEDs work OK but ..it misses seconds spontaneously. sometime it jumps the numbers like 00 01 03 06, sometimes 00 02 03 05.. sometimes it hangs at one number for a short time.

 1. Is the problem in my code?
 2. Or is it due to hardware limitations of the ESP-12e?
 3. How can I do it better?

Here is my sketch (I removed some number definitions [...] for better overview):

    #include <ESP8266WiFi.h> //WiFi
    #include <Adafruit_NeoPixel.h> //LEDs
    #include <TimeLib.h> //Time
    #include <WiFiUdp.h> //Synchronize Time

    const char* ssid = "XXXXX";
    const char* password = "XXXXXXX";

    WiFiClient wifiClient;

    //NTP Servers
      static const char ntpServerName[] = "us.pool.ntp.org";
      const int timeZone = 1; // Central European Time
      WiFiUDP Udp;
      unsigned int localPort = 8888;  // local port to listen for UDP packets
      time_t getNtpTime();
      void digitalClockDisplay();
      void printDigits(int digits);
      void sendNTPpacket(IPAddress &address);

      // Setup Wifi
    void setup_wifi() {

      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      randomSeed(micros());

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    /*-------- NTP code ----------*/
    // ====================================

    const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
    byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

    time_t getNtpTime()
    {
      IPAddress ntpServerIP; // NTP server's ip address

      while (Udp.parsePacket() > 0) ; // discard any previously received packets
      Serial.println("Transmit NTP Request");
      // get a random server from the pool
      WiFi.hostByName(ntpServerName, ntpServerIP);
      Serial.print(ntpServerName);
      Serial.print(": ");
      Serial.println(ntpServerIP);
      sendNTPpacket(ntpServerIP);
      uint32_t beginWait = millis();
      while (millis() - beginWait < 1500) {
        int size = Udp.parsePacket();
        if (size >= NTP_PACKET_SIZE) {
          Serial.println("Receive NTP Response");
          Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
          unsigned long secsSince1900;
          // convert four bytes starting at location 40 to a long integer
          secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
          secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
          secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
          secsSince1900 |= (unsigned long)packetBuffer[43];
          return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
        }
      }
      Serial.println("No NTP Response :-(");
      return 0; // return 0 if unable to get the time
    }

    // send an NTP request to the time server at the given address
    void sendNTPpacket(IPAddress &address)
    {
      // set all bytes in the buffer to 0
      memset(packetBuffer, 0, NTP_PACKET_SIZE);
      // Initialize values needed to form NTP request
      // (see URL above for details on the packets)
      packetBuffer[0] = 0b11100011;   // LI, Version, Mode
      packetBuffer[1] = 0;     // Stratum, or type of clock
      packetBuffer[2] = 6;     // Polling Interval
      packetBuffer[3] = 0xEC;  // Peer Clock Precision
      // 8 bytes of zero for Root Delay & Root Dispersion
      packetBuffer[12] = 49;
      packetBuffer[13] = 0x4E;
      packetBuffer[14] = 49;
      packetBuffer[15] = 52;
      // all NTP fields have been given values, now
      // you can send a packet requesting a timestamp:
      Udp.beginPacket(address, 123); //NTP requests are to port 123
      Udp.write(packetBuffer, NTP_PACKET_SIZE);
      Udp.endPacket();
    }

    // NEO PIXELS
    // ====================================

    // Setup
    #define PIN 0
    #define NUMPIXELS 224

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    int individualPixels[NUMPIXELS];

    // Time variables
    int hs;
    int m;
    int s;

    // For Loops
    int x;

    // RGB color variables
    int red;
    int green;
    int blue;

    void colorBlue(){
      red = 0;
      green = 0;
      blue = 100;
    }

    /* IN LOOP Light pixels corresponding to current time */
    void neoPixler(){
      for (x=0; x<sizeof(individualPixels); x++){
        if (individualPixels[x]==1){
          pixels.setPixelColor(x, pixels.Color(red,green,blue)); //Set Neopixel color
        }
        else{
          pixels.setPixelColor(x,pixels.Color(0,0,0));
        }
      }
      pixels.show(); //Display Neopixel color
    }

    // ALL OFF
    void turnOff(){
      for(x=0; x<pixels.numPixels(); x++) {
        individualPixels[x]=0;
        pixels.show();
      }
    }

    //Numbers
    void dl_one(){
      individualPixels[160]=1;
      individualPixels[161]=1;
      individualPixels[146]=1;
      individualPixels[147]=1;
      individualPixels[116]=1;
      individualPixels[117]=1;
      individualPixels[102]=1;
      individualPixels[103]=1;
      individualPixels[72]=1;
      individualPixels[73]=1;
      individualPixels[58]=1;
      individualPixels[59]=1;
      individualPixels[28]=1;
      individualPixels[29]=1;
      individualPixels[148]=1;
      individualPixels[149]=1;
      individualPixels[112]=1;
      individualPixels[113]=1;
    }
    void dr_one(){
      individualPixels[172]=1;
      individualPixels[173]=1;
      individualPixels[134]=1;
      individualPixels[135]=1;
      individualPixels[128]=1;
      individualPixels[129]=1;
      individualPixels[90]=1;
      individualPixels[91]=1;
      individualPixels[84]=1;
      individualPixels[85]=1;
      individualPixels[46]=1;
      individualPixels[47]=1;
      individualPixels[40]=1;
      individualPixels[41]=1;
      individualPixels[136]=1;
      individualPixels[137]=1;
      individualPixels[124]=1;
      individualPixels[125]=1;
    }
    void dl_two(){
      individualPixels[152]=1;
      individualPixels[153]=1;
      individualPixels[156]=1;
      individualPixels[157]=1;
      individualPixels[158]=1;
      individualPixels[159]=1;
      individualPixels[160]=1;
      individualPixels[161]=1;
      individualPixels[144]=1;
      individualPixels[145]=1;
      individualPixels[118]=1;
      individualPixels[119]=1;
      individualPixels[104]=1;
      individualPixels[105]=1;
      individualPixels[102]=1;
      individualPixels[103]=1;
      individualPixels[68]=1;
      individualPixels[69]=1;
      individualPixels[64]=1;
      individualPixels[65]=1;
      individualPixels[22]=1;
      individualPixels[23]=1;
      individualPixels[24]=1;
      individualPixels[25]=1;
      individualPixels[26]=1;
      individualPixels[27]=1;
      individualPixels[28]=1;
      individualPixels[29]=1;
      individualPixels[30]=1;
      individualPixels[31]=1;
    }
    void dr_two(){
      individualPixels[34]=1;
      individualPixels[35]=1;
      individualPixels[36]=1;
      individualPixels[37]=1;
      individualPixels[38]=1;
      individualPixels[39]=1;
      individualPixels[40]=1;
      individualPixels[41]=1;
      individualPixels[42]=1;
      individualPixels[43]=1;
      individualPixels[52]=1;
      individualPixels[53]=1;
      individualPixels[80]=1;
      individualPixels[81]=1;
      individualPixels[92]=1;
      individualPixels[93]=1;
      individualPixels[90]=1;
      individualPixels[91]=1;
      individualPixels[132]=1;
      individualPixels[133]=1;
      individualPixels[130]=1;
      individualPixels[131]=1;
      individualPixels[168]=1;
      individualPixels[169]=1;
      individualPixels[170]=1;
      individualPixels[171]=1;
      individualPixels[172]=1;
      individualPixels[173]=1;
      individualPixels[140]=1;
      individualPixels[141]=1;
    }

    [......]

    // Seconds
    // ====================================
    void print_numbers(byte num){
      byte num10;
      byte num1;
      num1=num;
      num10=(num-num1)/10;
      switch (num10){     //10...
      case 0:
        dl_null();
        break;
      case 1:
        dl_one();
        break;
      case 2:
        dl_two();
        break;
      case 3:
        dl_three();
        break;
      case 4:
        dl_four();
        break;
      case 5:
        dl_five();
        break;
      }
      switch (num1){      //1...
      case 0:
        dr_null();
        break;
      case 1:
        dr_one();
        break;
      case 2:
        dr_two();
        break;
      case 3:
        dr_three();
        break;
      case 4:
        dr_four();
        break;
      case 5:
        dr_five();
        break;
      case 6:
        dr_six();
        break;
      case 7:
        dr_seven();
        break;
      case 8:
        dr_eight();
        break;
      case 9:
        dr_nine();
        break;
      }

    }
    void seconds(){
    /* Get current time */
    s=second();
    turnOff();
    print_numbers(s);
    neoPixler();      // Lights
    }

    void setup() {

      // Debug info
      Serial.begin(115200);
      Serial.println(F("Booting"));

      setup_wifi();

      // Setup UDP Time + Sync Time
      Serial.println("Starting UDP");
      Udp.begin(localPort);
      Serial.print("Local port: ");
      Serial.println(Udp.localPort());
      Serial.println("waiting for sync");
      setSyncProvider(getNtpTime);
      setSyncInterval(3000);

    /* NEO PIXELS ------------------------------------------------------------------------------------------------------*/
      colorBlue(); //Standard Color
      pixels.begin(); //Begin Neopixel string
      pixels.show(); // Initialize all pixels to 'off'
    }

    void loop() {
      seconds();
    }

body:
It's likely the problems are in your code somewhere; but not enough information is available to say for sure.

---

Your first step toward debugging the problem probably should be taking any ESP-12e issues out of the mix.  At the beginning of `getNtpTime()` temporarily add something like `return 1477897101UL + millis()/1000;` to get a sync-time that advances at the correct rate and is repeatable for testing.  If the display suddenly begins updating smoothly, look for problems in your time code, else in the display code.

---

The technique of duplicating a whole bunch of `individualPixels[116]=1;` lines (with different pixel numbers) is crude, tedious, verbose, error-prone, inflexible, etc.  You might instead create some arrays and use a loop to set pixel data.  For example:

    const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,
      149, 112, 113, 0};
    ...
    const byte R2[] = {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 52, 53, 80, 81, 92, 93, 90,
      91, 132, 133, 130, 131, 168, 169, 170, 171, 172, 173, 140, 141, 0};

    void loadDigit(byte *pixelList) {
      for (byte j=0; pixelList[j]; ++j)
        individualPixels[pixelList[j]] = 1;
    }
    ...
       loadDigit(L1);  // Write a left 1
    ...
       loadDigit(R2);  // Write a right 2

---

You could also create an array of addresses of number-data arrays, to get rid of the crude, tedious (etc.) switch/case statements in `print_numbers()`.  For example:

    const byte *digitsL[] = {L0, L1, L2, L3, L4, L5, L6, L7, L8, L9};
    const byte *digitsR[] = {R0, R1, R2, R3, R4, R5, R6, R7, R8, R9};
    ...
    if (num>9)
      loadDigit(digitsL[num/10]);  // Write tens digit
    loadDigit(digitsR[num]);    // Write units digit

---

If your matrix is logically organized, all of the 1's in R0 are at constant offsets from the 1's in L0 (for example, 12 more), and similarly for other digits.  If that's the case, you could modify `loadDigit()` to take a second parameter, `offset`, which indicates where to place the digit in the matrix, ie, tells `loadDigit()` how much to add via a statement like `individualPixels[offset+pixelList[j]] = 1;`.  Then you could leave out the `R0 ... R9` arrays (and `digitsR[]` as well) and use code like the following:

    ...
    if (num>9)
      loadDigit(digitsL[num/10], 0);  // Write tens digit at left
    loadDigit(digitsL[num], 12);   // Write units digit at right

---

A drawback to using `const byte` arrays like `L0 ... L9` and `R0 ... R9` is that when your program starts they get copied from PROGMEM into RAM for access.  It would make sense to declare them in PROGMEM, and use them directly from PROGMEM by appropriate changes.  [*Edit:* See example program, below]

---

Note, a string of 224 WS2812B units takes about 6.7 ms to update:  224 units x 24 bits x 1.25 μs/bit.  Each time you update your matrix of lights, the `millis()` counter, `timer0_millis`, will lose 5 or 6 ms because `pixels.show()` runs with interrupts turned off.  To compensate, you could add 5 to `timer0_millis` after each update.  To make the loss always be 5 ms instead of sometimes 5 and sometimes 6, add the following code just before `pixels.show()`:  `unsigned long now=millis(); while (now==millis());`, which will stall until the end of the current millisecond.  To see how to change `timer0_millis`, see the  “**Better Alternative**” section of [my answer to “How to keep accurate millis() while using ADC_sleep mode?”](https://arduino.stackexchange.com/a/30080/391).

---

I'd remove the `pixels.show()` call from `turnOff()` because you will (I think) always be calling `pixels.show()` shortly after that, after loading number images, to turn on a bunch of other pixels.  That is, clear the array, fill the necessary 1's, then show, without a show between clearing and filling.

---

Following is an example program that illustrates storing a constant array of bytes in PROGMEM, and accessing its entries via `pgm_read_byte()` calls.

    // Sketch that accepts a number k via serial input, and responds with
    // the k-th set of numbers from among some sets of numbers stored in
    // PROGMEM.  This avoids copying the array data into RAM.  jiw 31 Oct 2016

    #include <Streaming.h>  // Ref: http://arduiniana.org/libraries/streaming/

    // Set up datatext in PROGMEM
    const byte L1[] PROGMEM = { 102, 103, 112, 113, 116, 117, 146, 147, 148,
           149, 160, 161, 28, 29, 58, 59, 72, 73, 0};

    const byte R1[] PROGMEM = { 124, 125, 128, 129, 134, 135, 136, 137, 172,
           173, 40, 41, 46, 47, 84, 85, 90, 91, 0};

    const byte L2[] PROGMEM = { 152, 153, 156, 157, 158, 159, 160, 161, 144,
           145, 118, 119, 104, 105, 102, 103, 68, 69, 64,
           65, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0};

    const byte R2[] PROGMEM = { 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 52,
           53, 80, 81, 92, 93, 90, 91, 132, 133, 130,
           131, 168, 169, 170, 171, 172, 173, 140, 141, 0};
    const  void* Addrs[] = { L1, R1, L2, R2 };
    enum { nAddrs = sizeof Addrs / sizeof Addrs[0] };

    void prompt() {
      Serial << endl << "Please enter item number from 1 to " << _DEC(nAddrs) << ": ";
    }

    void setup() {
      Serial.begin(115200);         // init serial port
      prompt();   // Issue initial prompt
    }

    void loop() {
      char c, d;
      while (Serial.available()) { // Get characters
        c = Serial.read();
        if (c >= '0' && c <= '9') {
          Serial << c << endl; // Echo the entered digit
          d = c - '0' - 1;
          if (d>=0 && d < nAddrs) {
            byte k=0, t = pgm_read_byte(Addrs[d]);
            Serial << "Set #" << _DEC(d+1) << ": ";
            while (t) {
           Serial << _HEX(t) << ' ';
           t = pgm_read_byte(++k + Addrs[d]);
            }
            Serial << endl;
          }
          prompt();   // Issue prompt after any digit
        }
      }
    }


sender: user

sender: assistant

body: NTP is a protocol implemented over UDP which is a connectionless protocol.  If packets are lost then neither the client nor the server will be aware of their loss.  So on top of everything else that might be wrong your data source may also be injecting additional errors.  You should take the time from a timer on the board and update it from NTP when you receive data.


body:
When I'm trying it like this I get the error:

    invalid conversion from 'const byte* {aka const unsigned char*}' to 'byte* {aka unsigned char*}' [-fpermissive]

------

        #include <ESP8266WiFi.h> //WiFi
        #include <Adafruit_NeoPixel.h> //LEDs

        // 1
        const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,  149, 112, 113, 0};
        const byte R1[] = {172, 173, 134, 135, 128, 129, 90, 91, 84, 85, 46, 47, 40, 41, 136, 137, 124, 125, 0};
    ...
        const byte *digitsL[] = {L0, L1, L2, L3, L4, L5, L6, L7, L8, L9};
        const byte *digitsR[] = {R0, R1, R2, R3, R4, R5, R6, R7, R8, R9};

        void loadDigit(byte *pixelList) {
          for (byte j=0; pixelList[j]; ++j)
            individualPixels[pixelList[j]] = 1;
        }

        void print_numbers(byte num){
          if (num>9){
            loadDigit(digitsL[num/10]); // Write tens digit
          }
          else {
          loadDigit(digitsR[num]);  // Write units digit
          }
        }

        void seconds(){
        turnOff();
        print_numbers(byte second());
        //print_numbers(second());
        neoPixler();
        }

**EDIT:**
It works when I add "const" to the loadDigit

        //0
        const byte L0[] = {156, 157, 158, 159, 160, 161, 152, 153, 110, 111, 108, 109, 66, 67, 64, 65, 144, 145, 118, 119, 100, 101, 74, 75, 56, 57, 24, 25, 26, 27, 28, 29, 0};
        const byte R0[] = {168, 169, 170, 171, 172, 173, 140, 141, 122, 123, 96, 97, 78, 79, 52, 53, 132, 133, 130, 131, 88, 89, 86, 87, 44, 45, 36, 37, 38, 39, 40, 41, 0};
        //1
        const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,  149, 112, 113, 0};
        const byte R1[] = {172, 173, 134, 135, 128, 129, 90, 91, 84, 85, 46, 47, 40, 41, 136, 137, 124, 125, 0};

      void loadDigit(const byte *pixelList) {
          for (byte j=0; pixelList[j]; ++j)
            individualPixels[pixelList[j]] = 1;
        }
        void print_numbers(byte num){
          if (num>9){
            loadDigit(digitsL[num/10]);
            loadDigit(digitsR[num]);
            }
          else {
            loadDigit(digitsR[num]);
          }
        }
        void seconds(){
          s=second();
          turnOff();
          print_numbers(s);
          neoPixler();
        }


message:
Sim800L's library can not compile on Arduino Due

. Is there any way to create a library for Arduino Due?

    #include <Sim800l.h>
    #include <SoftwareSerial.h>

    Sim800l Sim800l;
    char* text;
    char* number;
    bool error;

    void setup(){
        Sim800l.begin();
        text = "Testing Sms";
        number = "2926451386";
        error = Sim800l.sendSms(number,text);
        // OR
        //Sim800l.sendSms("+540111111111","the text go here")
    }

    void loop(){
        //do nothing
    }

I guess that the problem is the software serial library, too. However, I don't know how to replace this library for Arduino Due.

Any help appreciated.

body:
First we must delete the SoftwareSerial and SIM800L libraries, then define Sim800l and assign it to Serial 3 on pins 14 and 15. In `setup`, call `Sim800l.begin()` and the rest of the code is unchanged.

    #define SIM800l Serial3

    void setup () {
      Serial.begin (9600);
      SIM800l.begin (9600);
      while(!Serial);
      SIM800l.write ("AT+CMGF=1\r\n");
      delay (1000);
      SIM800l.write("AT+CMGS=\"5432154552"\"\r\n");
      delay(1000);
      Serial.println("send SMS");
      SIM800l.write ("test send SMS");
      delay (1000);
      SIM800l.write ((char)26);
      delay(1000);
    }

    void loop (){}


message:
use button to select variable

i have a need to use 3 buttons a a simple option/variable selector at sketch start up ...

Pretty much at startup , script must wait for button press ( one of 3 ) , when button is pressed , use that buttons predefined string value as a variable for the loop script further down .. if wanting to change the "variable" then a reboot is required ..

i know how to digital read in the buttons , but not sure how to

1) wait for one of the buttons to be pressed to then jump to main loop
2) Associate a "string" variable to each button

thinking about it i suppose a If/Else loop will be required for the Input 'wait" and then just if the digital input (button) is pushed then continue .. am i correct ?

Ideas or better way to do it ?

Thx
Greg

body:
1) One solution is to create a function that loops repeatedly, eg `while(1)`, until one of the buttons is pressed. It then returns the button "number", eg 0,1 or 2.

2) In C you would usually remember the index into a string table. So one solution is to store the button number in a global variable and use it to index a "string array", something like `char * buttonStrings["B1","B2","B3"];` and to get the string for a button use `buttonStrings[buttonNumber];`


body:
When I am searching for something inside a loop, I find that the
simplest thing to do is to just `break` out of the loop once I found it.
This was frowned upon in the days when structured programming was a hot
thing, but as long as it makes things simpler, you should not be ashamed
to `break`:

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

    const int button_pins[] = {2, 3, 4};
    const char * const urls[] = {"foo.com", "bar.org", "baz.net"};
    const char * url;  // the selected URL

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

        // Configure input pins.
        for (int i = 0; i < 3; i++)
            pinMode(button_pins[i], INPUT_PULLUP);

        // Find first button pressed.
        int i;  // button index
        for (i = 0; ; i = i==2 ? 0 : i+1) {
            if (digitalRead(button_pins[i]) == LOW)
                break;
        }

        // The button index selects the URL.
        url = urls[i];

        Serial.print("Selected URL: ");
        Serial.println(url);
    }

    void loop() {}

The `for` loop above is written as an endless loop (no end condition).
The expression `i = i==2 ? 0 : i+1` means: “if `i` is `2`, make it `0`,
otherwise make it `i+1`”. In other words, we are endlessly looping `i`
over 0, 1 and 2.

Now, it may well happen that you actually do not care about which button
was pressed once you have selected the proper URL. In this case, you can
use the URL pointer as a “flag” that tells you when you can end the
loop:

    // First button pressed selects the URL.
    for (int i = 0; !url; i = i==2 ? 0 : i+1) {
        if (digitalRead(button_pins[i]) == LOW)
            url = urls[i];
    }

Where `!url` means “the URL has not been found”. This works because the
C runtime initializes `url` to zero, which is interpreted as `false` in
boolean context.

**Addendum**: If you are likely to add new button/URL pairs, you can
make this easier by structuring the list as an array of structs:

    const struct {
        int pin;          // pin number
        const char *url;  // associated URL
    } buttons[] = {
        {2, "foo.com"},
        {3, "bar.org"},
        {4, "baz.net"}
        // etc. just add to this list as needed.
    };
    const size_t button_count = sizeof buttons / sizeof buttons[0];

Then the search becomes:

    for (int i = 0; !url; i = i==button_count-1 ? 0 : i+1) {
        if (digitalRead(buttons[i].pin) == LOW)
            url = buttons[i].url;
    }


message:
Which interrupts are enabled when programming an ATTiny85 with Arduino IDE?

I have programmed a tiny85 using the Arduino IDE. I am using the pulseIn() function. Wrapping it in noInterrupts()/interrupts(); appears to make the function more consistent. This would imply that interrupts are running.

Which interrupts are running? Can I disable them?

I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.

(I know I can improve the code by not using pulseIn and using interrupts, however the question I have at the moment is which interrupts are running when I am not explicitly enabling any.)

body:
The only interrupt that is *always* running is the one which generates the count for `millis()` and `micros()`. Disabling interrupts disables your ability to keep track of time and use `delay()`.

Timer interrupts are also used by the `tone()` function and for sending / receiving serial data if the chip has a UART.

Disabling interrupts would also affect the use of external interrupts and pin change interrupts should you be using them.

It sounds, from your brief description, that you would only be effecting the use of `millis()` and `delay()` since you aren't using the other systems that use interrupts at all.


body:
> Which interrupts are running?

It depends on your code which you haven't shown. The Timer 0 overflow interrupt is usually active, as that lets the library count when a millisecond is up (roughly).

If you have done a `Serial.begin` then serial interrupts would be active. If you have used the I2C library (Wire) then I2C interrupts would be active.

*(Disclaimer: That really refers to the Atmega328P. I'm not quite so sure on the ATtiny, it would depend on what the libraries do).*

---

> Can I disable them?

If you want to. Doing `noInterrupts()` is the simplest way. Note that if you disable interrupts for more than a millisecond (approximately) then the time returned by `millis` and `micros` will be wrong. Plus `delay` won't work. Plus you won't be able to serial print properly or at all.

---

> I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.

That is exactly what it does. Once activated the hardware timers can generate a PWM signal purely in hardware.

---

There are other ways of timing intervals (than `pulseIn`). One method is to use one of the other timers, configured with a small, or no prescaler. Then you can measure up to very high accuracy. I have examples of that on [my page about timers](http://www.gammon.com.au/timers).

*(The ATtiny85 only has two timers, so you couldn't use the second timer for measuring **and** do PWM output with it, however you can use Timer 0 for the PWM output). That limits the PWM frequency to its default, however you could still alter the duty cycle)*


message:
How to ground a arduino with an external power-source?

I have magnet hooked up to my arduino with a Darlington Transistor, like this:

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

The powersource is a 12V adapter[![enter image description here][2]][2]

I'm pretty new to electronics but i'm told that the transistor won't work unless the ground on the arduino is the same as the ground on the external source. How do I do this in practice? Should I run a wire from the ardunio-ground to the negative pole on the powersource? How do I tell which one is the negative one?

  [1]: https://i.stack.imgur.com/O7XEm.png
  [2]: https://i.stack.imgur.com/tcHLQ.jpg

body:
Ground is usually (though not always, but in your case it is) the point of lowest potential in a circuit. In your circuit that is the "negative" connection of the power supply. Note that the "negative" isn't actually "negative", it is zero volts when measured from the reference point of itself.

So yes, you need to know which is the "negative" connection and connect that to ground on the Arduino.

Since you already have it wired up the negative is the one which connects to the emitter of your transistor. If you don't know which that is and you just randomly connected a random wire to a random pin then you need to investigate your power supply.

The simplest way is with a Digital MultiMeter (one of the most basic items you need to own if you are working with electronics - if you don't have one then go and buy one immediately). Set it to DC Volts in the right range then connect the two probes (correctly inserted into the right sockets on the DMM) to the power supply's output connections. If the voltage reads positive then the black probe is connected to negative. If it reads a negative value then the red probe is connected to negative.

If you cannot get a DMM but you have an LED (note: a bulb will not work) and a suitable resistor (say 2.2K) you can connect the resistor in series with the LED then connect the two to the power supply. The cathode of the LED (the pin with the flat side on the case) connects to negative. Connect the power both ways round. The way round that it lights the LED is the correct way round, and you know that the connection that goes to the cathode (flat side of the lip round the bottom of the LED) is the negative.


body:
Majenko explained how to figure out what is what. I'm just repeating the shematics again with "additional" description:

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

Current limiting resistor R1 is REQUIRED, if you don't want to destroy Arduino output by over current.

About using the LED to test your power source polarity:

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

And again, current limiting resistor is required, or you'll burn it. As Majenko stated, it should be about 2k2.

  [1]: https://i.stack.imgur.com/DV5d0.png
  [2]: https://i.stack.imgur.com/IXiPQ.png


body: I would be careful about "ground loops" when using two supplies connected to the mains electricity. You may get strange results. If you are using a lap top then maybe disconnect it from the charger while the PSU is plugged in the wall. Or use a battery for your coil. Or power the Arduino from a power bank. Or get a 12v USB adaptor and power the arduino from the 12v supply. Add and LED for debugging while connected to the computer. Then disconnect from the computer and plug in the 12v supply.


message:
How to program an nRFL01 RF module that is connected to a pc via a USB to UART/TTL adapter?

In a few of my previous questions I was told that the nRF24L01 RF Module can be connected to a pc using a USB to UART/TTL adapter. After a bit of research I understand that one way to use it is to connect it to an arduino- and then to use certain dedicated libraries like RF24.h, and nRF24L01.h to send and receive data. Though I've not been able to find any tutorial outlining the procedure for programming the nRF24L01 once its been connected to the pc.
  How do I send and receive data using my pc-interface? What software do I write and how do I write it?

body:
In short: whatever software you use on the remote end (rf24.h for example) you have to re-write on the PC using whatever language you can interface to the FT2232 with. That means having intimate knowledge of:

1. The USB to SPI adapter you choose (NOT USB TO UART!)
2. The low-level control and interfacing of the nRF24L01+ chip
3. The exact protocol used by your chosen Arduino library.

That's a lot of understanding which (by the level of your questions) is most likely way outside your area of ability.

If you equate time to money then the cost of doing what you want to do is far higher than just using a small Arduino to act as an intelligent interface between your PC and your chosen wireless system. You can discount points 2 and 3 above since they have already been done for you by the Arduino libraries and tutorials. Point 1 becomes considerably easier since you are then just talking to an Arduino using a protocol which you yourself have come up with.

So do yourself (and us) a favour and come to your senses and just plug the nRF24L01+ into an Arduino then plug the Arduino into your PC and program the Arduino to do the RF communications according to commands and instructions you send to your sketch from the PC.


message:
Arduino trim: does it remove the \n as well?

According to the manual:

https://www.arduino.cc/en/Reference/StringTrim

Trim strips one or more whitespaces from the beginning and the end. Does it also removes tabulators and \n ?

I have the following code which works:

     while (Serial.available()) {   // something came across the serial
          char c = (char)Serial.read();
          Command += c;
          Command.trim();
          if (c=='\n')
             {
               Complete =true;
             }
       if (Command.length() >0 && Complete) {

            if (Command == "LED_ON") {
                   // Do stuff
            }

Although I'm not sure that it is working because of the last if statement which says: if (Command == "LED_ON") ignores the ending \n and say ok it matched OR Command.trim() really takes off that \n.

Thank you

body:
Yes, \n is also removed.

The source for the trim() function is in [WString.cpp][1].

    void String::trim(void)
    {
     if (!buffer || len == 0) return;
     char *begin = buffer;
     while (isspace(*begin)) begin++;
     char *end = buffer + len - 1;
     while (isspace(*end) && end >= begin) end--;
     len = end + 1 - begin;
     if (begin > buffer) memcpy(buffer, begin, len);
     buffer[len] = 0;
    }

We can see it uses the `isspace()` function, but where's that function defined? `WString.cpp` only `#include`s `WString.h`, so we go there.

In `WString.h`, we can see [it includes `ctype.h`][2]. Time to go to the [C++ Reference][3], which tells us that yes, `\n` is a "space" according to isspace(), so it is trimmed.

(note that `isspace()` is affected by localization settings. I'm not sure what the localization settings are when compiling for Arduino)

  [1]: https://github.com/arduino/Arduino/blob/be9bbc3255e784108fc10a069d79a4fa8b4ca37e/hardware/arduino/avr/cores/arduino/WString.cpp#L719-L729
  [2]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.h#L28
  [3]:
http://www.cplusplus.com/reference/cctype/isspace/


body:
Whilst rchard2scout is quite right that `trim` will remove newlines, why not rearrange the code so it doesn't matter?

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

      char c = (char)Serial.read();
      if (c == '\n')
         Complete = true;
      else
         Command += c;


message:
NRF24L01+ unable to receive data

I have 2 Arduino UNO R3 nodes communicating using NRF24L01+ transceivers with the TMRh20 library.

**Setup** I have original as well as cheaper but 'compatible' [arduinos][1]. One of the nodes uses an original arduino Uno whereas the other uses the cheaper one.

**Observation**

1. The node with the cheaper Uno can transmit data (sucessfully received by the other node) but is unable to receive data.
I have a number of Rf modules and UNo boards. The observation is similar across.

2. Using the same configuration (rf module, connection and code) , the original uno board receives data but noot the other types.

3. Another thing that i observed is that the cheaper uno comes with a 12MHz oscillator on the board whereas the original one has a 16 Mhz one.Can it be the source of problem?

This [article][2] mentions something that I could not get but am suspicious of it being a possible direction to the solution to the problem, only if someone could help.

> On Arduino UNO boards SPI pins are connected with some digital pins. While using modem you most remember that these digital pins won't be available.

  [1]: http://www.ebay.in/itm/Arduino-UNO-R3-Compatible-ATmega328P-Development-Board-and-CH340-Original-IC-/291764662609?hash=item43ee877151:g:feYAAOSwSgJXOGX4
 [2]: http://starter-kit.nettigo.eu/2014/connecting-and-programming-nrf24l01-with-arduino-and-other-boards/

body:
As it turns out, the culprit was the power supply on the board.

The clone came with AMS1117 based regulator for the 3.3V which it did indeed generate (3.27 measured). Using it, the reception of the RF device failed (although it could transmit data). Also had 10uF and a 0.1uF capacitor hooked up in parallel to Vdd and Gnd of the NRF24L01+, as recommended. I therefore suspected something to do with the SPI configuration.

Finally, having powered the 3.3V to the Rf device from another genuine Arduino solved the problem. Not sure if it was the 3.3V rail from the clone possibly having excessive noise which may be causing the issue, as I did not see a reasonable drop in 3.3V output of the clone while in operation.


message:
Can Atmel Studio 6 Simulator simulate SPI?

I am trying to do PAL composite video output with Arduino Nano. I am using Atmel Studio 6, not the Arduino IDE. I am sending out the picture data via SPI. On the TV I could not see the text I tried to produce, so I tried to run my program in the Atmel Studio simulator (to use it as a logic analyzer). But in the resulting stimuli file I also do not see the MOSI pin changing.

I am using the A0 pin (PORTC bit 0) to send out the sync signal, that appears correctly in the output .stim file: PORTC changes exactly at the right time. But PORTB does not change at all.

My program can definitely be buggy, but that is another topic... the question is, **can Atmel Studio Simulator simulate the SPI** at all?

body:
No Atmel Studio cannot simulate SPI.

The fact that you are using SPI makes me think that you are using the MAX7456 IC or even the [SparkFun On Screen Display Breakout][1] which uses this same IC.

You can generate composite video just by using a few resistors and an Arduino.

I have found a number of sites on Google who have used the Arduino to output PAL composite video to display the Pong game on an old TV.

 - [http://searle.hostei.com/grant/AVRPong/index.html][2]
 - [http://www.makeuseof.com/tag/how-to-recreate-the-classic-pong-game-using-arduino/][3]
 - [http://www.instructables.com/id/2-player-Pong-using-Arduino/][4]
 - [http://forum.arduino.cc/index.php?topic=8708.0][5]
 - [http://apcmag.com/arduino-project-7-build-a-retro-gamebox.htm/][6]
 - [http://electronics.divinechildhighschool.org/Home/electronics-spring-2012-1/arduino-pong][7]

  [1]: https://www.sparkfun.com/products/retired/9168
  [2]: http://searle.hostei.com/grant/AVRPong/index.html
  [3]: http://www.makeuseof.com/tag/how-to-recreate-the-classic-pong-game-using-arduino/
  [4]: http://www.instructables.com/id/2-player-Pong-using-Arduino/
  [5]: http://forum.arduino.cc/index.php?topic=8708.0
  [6]: http://apcmag.com/arduino-project-7-build-a-retro-gamebox.htm/
  [7]: http://electronics.divinechildhighschool.org/Home/electronics-spring-2012-1/arduino-pong


message:
multiple multiplexer (4051) - how to process the inputs?

I have my Arduiono which has only a limited amount of Inputs/Outputs. But in my project I will have to attach a ton of potentiometers/buttons/LEDs, so I will have to use the IC4051-Multiplexer/Demultiplexer.

I have understood how to switch the Inputs/Outputs via the 3-Bits. But I don't get it, how to connect multiple ID4051s and process the signals(?)

Can someone explain that to me?

body:
I have no experience of this chip but I would guess that you would need to connect the child level multiplexer to the output of the parent and use the outputs to drive the address lines.

You could look at an MCP23008 or MCP23016, these are 8 and 16 bit GPIO expanders that you control via I2C.  You can have 8 of the MCP230008 (64 pins) before you need to look at I2C bus expanders (which you can get).  I think its the same for the 16 bit version, but you would need to double check.


body:
The 4051s are only useful, for your potentiometers. For leds, I'd use shift-registers. For buttons you could use input-shift-registers. Though there are better options. E.g. chips that can scan a matrix of buttons, or chips that send you an interrupt, if one of the buttons is pressed (so you don't have to constantly poll the button states.

As to the original question. You can connect the S1, S2, S3, and Z pins of multiple chips to the same pins on the Arduino. You need to use a different Arduino pin for each of the chips E pin.

You can then set the E pin of the chip you want to read to LOW. You then set the correct S1-3 pins to select which output/input of that chip you want to connect to. You then read the value from the Z pin.

I hope that makes sense. Otherwise, let me know.


message:
int VS uint8_t VS uint16_t

This question is quite clear. What are the differences between an `int`, an `uint8_t`, and an `uint16_t`. I know it has to do with bytes and memory but can someone clarify me a bit?

Things I want to know:

1- How much memory does each take.

2- When to use what.

3- In the end of the day, are they that different?

body:
You can decipher most of them yourself.

* A `u` prefix means `unsigned`.
* The number is the number of bits used. There's 8 bits to the byte.
* The `_t` means it's a `typedef`.

So a `uint8_t` is an unsigned 8 bit value, so it takes 1 byte. A `uint16_t` is an unsigned 16 bit value, so it takes 2 bytes (16/8 = 2)

The only fuzzy one is `int`. That is "a signed integer value at the native size for the compiler". On an 8-bit system like the ATMega chips that is 16 bits, so 2 bytes. On 32-bit systems, like the ARM based Due, it's 32 bits, so 4 bytes.  Of the three it is the only one that changes.

Personally I rarely use `int` and always use `uint8_t` etc., since the variable type is the same no matter what architecture you compile for.  When you use `int` you can run into problems if you had a program that worked fine on a 32-bit ARM but then doesn't work right on an 8-bit ATMega, since the `int` can only store a fraction of the range of numbers on the 8-bit system compared to the 32-bit system.


message:
Arduino Uno + aRest + ESP8266

So, I can use the aRest library to program to the ESP8266 standalone, but if I have the ESP8266 connected to the Arduino Uno, can I still use the aRest library? Or will this no longer work?  I am trying to send a request to the Arduino unit that will toggle a pin to turn on/off via the aRest library.  Thanks!

aRest can be found here: https://github.com/marcoschwartz/aREST

body:
Why don't you just try it? :)

In overview of GitHub repo, first sentence, it says: "A simple library that implements a REST API for **Arduino** & the ESP8266 WiFi chip." Next paragraph confirms it.


message:
How to keep track of if data is outdated

I have a large set of data and it is refreshed every 30 seconds or so. However, not all data is refreshed every time. It is possible that no new data for a particular calculation isn't received for even a few hours. For this reason I need to track what data is possibly outdated, but hasn't been updated (maybe due to technical malfunctions or a sensor is down). I was thinking about creating an additional (large) 2d array to do this, and increment some sort of counter. This way if a particular spot is at `1000` this means it is old. When new data is received it can be reset to `0`. However, this seems like a slow, ineffective way to do this. How could I keep track of data more efficiently?

body:
OK, so you have three possible states for your values:

1. No valid data (-1, or 0xFFFF in 16-bit 2's complement)
2. Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
3. Valid but "old" data.

If you first check for invalid data before thinking about "old" data (invalid data is never considered "old") then you just have two states:

1. Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
2. Valid but "old" data.

As you can see the highest 6 bits of the stored value aren't used at all except for storing -1 for invalid data (hence checking for that first). So you could utilize those 6 bits to store all sorts of things. In 6 bits you can store the values 0 to 63. That could be the number of seconds since the last time you got some data.

By masking and shifting you can separate out the two values:

    val = data[x] & 0x3FF;
    sec = data[x] >> 10;

Every second add one to the seconds count of each and every data entry that is less than (say) 60.

    val = data[x] & 0x3FF;
    sec = data[x] >> 10;
    if (sec < 60) sec++;
    data[x] = val | (sec << 10);

Now each entry in your array knows how old it is (up to 1 minute), and if it's older than a certain threshold (30 seconds? 45 seconds? you choose) then you consider it "old" and display it as such.

You can make it easier to program by using a union/struct combination:

    typedef union {
        int16_t rawval;
        struct {
            unsigned value:10;
            unsigned seconds:6;
        } __attribute__((packed));
    } data_t __attribute__((packed));

If your data array is now made up of that type instead of integers:

    data_t data[500];

you can now access:

* data[x].rawval as the raw 16 bit signed value (to look for -1).
* data[x].value as the unsigned 10 bit value from 0 to 1000.
* data[x].seconds as the unsigned 6 bit value from 0 to 63.

Updating the seconds then becomes as simple as:

    if (data[x].seconds < 60) data[x].seconds++;

When you store a new value using

    data[x].rawval = sensor.getValue();

the seconds is automatically overwritten with 0 which resets the count for you.

And both methods give you data ageing without using a single byte more memory.


body:
Rather than frequently updating a time flag for each data item, you can store a “generation number” for each item.  Maintain a “current generation number” `currentGen` and at intervals add one to it.  If the interval at which you increment `currentGen` is 20 seconds and you store 16-bit generation numbers, rollover will occur about every 15 days.  [20*2¹⁶/3600/24 = 15.17 days.]

For example, suppose your data structure has fields for item.value and item.gen.  Whenever you store a new value into item.value, copy `currentGen` into item.gen.  Later, to tell the age of an item, use `unsigned int` arithmetic to subtract item.gen from `currentGen`.  For example, if  `currentGen` is 23453, an element with item.gen = 17487 is about 33 hours old.

Note, if item age ever exceeds 15.17 days, it will wrap around to zero.  It that's a concern, either use a larger datatype for item.gen, or update `currentGen` less frequently, for example every two minutes for a 90-day wraparound or every 8 minutes for a 364-day wraparound time.


message:
How to automate an electric kettle?

I have [this tea kettle](http://chefman.com/products/coffee-tea/rj11-17-gp/), which requires pressing two buttons one after the other ("on" and "prog") to start.

I'd like to automate that action (tying it to Tasker on my phone), and am wondering what's my simplest/cheapest option. My communication options are either WiFi or Z-Wave/ZigBee.

I'm assuming Arduino Uno Wifi is an option, but that seems like a huge overkill given how simple what I want to do is. Are there any other simpler/cheaper tools that I could use to do this?

body:
Replace your button with a relay and use a microcontroller to switch it.

It will be cheaper to use an ESP6266, which could be programmed with the Arduino IDE and the same Arduino code works on it. It will be perfect as it has got just 2 GPIO ports and it will just be the size of your thumb.


body:
**This is simply a suggestion. It is not in your list of communication protocol that you listed but this could work great.**

A good and reliable way is to use an GSM shield with and Arduino. The GSM shield could receive a text such as "on" or "off" and could interpret those messages to control your kettle.

To emulate the switches, you can use 2 MOSFET. They act like an electronic in the sense that when you apply 5V (PNP transistor), it lets current pass and will cut the current flow when there is no voltage applied to it.

NOTE: GSM modules are quite cheap if you know where to get them. I recommended getting a chinese version because they usualy work fine for me and there price is way lower.


body:
You could use lots of options to control it from Mbed boards to the Uno with a wifi shield, to a raspberry pi to .... the list goes on.  But if it were me I would use the something like the ESP8266 which cost less than $10 usd and can be programmed with the arduino IDE (I'm assuming that is useful given the community this was posted in).  There are also lots of tutorials available online for this kind of thing.

To trigger the button you have two options: a non-destructive one and a destructive one.  For the non destructive one, use something like a solenoid in a custom mount or a servo and small lever arm to push the button.  The benefit to this is that if you change your mind you just have to move the device and you still have a perfect unharmed kettle.  Plus, you can still use it if your device breaks or malfunctions.

For the destructive option, open up the kettle to get at the buttons or button pads and solder a wire to each side.  If you're lucky you can do this so that it can still be put back together and the original button still work.  One option is to use a relay to connect them.  You can use a small solid state relay or a larger coil relay; both would be under a couple of dollars and not large enough to be too obtrusive.  Using a relay is nice since you don't have to worry about which voltages are being used on which side of the button and it isolates the microcontroller from the kettle better.  (Actually some relays are polarized so if it doesn't work, switch the wires and try again).  Another option is to use an  optoisolator like [this][1] one.  It is polarized so if it doesn't work switch the wires.  Another option is to use a mosfet.  I believe it will work if you get an N channel mosfet with a Vgs (gate to source voltage) less than 3.3V.  Hook up the Source pin to the more negative of the two button leads and the Drain to the other.  Hook up the gate to a pin on the micorcontroller.  Also, you should put a resister between the gate and the source pins.

  [1]: https://www.sparkfun.com/products/9118


message:
How do I hook up a 3V device to a 74AHCT125 (Quad Level-Shifter)?

I have [this level shifter][1] that I'm trying to feed a 5V power source and then hook up a 3V device.

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

I've got the 5V source hooked up fine (on the top pinouts), but having trouble figuring what the "power out" would be that's 3V.

Here's the [data sheet][3].

  [1]: https://www.adafruit.com/products/1787
  [2]: https://i.stack.imgur.com/EMi9y.jpg
  [3]: https://cdn-shop.adafruit.com/product-files/1787/1787AHC125.pdf

body:
It's not a level shifter. It's a buffer chip that *can be used to level shift in one direction only*.

It is good for shifting from a low voltage logic signal (3.3v, say) up to a 5V logic signal. It can't shift down from 5V to 3.3V.

Basically it works by having a fixed voltage that it considers to be a logic HIGH, and any voltage above that will be output as 5V. Any voltage below will be output as 0V.  This is the "TTL Logic Level" specification in the datasheet.

So if you have a sensor that emits a 3V logic signal the HIGH logic value will be above its fixed threshold and will trigger a 5V HIGH on the output.

In contrast "CMOS" logic uses a percentage of the supply voltage to set the thresholds (usually > 0.6 x Vcc), and a 3V signal is less than that (3.3V is about bang on it, so is "iffy"), so won't work (or not reliably).


body:
The datasheet would let you think it cannot shift in that direction, but it's the chip recommended by Adafruit to do so : https://www.adafruit.com/product/1787

The "trick" is to feed it 3V power. It seems it will then happily accept 5V input and produce 3v outputs.


message:
Inconsistent response AT command

I'm building a vehicle tracker with Arduino shield with Waveshare SIM 808. I am communicating with the Arduino via AT commands, and came across the following problem: The method "leserial ()" returns me the result of the command missing characters

Response
`+CGNSINF: 1,1,20161101222934.000,-23.285230,-51.20`

Expected response
`+CGNSINF: 1,1,20161101223215.000,-23.285222,-51.204778,623.000,0.02,142.3,1,,1.2,2.5,2.2,,8,7,,,38,,`

Code:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(2, 3); //RX, TX

    String inputString = "";
    char inChar;

    const int powerkey =  5;
    const int statuspin = 6;

    void setup() {
      Serial.begin(9600);
      mySerial.begin(9600);
      pinMode(powerkey, OUTPUT);
      pinMode(statuspin, INPUT);

      mySerial.println("AT");
      delay(2000);
      leserial();

      //TURN ON GPS
      mySerial.println("AT+ CGNSPWR =1");
      delay(2000);
      leserial();
    }

    void loop() {
      //GET LOCATION
      mySerial.println("AT+CGNSINF");
      delay(4000);
      leserial();
      delay(5000);
    }

    void leserial(){
      inputString = "";
      while (mySerial.available()>0){
        inChar = mySerial.read();
        inputString += inChar;
      }
      Serial.println(inputString);
    }

body:
Basically you're sending a command that gives a response, then waiting 2 seconds for that response to arrive (which is completely the wrong thing to do to start with).

You have to ask yourself: where does that response go when it does arrive, while it's waiting for you to finally get around to reading it?

The answer is: into a small internal buffer that is considerably smaller than the response.

Thus most of the response just gets thrown away because there isn't room for it.

Instead you should most definitely NOT delay for 2 seconds waiting for the response, and instead keep looking to see if there are any characters to read up until you reach the end of the line.

It's all explained here: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


body:
I managed to solve the problem, I edited the file "SoftwareSerial.h" and changed the size stated in constant `_SS_MAX_RX_BUFF.`

    #define _SS_MAX_RX_BUFF 64 // RX buffer size

    to:

    #define _SS_MAX_RX_BUFF 128 // RX buffer size

I reached the conclusion that when I realized that the number of bytes returned in the function "mySerial.avaliable ()" was no more than 63 bytes.
I appreciate the support of all.


message:
Print when echo is read by HR-S04 sensor

I'm trying to see when an echo is received by my HR-S04 sensor. I have a Serial.println within my while loop to read the signal and see once a change happens to break the loop.

The issue is my serial just prints out the pin my echo to linked to. How can I set it so that the serial output is LOW and then HIGH once an echo is received?

    int trig1 = 3; //Trig 1
    int echo1 = 4; //echo1
    int ECHO1;
    double pingTime1;

    void setup()
    {
      Serial.begin(9600);
       pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
       pinMode(echo1, INPUT);  //sets the digital pin 5 as input
    }

    void loop()
    {
      ECHO1 = digitalRead(echo1); //assume echo1 is LOW and HIGH once echo is received

      while (ECHO1 == 0) //continuous loop until echo is HIGH
      {
        digitalWrite(trig1,LOW);
        delay(100);
        digitalWrite(trig1,HIGH);
        Serial.println(echo1); //Troubleshooting to see when pulse is read by sensor
       ECHO1 = digitalRead(echo1);
      }
      pingTime1 = pulseIn(echo1, HIGH); //Measure ping travel time in microseconds
      pingTime1 = pingTime1*1000; //convert microseconds to seconds

    }

body:
A couple things:

1) I believe your code for the trigger pin is wrong. An example I found sets it up as LOW for 2 microseconds, then HIGH for 10 microseconds, then LOW. (Note that the units are MICROseconds so you must use delayMicroseconds()

2) digitalRead(echo1) does nothing. Use the pingTime1 instead. You will always be receiving an 'echo' so it's not a HIGH or LOW but rather a changing variable stored as pingTime1.

3) echo1 is the variable for the pin. That's why Serial.println(echo1) prints the pin number. You could try Serial.println(ECHO1) but I don't think it will work because of what I said above.

4) If you want a HIGH or LOW to print to screen you must set a cutoff value for pingTime1 then use an if statement to print the appropriate value.

I'm not sure what exactly you're trying to do, but given the points above I do not believe a while loop is necessary.

Try this code. You can keep the first Serial.println() to see the duration of the pulse and/or you can keep the if statement if you want a HIGH or LOW to print to screen.

    // Send a pulse out through trig pin
    digitalWrite(trig1,LOW);
    delayMicroseconds(2);
    digitalWrite(trig1,HIGH);
    delayMicroseconds(10);

    //Receive pulse through echo pin
    pingTime1=pulseIn(echo1, HIGH);
    pingTime1=pingTime1*1000;

    // Serial print
    Serial.println(pingTime1);

    //Serial print (for HIGH or LOW)
    if (pingTime1 > cutoff) {
     Serial.println('HIGH');
    }
    else {
     Serial.println('LOW');


body:
To start with, you code isn't suppose to work. Here is a working code to start with (code below). You have a lot of mistakes so I suggest comparing your code to this one. Also, don't try to debug by adding a `Serial.print(/*something*/);` in your code.

For the time the echo is received is way too fast (under 0,001 seconds). I doupt you can use that for something useful. There is a way to calculate that using the `millis()` function, but it is quite complex for your project.

Here is a working code for the HC-SR04:

    const int trigPin = 2;
    const int echoPin = 3;

    long duration, distance;

    void setup() {

      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      Serial.begin(9600);
    }

    void loop() {

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distance = duration * 0.034 / 2;

      if (distance < 150) {
        Serial.print(distance);
        Serial.println("  cm");
      }
      if (distance > 150) {
        Serial.println("OUT OF RANGE");
      }
      delay(20);
    }


message:
Wake Arduino (Atmega328) from sleep with ADXL345 interrupt

So I'm relatively new to microcontrollers, and I'm having a problem implementing a feature I want for a project.

I've learned about putting an Atmega328P to sleep from [this tutorial](https://www.youtube.com/watch?v=urLSDi7SD8M). I'm using an Arduino Nano, so I only get my current down to ~9mA rather than the µAs the tutor is getting. Nonetheless, it demonstrates the abstraction I want to learn for when I move to just the Atmega328 with no board.

I've learned to wake up my microcontroller from sleep with a falling external interrupt on INT0/D2 from a simple button. My ISR is empty and just boots me back to the loop, which is fine. As an aside, I have heard that it is better to have simple and short ISR's, but I am not completely sure why.

My question is, can I use my ADXL345 to trigger an interrupt that wakes my Arduino? I am semi-familiar with using an ADXL345 over I2C, although I don't understand why my Sparkfun ADXL345 requires different wiring than my unbranded one, but that's for a separate question I suppose.

So my question is, is it possible, and if so, how? Also, is the I2C connection meaningful for an ADXL345 that is primarily being used as a wake-up interrupt on the Z-axis only? (My use case is an item someone picks up, which wakes my embedded circuit out of sleep and begins logging load cell and UWB sensor data, and is put back to sleep after a period of inactivity).

Thanks in advance - I appreciate any and all help!

body:
When using an ADXL345 to trigger an interrupt to wake an Arduino, I2C (or SPI) need not be relevant.  Instead, you can just connect pin 8 or 9 (INT1, INT2) of the ADXL345 directly to the Arduino pin that wakes the Arduino.  Note, INT1 and INT2 in this answer refer to pins 8 and 9 of the ADXL345.

On the ADXL345, map the wake-up event (or events) to whichever of INT1 or INT2 (pin 8 or 9 on the ADXL345) you've connected to the Arduino.  By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345, and might have both of them connected to different pins on the Arduino for different purposes.

As noted on page 20 of the Analog Devices ADXL345.pdf Rev. E datasheet,
> The default configuration of the interrupt pins is active high. This can be changed to active low by setting the INT_INVERT bit in the
DATA_FORMAT (Address 0x31) register.

>How do I toggle bits in an ADXL345?

You can use SPI or I2C to set up registers on the ADXL345.  You will need to configure the unit before it does anything, because it powers up into standby mode.  See the second paragraph of **POWER SEQUENCING**, page 13 in spec sheet, and see Table 6 on that same page:
>At power-up, the device is in standby mode, awaiting a command to enter measurement mode, and all sensor functions are off. After the device is instructed to enter measurement mode, all sensor functions are available.


message:
Change Digispark clock speed, run at low voltage?

I have a low voltage (3.2v) application. I was hoping to use the Digispark. I have a solution using a separate Tiny85, but want to use the Digispark USB programming.

To run at lower voltage I think you need the lower clock rate. I have done this using the standalone Tiny85. I could hook up the Digispark to the programmer direct and change the frequency fuses, however...

I assume reducing the clock rate by programming the fuses would break the Digispark boot loader as it would have the wrong timing. Correct?

Can I dynamically switch the clock frequency in my code after the bootloader or is it fuse controlled only?

Is the bootloader available and could I change it to a lower frequency? Would there be a lot of work changing the code to a different freq? Would it be powerful enough to run the USB bootloader?

body:
You can set the clock prescaler at run time. For example:

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

    #include <avr/power.h>

    void setup()
    {
        clock_prescale_set(clock_div_8);
        // etc...
    }

More details in the [documentation from
avr-libc](http://www.nongnu.org/avr-libc/user-manual/group__avr__power.html#gae2d32c0c4f18f0019e680354bcc1c3ef).

Note that with this method your Digispark will still be overclocked when
booting, so it might not be 100% reliable. But it will be overclocked
only for a very short time.


body:
The digispark uses the [micronucleus bootloader](https://github.com/micronucleus/micronucleus).

You can flash that directly onto an Tiny85 without needing the digispark module. So your existing Tiny85 solution could acquire the USB bootloader if you can spare the 2k program space for the bootloader.

I realize this is not a direct answer to your question, but you did note that you have a Tiny85 solution and wanted USB bootloader support on it.


body:
Maximum safe frequency at 3.2V is around 12.7Mhz. See figure 20-2 in the [datasheet](http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf).

This is indeed lower than the 16MHz the digispark is running at.


message:
Do I use an Arduino or an ARM based Launchpad board for my commercial project?

I want to use a board for an Industrial Project, which is based on temperature sensing, sharing and data storage.

Which board do I use?
Will it be reliable for a long span of time?
Will it be foolproof?

body:
If you are want to be professional, make a custom PCB. This lets your project be neither and also stronger. This also makes you look like you actually spent more time on the project and make it great for industries.

If you still want to use an Arduino based board, you might as well use an Teensy 3.2. They are small, powerful and are still at a low price. Buy it [here][1].

If you make a good case for your project, it could last quite a long time. It might even last many years of continuous run outside at unregulated temperatures. Just make sure it doesn't get in contact with water or high levels of humidity and you should be good.

  [1]: https://www.sparkfun.com/products/13736


body:
Adding to Candice the Cyborg's answer above.
Which board do I use?
Since its a commericial project you are going to sell then -I would say the right answer is the cheapest ARM or Arduino based board (when migrated to breadboard) to make your project.
Will it be reliable for a long span of time?
For reliability ARM and arduino would be reliable-they are after all both professional engineering products-and both can be used to make commercial products. I am assuming can be sure that your software for the ARM or Arduino is not buggy and professional-thus there is no reliability issues from the software. The span of time that the arduino can retain information reliably is given  in the data sheet-I think its about 100 years.
Will it be foolproof?
Yes if you can be sure that you get the hardware design correct and the software correct-I would imagine this is where a problem would probably come from for your device.


message:
Getting an error while uploading a code to the Arduino when ethernet shield is attached

I bought ethernet Shield today and connected it to Arduino Uno, now when I try to upldoad I get the following error, however if I remove the shield from the UNO it works fine.

    Sketch uses 10,486 bytes (32%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 661 bytes (32%) of dynamic memory, leaving 1,387 bytes for local variables. Maximum is 2,048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

[![Ethernet is not plugged in][1]][1]

Is it something wrong with he ethernet shield ?
Ethernet is not plugged in but even when i plug in the ethernet wire the indicators at Jack does not lit up

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

body:
I fixed the problem by cleaning the soldering near the SD card slot on ISCP, see image below.

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

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


message:
Arduino ESP8266 Webserver

What I would like to do is control my garden lights using the ESP8266. For this I use the Arduino approach from [here][1]. This works great, I use bootstrap and jquery even :D all is well!

Switching lights on and off using my code is fine but now I'd like to switch some continues routines, like blinking. I can start the blinking from the webpage but this code is a loop so I cannot get back to turn it  off again.

I could make it blink for a set amount of loops, so eventually it will stop blinking and show the control webpage again.
Or I can add the blinking to the hardware, maybe use a 555 for the first time?
But there might be a better way of implementing this..

Using Google I found information about Break and Interrupts, not yet what I am looking for.

    #include <Arduino.h>

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>

    const char *ssid = "mynetwork";
    const char *password = "mypassword";

    ESP8266WebServer server ( 80 );

    const int led = 5;
    String webPage =
    "<!DOCTYPE html>\
    \
    \
      <title>Funny Bunny Control</title>\
      <meta charset='utf-8'>\
      <meta name='viewport' content='width=device-width, initial-scale=1'>\
      <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>\
      \
      \
    \
    \

\

\

Funny Bunny v0.1
\

\

Omdat snuffelen er bij hoort.
\

Niet voeren aub.
\

\

aan
\

uit
\

\

\
    \
    ";

    void handleRoot() {
      server.send(200, "text/html", webPage);
    }

    void aan() {
      digitalWrite ( led, 1 );
      server.send(200, "text/html", webPage);
    }

    void uit() {
      digitalWrite ( led, 0 );
      server.send(200, "text/html", webPage);
    }

    void setup ( void ) {
      pinMode ( led, OUTPUT );
      digitalWrite ( led, 0 );
      Serial.begin ( 115200 );
      WiFi.begin ( ssid, password );
      Serial.println ( "" );

      // Wait for connection
      while ( WiFi.status() != WL_CONNECTED ) {
        delay ( 500 );
        Serial.print ( "." );
      }

      Serial.println ( "" );
      Serial.print ( "Connected to " );
      Serial.println ( ssid );
      Serial.print ( "IP address: " );
      Serial.println ( WiFi.localIP() );

      if ( MDNS.begin ( "esp8266" ) ) {
        Serial.println ( "MDNS responder started" );
      }

      server.on ( "/", handleRoot );
      server.on ( "/aan", aan );
      server.on ( "/uit", uit );
      server.onNotFound ( handleRoot );
      server.begin();
      Serial.println ( "HTTP server started" );
    }

    void loop ( void ) {
      server.handleClient();
    }

  [1]: https://github.com/esp8266/Arduino

body:
Take a look at the SimpleTimer [http://playground.arduino.cc/Code/SimpleTimer] library in the Arduino IDE environment.

You can have timers to:

 - call a function at a consistent interval,

 - call a function once after a set delay,

 - call a function a set number of times with a consistent interval
   between.


message:
Is there a way of turning a computer into a Arduino type board?

The Arduino's processing power is not sufficient for some of the tasks I would like it to perform...

I'm thinking of making a Home Automation System and would like some serious processing power at the center of it all.

So I'm wondering if I can just use standard PC parts to essentially put together my own board?!?

Is this possible???

body:
A regular Arduino uses an AVR, more "pimped" Arduino might go to ARM. Some special versions of Arduinos uses other chips, such as the ever iconic ESP8266.

For home automation, an ESP8266 is WAY enough. Using an ARM is quite and overkill for home automation. But I've never seen anybody using a full PC for it. Why? Because it is around 10-20 times more expensive. They require much more components and many other things.

Something close to a full PC that you can get is a Raspberry Pi (any version would do). They act like a small PC, some even use it as a laptop. See [PiTop] [1]. The Raspberry Pi is stronger, more powerful, and much faster then any Arduinos. The Pi also has ethernet, a graphic interface, and an audio interface built in. That means that you can pretty much connect it to a monitor and it will work as a normal PC running either Windows or Linux. You can then watch a video, with graphics and sound, from the inthernet without external modules like you would need on an Arduino. Their only weakness is that it is harder to program them to read may sensors. That is why the Arduino is popular for covering that.

At the end of the day, it is your choice. I would personnally suggest an ESP8266. This module has many GPIOs, depending on the breakout that you have, and has WiFi built in. This is a great feature for home automation. Most home automation builders use this module.

If you have any questions about the informations I just gave you, comment it, I'll reply.

  [1]: https://www.youtube.com/watch?v=DTWe7EwriiA


body:
Adding to Candice the Cyborg's answer I would go for esp8266-12 (for a specific breakout board) if you choose to go down that route-where Candice the Cyborg writes " "pimped" Arduino" this does not refer to the esp8266.
But if you're using a PC to begin with you might as well get a PC based hardware to do the home automation. Arduino can't compete with PC for power and features-but it was never designed to.

You could try linking multiple Arduino's together communicating through the serial port pins-essentialy it would work something like a parallel processor. If it's just run of the mill home automation things then this can be broken down into a parallel problem. If you update your question with more info I can give you a more specific answer. I mean if your tasks only require a little extra processing power then it may be possible to do using an addition Arduino for example.

The cheapest way to set up a PC for home automation is probably add in a parallel port card-there are project around the internet that show how to use a PC for home automation with parallel port-if you don't have a parallel port then you can get a parallel port card for less than $5-so its cheap way to get IO pins-this was the way things could be done before the days when Arduino existed.

 Using an Arduino UNO or the like is not a good idea for interfacing to USB devices -like cameras -if you has that in mind- that's because the ATMEGA chip does not natively support USB host and it's non-trivial to implement USB interface host yourself on Arduino-it would take deep knowledge of USB protocol as a minimum.

Sorry to say it on an Arduino site- but it may turn out cheaper to use a full PC (if your project can be run on an old PC you can get cheap or free) with no Arduino- a PC after all has much more hardware already built into it -lots more ports, video output and so on. Adding the cost of shields to do something similar on Arduino could cost a lot-it depends on the specifics of your question -which you don't give.


body:
One thing a PC lacks, which is kind of critical for working with sensors and things, is easy access to IO.

A PC has a number of buses, but no GPIO pins. To get any form of GPIO you will have to add extra hardware in the form of PCI cards, etc. Those kind of things, since they are not widely used, are rare and hence expensive.

People have "hacked" their PC hardware before now to add I2C devices to the I2C bus that is present on all DDRx DIMM slots (used for module identification) and using that you could add I2C IO expanders to get some GPIO pins - however that is not easy to do, and then you have the problem of programming it on top of that.

The most flexible solution is to use USB. Using the PC as the "core" processor for heavy data processing, image capture, network communication, etc is simple enough and commonly done. Then using USB you interface to the devices you want to work with - cameras, etc. You can get USB-based IO boards which provide different forms of IO communication, such as TTL UART (FT232 boards, etc), parallel GPIO, I2C buses, SPI, etc. Of course, programming those things becomes somewhat tricky, and you may end up with a massive number of dongles on your computer to interface with the large number of things you want to connect to.

So a more flexible and sensible approach is to create your own USB interface to your sensors and other items. And one of the best and easiest systems to do that is, of course, the Arduino and Arduino-like boards.

An Arduino, or multiple Arduinos, become a sensor interconnect board which you program to communicate with whatever you need to communicate. That can then pass data back to the PC through USB which then performs the heavy number-crunching and what have you. Data can then be passed back through the USB to the Arduino for controlling other things (fans, lights, heaters, whatever).

So yes, you *can* use a PC as a powerful processor system in a larger plan, but the PC itself cannot replace an Arduino.

Of course, all this is assuming you have a PC to waste on the project, or you have the requirements of massive amounts of processing power that you can't get from any decent micro-controller or SoC.

One thing to remember: there are micro-controllers available cheaply today with considerably more power than the first pentium PCs - I regularly work with 200MHz MIPS based MCUs with embedded FPU - that's 3.33 times more powerful than the first pentiums (and without the floating point bug ;) )

The current Raspberry Pi embedded Linux computers provide all the GPIO and interfacing you should need at a tiny fraction of the price of a PC. They are (as of version 3) a quad-core 1.2GHz 64-bit SoC. The same quad-core 1.2GHz core that is used in many smart phones. That's more powerful than my laptop.


body:
You could simply opt for a different platform? A Raspberry Pi or Beagle Bone? Either would probably have enough processing power and ram. The Onion Omega2 is a SoC with a 400Mhz CPU, 64MB of DDR2 RAM, 16MB of on-board flash storage, 802.11b/g/ WiFi at 150 Mbps, 18 digital GPIOs, I2C, SPI, and USB2.0, a full Linux Operating System, and it costs $5.
[The Onion Omega][1]

  [1]: https://wiki.onion.io/Documentation/Hardware/Omega-Hardware


body:
One approach that I am using in a project right now is to use _both_ an
[Arduino Mega 2560][] (for interfacing the hardware, as it has many
5 V GPIO pins, analog inputs and very predictable timings) and a
[Raspberry Pi][] (for running a [Node.js][]-based Web server). They
communicate through a level-shifted serial link, using a protocol
roughly shaped on this [command line interpreter][].

This way I have both the ease of interfacing hardware provided by the
Arduino and the power of a real computer.

Not saying it is the right solution for you, but as you did no provide
details on your project's requirements, we can only make suggestions.

[Arduino Mega 2560]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
[Raspberry Pi]: https://www.raspberrypi.org/products/raspberry-pi-3-model-b/
[Node.js]: https://nodejs.org/
[command line interpreter]: https://gist.github.com/edgar-bonet/607b387260388be77e96


message:
Arduino Pro Mini name in CMakeList.txt in CLion

I recently try to get my Arduino Pro Mini (5v 16mhz)running in Clion.

I tried to set up the CMakeList.txt but I get the following error:

> Error:Can not find f_cpu in boards.txt for Arduino board ID (pro),
> aborting.

I used the following configuration:

    set(${CMAKE_PROJECT_NAME}_BOARD pro)

In the boards text, located at C:\Program Files (x86)\Arduino\hardware\arduino\avr\boards.txt I found the following lines:

    pro.name=Arduino Pro or Pro Mini

    pro.upload.tool=avrdude
    pro.upload.protocol=arduino

    pro.bootloader.tool=avrdude
    pro.bootloader.unlock_bits=0x3F
    pro.bootloader.lock_bits=0x0F

    pro.build.board=AVR_PRO
    pro.build.core=arduino
    pro.build.variant=eightanaloginputs

    ## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
    ## -------------------------------------------------
    pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

    pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
    pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
    pro.menu.cpu.16MHzatmega328.upload.speed=57600

    pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
    pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
    pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
    pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

    pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
    pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

So I'm wondering what Boardname to use, to get the Pro Mini working. Thanks in advance!

body:
The problem here is that the Pro Mini comes in a number of variants for different voltages / speeds etc. The different variants are selected using a menu in the IDE.

CLion doesn't know about those menus, nor how to find the f_cpu from the right one for your board.

So there are two solutions:

1. Create your own board entry for the Pro Mini without the menu entries.
2. Use an earlier version of the IDE that has the Pro Mini boards as separate entries (basically any version before the menu system was created).

If you want the latest API then you will have to go route 1. That could be as simple as modifying the existing `pro.*` entries to remove the menu and replace that section with just the flags that are set by the correct menu (basically remove all the `pro.menu.*` entries except the ones for your board, then remove the `menu.cpu.<whatever>.` from each of the lines, as well as the entire menu entry name line.)

So you would basically change these lines:

    ## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
    ## -------------------------------------------------
    pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

    pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
    pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
    pro.menu.cpu.16MHzatmega328.upload.speed=57600

    pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
    pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
    pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
    pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

    pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
    pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

to this:

    ## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
    ## -------------------------------------------------
    pro.upload.maximum_size=30720
    pro.upload.maximum_data_size=2048
    pro.upload.speed=57600

    pro.bootloader.low_fuses=0xFF
    pro.bootloader.high_fuses=0xDA
    pro.bootloader.extended_fuses=0x05
    pro.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

    pro.build.mcu=atmega328p
    pro.build.f_cpu=16000000L

and delete all the other `pro.menu` entries.


message:
Problem fetching data from MPU6050

I am new to Arduino. I have an arduino mega board, which I need to interface with MPU6050 accelerometer-gyroscope module.

My connections are

Arduino_SCL->MPU6050_SCL;

 Arduino_SDA->MPU6050_SDA;

 Arduino_GND->MPU6050_GND;

Arduino_5 V->MPU6050_Vcc;

Arduino_Pin 2->MPU6050_INT;

I have uploaded the following code to the arduino mega.

    #include "I2Cdev.h"
    #include "MPU6050.h"
    #include "Wire.h"

    MPU6050 accelgyro;

    int16_t ax, ay, az, gx, gy, gz;
    double  time;
    int i;

    void setup()
    {
      Wire.begin();
      Serial.begin(9600);
      accelgyro.initialize();
      time = millis();
      i = 1;
    }

    void loop()
    {
      // collect readings
      accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

      // print result
      Serial.print(i);   Serial.print("\n");
      Serial.print(ax);   Serial.print("\t");
      Serial.print(ay);   Serial.print("\t");
      Serial.print(az);   Serial.print("\t\n");
      Serial.print(gx);   Serial.print("\t");
      Serial.print(gy);   Serial.print("\t");
      Serial.print(gz);   Serial.print("\t\n");

      i = i + 1;
      delay(1000);
    }

My problem is when I observe the reading on serial monitor, it shows every reading as zero. Does this mean my sensor is damaged or there's some problem with my connection? Or is my code for fetching the data incorrect?

Thanks

body:
If you are using the MPU6050 library from jrowberg/i2cdevlib, the library does not have any kind of error handling, so it is unfortunately not easy to guess what went wrong, or even *if* something went wrong. If the getMotion6 function fails, it will simply copy corrupt data into your return values and it is not possible after the invocation to tell if the function succeeded and you got a valid reading, or if the function failed and you only got garbage back.

One possible problem is that the MPU6050 can be configured to use one of two I²C addresses (0x68 or 0x69) and you are using the default address, as implemented in the MPU6050 library (0x68). It might be worth to try the other address, in case your module is configured that way:

`MPU6050 accelgyro(0x69);`


message:
clkI/O 256 & 1024 (From prescaler) not working with driving PWM on Nano board

I've been working with PWM in TIMER0 of my nano board.

So, it's working now and I know how to set OCR0A or OCR0B.

Then, I went to play with Clock Select Bits CS02 CS01 CS00 in TCCR0B.

0, 8 and 64 prescaler configurations worked as I also don't see the effect on the LED fade speed.

But the more problem I get is that 256 and 1024 prescaler don't work at all and the LED goes on all the time.

What is the problem?

The code:

    void setup() {
        DDRD |= (1<<DDD6);
        TCCR0A |= 0xC1;
        TCCR0B |= 0x00; // this works for 0x01, 0x02, 0x03 only
        }

        void loop() {
        uint8_t i;
        for (i=0;i<256;i++)
        {
          OCR0A = i;
          _delay_ms(1);
        }
        }

regards,

body:
The main problem is the prescaler on `Timer0` is already configured to divide clock source by `64` `CS01` and `CS00` are set `(0b00000011)`.

And you are using bitwise OR to "change" prescaler: `TCCR0B |= 0x05;` or `TCCR0B |= 0x04;`. But this'll result into the clock source `7` `(0b00000111)` - clock source is expected on `T0` input counting on rising edge.


message:
How to detect Arduino serial port programmatically on different platforms?

I am trying to write a little program that needs to detect Arduino ports automatically. I have tried many methods but haven't found any reliable way.

I can see that the Arduino IDE can detect it, by showing `/dev/cu.xyz (Arduino Uno)` or `COM6 (Arduino Uno)` etc.

How could I detect if the device connected to the serial port is an Arduino or not? Preferably without pre-flashing the Arduino with specific firmware.

I found this Python version, which uses `serial.tools.list_ports.comports()` [here][1],  but it didn't work when I tested it on Windows and MacOS.

The best I can get is by using [go-serial][2]'s `USBManufacturer`, I can get 'Arduino (www.arduino.cc)'.

I also found [this post][3], about the same question, but without any solution.

  [1]: https://stackoverflow.com/questions/24214643/python-to-automatically-select-serial-ports-for-arduino
  [2]: https://godoc.org/github.com/mikepb/go-serial#Info
  [3]: https://forum.arduino.cc/index.php?topic=115517.0

body: You can start the Arduino IDE wait unit the port is detected-which are stored on the hard drive by the arduino IDE;exit the IDE; then read through that file with your custom Windows (or whatever OS you're using -to get your answer. This answers your question you wrote above.


body:
Here is a solution:

On Windows, Arduino IDE comes with a tool named **listComPorts.exe**, which will list all COM ports and their USB info like VID & PID. There is also a file named **arduino.inf** in drivers folder contains all known device types and their VID&PID etc, and we can look for the connected device.

On *nix, the IDE take advantage of libusb and no such a tool, and it's easy to find a tool to list usb info on these platforms.

[This go package][1] mentioned in the question is a good choice, which also uses libusb and could build on all platforms. (On windows, you have to install mingw to build the C code, cygwin & msys don't work, I tried TDM-GCC and it works. You also have to add `LDFLAGS: -lsetupapi` (in serial.go) to successfully link the code.) After list all serial ports, you can search for 'Arduino' to determine the port. 'CH340' is also a keyword to search as many modified boards use this chipset.

New version of the IDE don't have **listComPorts.exe**, they all uses libusb. I find this tool from version 1.6.5.

  [1]: https://godoc.org/github.com/mikepb/go-serial


body:
Quite late for the party! Just leave it here for anyone looking for a solution on windows.

The proper way is to read the device list from registry.

First location is

> ***HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM***

[![HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM][1]][1]

A better location is here

> ***HKLM\SYSTEM\CurrentControlSet\Services\usbser\Enum***

[![HKLM\SYSTEM\CurrentControlSet\Services\usbser\Enum][2]][2]

You have the list of Arduino devices there. Mine is Arduino Leonardo. Genuine Arduino UNO uses the similar chip and it should be in there as well.

To get the port, just copy the first device (index 0) and plug into this location

> ***HKLM\SYSTEM\CurrentControlSet\Enum***

So it is like this

> ***HKLM\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_8036&MI_00\9&88cb209&0&0000***

[![HKLM\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_8036&MI_00][3]][3]

[![HKLM\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_8036&MI_00\ --- Device parameters][4]][4]

So you have friendly name and port number of the serial device. Then just write some code to read these registry locations.

In C
```
#include <windows.h>
#include <wchar.h>
#define MAX_VALUE_LENGTH 255

void getUSBSerialList()
{

 HKEY hKey;
 //check if we can read registry
 INT dwRegOPenKey = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\usbser\\Enum"), 0, KEY_READ, &hKey);
 if(dwRegOPenKey != ERROR_SUCCESS) return 0;

 DWORD type=REG_DWORD, size=0, USBser_count = 0; // a place for RegQueryValueEx to write back to
 DWORD dwRes;

 //read count of usb devices
 dwRes = RegQueryValueExW(hKey, _T("Count"), NULL, (LPDWORD) &type, (LPBYTE) &USBser_count, &size);
 if (dwRes) return 0;

 if (USBser_count)
 {
  for (INT i=0, dwRes = ERROR_SUCCESS; i<USBser_count; i++)
  {
   WCHAR achValue[MAX_VALUE_LENGTH];
   WCHAR buffer[MAX_VALUE_LENGTH];
   ZeroMemory(buffer, sizeof WCHAR  * MAX_VALUE_LENGTH);

   swprintf(achValue, L"%d",i); // read value name "0", "1"...
   dwRes = RegQueryValueExW(hKey, achValue, NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);

   // Plug that value into "SYSTEM\\CurrentControlSet\\Enum\\"
   HKEY hKey2;
   swprintf(achValue, L"SYSTEM\\CurrentControlSet\\Enum\\%s",buffer);

   INT dwRegOPenKey2 = RegOpenKeyExW(HKEY_LOCAL_MACHINE, achValue, 0, KEY_READ, &hKey2);
   if (dwRegOPenKey2) return 0; // check if this key exists

   // From here read friendly name
   dwRes = RegQueryValueExW(hKey2, _T("FriendlyName"), NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);
   if (dwRes) return 0;

   // or read COM port
   swprintf(achValue, L"%s\\Device Parameters", achValue);
   dwRegOPenKey2 = RegOpenKeyExW(HKEY_LOCAL_MACHINE, achValue, 0, KEY_READ, &hKey2);
   if (dwRegOPenKey2) return 0;

   dwRes = RegQueryValueExW(hKey2, _T("PortName"), NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);
   if (dwRes) return 0;
  }
 }
}
```

In C#, just use Registry object to do so

```
int usbser_count = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\usbser\\Enum", "Count", -1);
```

I haven't done it in C# but I think it's easier than in C.

What if yours is arduino clone that use CH340 instead of atmega16u2, it won't appear in the registry location above. It will show up here instead:

> ***HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CH341SER_A64\Enum***

You can do the same for other type of USB serial devices like CP210x (on some ESP32 dev boards)

> ***HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\silabser\Enum***

Or even get a list of WinUSB devices (such as ST-Link v2)

> ***HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WINUSB\Enum***

  [1]: https://i.stack.imgur.com/YvlZA.png
  [2]: https://i.stack.imgur.com/IAHaA.png
  [3]: https://i.stack.imgur.com/s2b3C.png
  [4]: https://i.stack.imgur.com/jmiii.png


body:
Here is snippet of C# code based on [answer][1] by [SimonVu14][2]. It looks through the named keys and gets ports for both Atmega and CH340 chips. If you expect to have just one Arduino connected to the computer, you can just go with the first one found. Otherwise you'll need to invent something to figure out which one is yours (which usually involves opening port, sending some predefined request and expecting some predefined response), or give user option to select via UI.
[![Sample][3]][3]

        private readonly string[] _arduinoKeys = {
            @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\usbser\Enum",
            @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CH341SER_A64\Enum"
        };

        /// <summary>
        /// See https://arduino.stackexchange.com/questions/30808/how-to-detect-arduino-serial-port-programmatically-on-different-platforms/80887
        /// </summary>
        private IEnumerable<(string name, string port)> EnumerateArduinos()
        {
            foreach (var arduinoKey in _arduinoKeys)
            {
                var countObject  = Registry.GetValue(arduinoKey, "Count", null);
                if (countObject is not int count)
                {
                    continue;
                }

                for (int i = 0; i < count; i++)
                {
                    var enumObject = Registry.GetValue(arduinoKey, i.ToString(), null);
                    if (enumObject is not string enumKey)
                    {
                        continue;
                    }

                    var friendlyName = Registry.GetValue($@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\{enumKey}", "FriendlyName", null);
                    var portName = Registry.GetValue($@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\{enumKey}\Device Parameters", "PortName", null);
                    if (portName is string port && friendlyName is string name)
                    {
                        yield return (name, port);
                    }
                }
            }
        }

  [1]: https://arduino.stackexchange.com/a/80887/80947
  [2]: https://arduino.stackexchange.com/users/71819/simonvu14
  [3]: https://i.stack.imgur.com/kbRnC.png


message:
Amplify Piezo Sensor

I am trying to amplify a piezo sensor per the instructions found at the link below.  I am not trying to trigger a buzzer only print to the serial monitor whether the vibration was detected or not.  I am a NOOB with respect to circuits and unable to understand why my circuit is not working.

The piezo is either giving a positive (sensing) reading or  giving a negative (not sensing) reading depending on where the poteniometer is set.  There is no state where-if all is quiet-the piezo is quite and if there is a vibration the piezo senses it and reports to the serial monitor.
I see from the blog that if the piezo get stuck on a state to lower the feedback resistor of the op-amp from 220k to 160k but again, there is never a case where it is working then get struck in state.  It is always stuck in a state!

The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor.  I am using the 10uf capacitor.  Will switching out the 10uf for a 0.1uf capacitor test potentially damage the Arduino? Is this the cause of the +-state of the piezo? Do I just have a wiring flaw?
Any advice is appreciated.

Here is a link to the post including the Fritzing diagram.
http://davidhoulding.blogspot.com/2014/02/high-sensitivity-vibration-sensor-using.html

Here is a picture of my circuit.
[![enter image description here][1]][1]

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

And the Sketch...

    #define VIBRATION_DIGITAL_IN_PIN 8
    int DurationMillis = 1000;

    void setup()
    {
      Serial.begin(9600);
      pinMode(VIBRATION_DIGITAL_IN_PIN,INPUT);
    }
    void loop()
    {
      if(digitalRead(VIBRATION_DIGITAL_IN_PIN)==HIGH)
      {
        Serial.println("I felt that");
        delay(DurationMillis);
      }
      else
      {
      Serial.println("I don't feel anything...");
      delay(DurationMillis);
      }
    }

body:
You write,
>The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor. I am using the 10uf capacitor.

The Fritzing diagram in the [high-sensitivity-vibration-sensor](http://davidhoulding.blogspot.com/2014/02/high-sensitivity-vibration-sensor-using.html) at davidhoulding.blogspot.com shows a 10μf capacitor connected from +5V to ground on the breadboard.  This is a reasonable thing to do, to avoid power supply glitching on that board.  It is ok to add an 0.1 μf capacitor in parallel (that is, in addition to, and connected to the same busses) to the 10μf if you want to suppress some noise as well.

The last diagram in the blog, an “updated circuit diagram showing the refinements for reducing the gain to avoid op-amp output lockup, and DC decoupler on the input”, also shows an 0.1 μf capacitor connected between the piezo node and the first op amp input.  This will block any DC voltage coming out of the piezo from going into the op amp input.  It's likely that any capacitor from 0.05 μf up to 0.5 μf will work just as well there.  A smaller coupling capacitor is suitable for higher frequency inputs, and a larger one for lower frequencies.  The presence or absence of that capacitor probably isn't the problem with your circuit.  Looking at your circuit photo, the wiring looks ok[*].  Perhaps try substituting a different piezo element, or a signal generator if you have one, or a low voltage from a pot varied up and down, to generate a signal into your op amp and comparator stages to see if they are working.  If they aren't working, substitute for the LM358.

[*] Although I can't see if the 220KΩ resistor goes to +5 or to pin 1.  Also is your comparator output connected into digital pin 8 on the Uno?  It looks more like 9 or 10 in the photo.  Also, as a personal preference I'd attach the Arduino end of the ground wire to a pin next to the +5 instead of to the ground next to Aref.