message:
Arduino Micro serial communication is not working after wake from power down

I'm trying to use the power down state for a battery application, but I'm having issues with the serial communication.

I'm using the `lowpower.h` library to put the Arduino Micro into power down mode.

When it wakes I flash an LED, which is working, so I know it's is waking up. And I also re-establish serial communication and send a message. This is not working. I receive nothing on the serial monitor, however the TX LED does flash.

I think the Arduino may be working correctly, but for some reason the serial monitor can't handle it. Perhaps there is a better serial monitor application?

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

    #include "LowPower.h"

    void setup()
    {
        //20sec delay added to make uploading easier (cant upload in power down state)
        Serial.begin(115200);
        Serial.println("20");
        delay(5000);
        Serial.println("15");
        delay(5000);
        Serial.println("10");
        delay(5000);
        Serial.println("5");
        delay(5000);
        Serial.println("START");
        pinMode(LED_BUILTIN, OUTPUT);
        delay(1000);
        Serial.end();
    }

    void loop()
    {
        // Enter power down state for 8 s with ADC and BOD module disabled
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

        Serial.begin(115200);
        delay(100);
        Serial.println("BLINK");
        digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(5000);                       // wait for a second
        Serial.println("BLINK_stop");
        digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
        delay(5000);                       // wait for a second

        Serial.end();

    }

Serial monitor output:

    20
    15
    10
    5
    START

and then nothing...

body:
I found the answer on this related question: https://arduino.stackexchange.com/questions/10408/starting-usb-on-pro-micro-after-deep-sleep-atmega32u4?rq=1

Which itself was a link to a sparkfun forum

Note: it requires you to close and open the serial monitor at proper timings.

    // disable the USB prior going to sleep
    USBCON |= _BV(FRZCLK);  //freeze USB clock
    PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
    USBCON &= ~_BV(USBE);   // disable USB

    // and wake it up after
    //routine to properly wake up
    sleep_disable();
    delay(100);
    USBDevice.attach(); // keep this
    delay(100);
    Serial.begin(9600);
    delay(100);


sender: user

message:
OLED on Hardware SPI, on DUE

I want to use an OLED with DUE.
I plan to connect it via hardware SPI.
The Due has a 3X2 pin connector labeled SPI. Is it here where i connect the SCK and MOSI?

If indeed, i connect it here, then which one is SCK and which one is MOSI?

Most importantly, i saw somewhere that in the DUE, hardware digital pin 13 is SCK and pin 11 is MOSI?
Is this true? Because if it is, i can simply hook it up to these pins and get rid of the confusing 3X2 pin connector.

sender: assistant

body:
It doesn't look like it's true. There is only one `SPI` module and it has fixed pins which are not duplicated anywhere.

However there are three instances of `USART` which can be used in synchronous mode as `SPI`:

* **`USART0`**: `RXD0`(`PA10`) / `TXD0`(`PA11`) / `SCK0`(`PA17`)
* **`USART1`**: `RXD1`(`PA12`) / `TXD1`(`PA13`) / `SCK1`(`PA16`)
* **`USART2`**: `RXD2`(`PB21`) / `TXD2`(`PB20`) / `SCK2`(`PB24`)

Whole table from SAM3X datasheet:

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

But I'm not sure if the `Arduino IDE` supports this mode, or you'll have to do it from scratch by yourself.

You can even use `RTS` as select slave signal:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/gDHo3.png
  [2]: https://i.stack.imgur.com/78oAx.png


message:
BMP 280 exact Altimeter readings

I was just going through this [pressure sensor tutorial][1].

What I want to know is how can I set the exact altimeter in my readings depending upon my different geographical place ? or may be if I am attaching the sensor to my balloon.

  [1]: https://iknowvations.in/arduino/pressure-sensor-bmp-280-arduino-tutorial/

body:
The tutorial sample source code has the line:

    Serial.print(bmp.readAltitude(1013.25)); // this should be adjusted to your local forcase

That `1013.25` value should be the local pressure at sea level in hundreds of Pa. If want to show altitude above ground level, you will need to know that for your location and write your code to calculate the altitude offset.

The sensor can't know location -- it only measures pressure. The AdaFruit library provides the altitude conversion, but being generic, it relies on several assumptions.


message:
How can I wire a 12V LED switch so that it is powered, but my Arduino only receives a 5V signal?

My arduino is powered by 12V.  I am getting some cool looking 12V led switches from amazon, but they need 12 volts to light up. My arduino will perform an override function when it detects the switch is closed. the digital pins can only handle 5V. How can I step down the 12V signal that powers the switch to the 5V that the pin can handle.

12V supply -> 12V led switch -> reduce 12V to 5V -> arduino digital pin

body:
You need a voltage divider:

The formula is:

V1 = 12V

R2 = 5V max

R1 = The rest (V1-R2)

And then you have to calculate max current. If you use 1/4watt resistors, you have to convert watt to current, P = U x I.

Pmax = 0,25W

R1volt = 7 volt

Imax for R1 = P/U = 0.25/7

Imax for R2= P/U = 0.25/5

Now you have the current and voltage for R1 and R2

And the relation between R1 and R2 is:

R1 = 7/12 x Rtotal

R2 = 5/12 x Rtotal

Rtotal = R1 + R2

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


message:
Power Measurement

I am trying to develop a system that reads the amount of power consumption from my load. Here is how my setup looks like;
[![enter image description here][1]][1]

The led represents a 5W and 12V light bulb(I was unable to get this in my simulator) and the battery i am using is 9 volts
Here is my code;

     sens = analogRead(A0);
     vol = sens * (2.0) * ( 5.0 / 1024.0);
     tot_vol = 5 - vol;
     current = vol / 10;
     power = current * tot_vol;
     Serial.print(power);
     Serial.print ("\n");
     delay(1000);
     if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
    }
    if (state == '0') {
     digitalWrite(ledPin, LOW); // Turn LED OFF
     state = 0;
    }
    else if (state == '1') {
     digitalWrite(ledPin, HIGH);
     state = 0;
     }
    }

I am trying to calculate the voltage drop across my resistor and then get the current and then power from that. This data is sent to an android app via the bluetooth module. However, here is the output i am getting;
[![enter image description here][2]][2]

What am i doing wrong?

  [1]: https://i.stack.imgur.com/Fl2Bj.png
  [2]: https://i.stack.imgur.com/w4oTd.png

body:
Normally the shunt resistor (in you schema 220 ohm) is way lower than the load it should measure, 12volt/5Watt = 0.42 Amp and R = U/I, 9V/0,42A = 21ohm. So your 220ohm's shunt is inflicting on the measurement value.

So to change the current measurement circuit you have to use a low ohm resistor and since the voltage drop over a shunt/low ohm resistor is small you need a amplifier.

Here is a page about how to calculate a shunt and use it with Arduino:
http://www.vwlowen.co.uk/arduino/current/current.htm

If we use a simplified version, 8v over the lamp and 1volt over the shunt.

U = I x R

Rlamp = 21 ohm

Ilamp = 8 volt/21 ohm

Rshunt = U/I = 1 volt/0.42 Amp


body:
A number of things wrong:

1. You have no ground connection to the Arduino. It can't work out what the voltage you are measuring is relative to.  ([Read this](https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/))
2. You should have the shunt resistor as the absolute last item in your chain of components so it is connected directly to ground (V+ -> LED -> LED's Resistor -> Relay -> Shunt Resistor -> GND
3. Your shunt resistor should be as low as you can get away with - low enough that it doesn't affect the circuit, yet high enough that you can measure a voltage drop. For that you need to first have a good idea about what level of current you will be measuring.

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

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

<!-- End schematic -->


message:
Unable to connect ESP8266 to WPA2+Enterprise network

I am trying to connect ESP8266 module to WPA2+Enterprise network with my ssid, username and password and the latest version supports such connection. I followed [this][1] link, and the code:

    #include "ESP8266WiFi.h"
    extern "C" {
      #include "user_interface.h"
      #include "wpa2_enterprise.h"
    }

    static const char* ssid = "ssid";
    static const char* username = "username";
    static const char* password = "password";
    const char* host = "host_ip";

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

      Serial.print("Connecting to ");
      Serial.println(ssid);
       // Setting ESP into STATION mode only (no AP mode or dual mode)
      wifi_set_opmode(0x01);

      struct station_config wifi_config;

      memset(&wifi_config, 0, sizeof(wifi_config));
      strcpy((char*)wifi_config.ssid, ssid);

      wifi_station_set_config(&wifi_config);

      wifi_station_clear_cert_key();
      wifi_station_clear_enterprise_ca_cert();

      wifi_station_set_wpa2_enterprise_auth(1);
      wifi_station_set_enterprise_username((uint8*)username, strlen(username));
      wifi_station_set_enterprise_password((uint8*)password, strlen(password));

      wifi_station_connect();
      Serial.print("Wifi station connect status:");
      Serial.println(wifi_station_get_connect_status());

      // Wait for connection AND IP address from DHCP
      while (WiFi.status() != WL_CONNECTED) {
        Serial.println(WiFi.status());
        delay(2000);
        Serial.println("Not connected");
      }

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

    void loop()
    {
      delay(2000);
    }
**OUTPUT:**

    Connecting to ssid
    Wifi station connect status:1
    6
    Not connected
    6
    Not connected
    .....

Status 6 is  WL_DISCONNECTED,i.e., module is not configured in station mode. I am not able to figure out what is causing the problem.

  [1]: https://www.hallgeirholien.no/post/esp8266-eap/

body:
The clear commands are not useful until after you have connected.
I use these commands just before setting user ID and password:

    wifi_station_set_enterprise_identity((uint8*)username1, strlen(username));
    wifi_station_set_enterprise_ca_cert(ca_cert, sizeof(ca_cert));

It is necessary that the radius server have `default_eap_type` set to TTLS or PEAP for username/password authentication. Perhaps there is another possibility, but there is a bug in ESP8266 so it does not properly search for supported EAP types.

    const char* username1 = "anonymous"; //works for me

    u8 ca_cert[] = "-----BEGIN CERTIFICATE-----\n"
    "MIIFETCCA/mgAwIBAgIJAO0ntD34r/+QMA0GCSqGSIb3DQEBCwUAMIGiMQswCQYD\n"
    "VQQGEwJVUzEXMBUGA1UECAwOTm9ydGggQ2Fyb2xpbmExDzANBgNVBAcMBkR1cmhh\n"
    "bTEeMBwGA1UECgwVTWl0Y2hlbGwvVHJhbXBlciBJbmMuMR8wHQYJKoZIhvcNAQkB\n"
    "FhBidXJ0bXNAZ21haWwuY29tMSgwJgYDVQQDDB9CdXJ0IFNlbGYgQ2VydGlmaWNh\n"
    "dGUgQXV0aG9yaXR5MB4XDTE4MDEyMzE1NTgxOFoXDTE4MDMyNDE1NTgxOFowgaIx\n"
    "CzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGluYTEPMA0GA1UEBwwG\n"
    "RHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIEluYy4xHzAdBgkqhkiG\n"
    "9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1cnQgU2VsZiBDZXJ0\n"
    "aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n"
    "AQC2O2m4JCmqimeztaZ8JasIuZqksrxvCjyWpkykoGzoR6v1/kDSuLgdp7EmtLKN\n"
    "vOJPQ2ea0yVvkFf0dQYcgDhNdAsXcqskMOprS+jefzlLQUbU1jTk+AOSiOcmxWT1\n"
    "H8uYhSp/1TkkWDM8dVO9RRIQyigVinsJNhdPyUVsTaQh3s29AL8CboixUNZWngOo\n"
    "d1+66lwy4N+3hXACJWlurgvc0q7RfqSqfJY/+lugfID0ANpGQqqu1Dq2IXZbLyx9\n"
    "roOPpC+fqX2wn5g9+RuA18OY/GPtkHc6clAoiJDGXsTRpffgsI5spdJ26WknbhO/\n"
    "3Q2vQJ2Q5m/QvSp55qOM5nevAgMBAAGjggFGMIIBQjAdBgNVHQ4EFgQUT3hChU84\n"
    "EEXHesDdKOtPqfhrg68wgdcGA1UdIwSBzzCBzIAUT3hChU84EEXHesDdKOtPqfhr\n"
    "g6+hgaikgaUwgaIxCzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGlu\n"
    "YTEPMA0GA1UEBwwGRHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIElu\n"
    "Yy4xHzAdBgkqhkiG9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1\n"
    "cnQgU2VsZiBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCCQDtJ7Q9+K//kDAPBgNVHRMB\n"
    "Af8EBTADAQH/MDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly93d3cuZXhhbXBsZS5v\n"
    "cmcvZXhhbXBsZV9jYS5jcmwwDQYJKoZIhvcNAQELBQADggEBADNmDxddEh1XSo8J\n"
    "fanCRuYqngpVFtKCzRNCtQ7aOAPrj6gRMtMAqQhlYmcbxjaVOCboAvJ8evY8x5We\n"
    "YU6eIAmg95PlDws8EvcVQhO2ZYcuOHTvdu5Q4Ior0oXaCfqdS35YcPW7pRGprY/x\n"
    "w7kbG84FFatpXPuDGQB65haqQ2KXPrILiE/jAKpTu9EBLEEN4uIAuxbB6unARovX\n"
    "YoXIQHFc32bZAjihquvs4J7FNkcSr3lJpuv03dryqMB+Qn3G8yM7PFLNL2QyS0Zu\n"
    "UbS5kDO7UqbTjtrUDolp5sUNvyrkX5ILYfZeEeaHqAlA20SFqNG7BcTY222NsCft\n"
    "yNXqX1c=\n"
    "-----END CERTIFICATE-----";

works for me. I have to go back and check whether those `\n`'s are needed.

I think I found the enterprise_identity command important for both TTLS and PEAP, and I found I needed a `ca_cert` to do PEAP but not necessary for TTLS. I am not certain why.


message:
How to do with fzz file

I have a file YunConfig.fzz file for arduino yun for map maker project with ultrasonic sensor.
How can I open or do with that file?
please answer me.

body:
Download and install the open-source, [Fritzing][1] CAD software for electronics hobbyist and open the .fzz file with that.

Versions are available for Linux, Mac, and Windows.

Installation instructions are on the [downloads][2] page.

  [1]: http://fritzing.org/home/
  [2]: http://fritzing.org/download/


body:
You can get the latest version here:
fritzing(dot)org/download/api/1.0/update/344
or find a version on softpedia


message:
Time Library Adjust Default on Windows

Looking at this Time Arduino library because I would like to send time stamps with data across my HC05-PC channel.

https://playground.arduino.cc/Code/Time

I wrote this function to get the time at any point

    String getTime() {
     String timeSecond = String(second());
     String timeMinute = String(minute());
     String timeHour = String(hour());
     String timeDay = String(day());
     String timeMonth = String(month());
     String timeYear = String(year());

     String now = timeHour + ":" + timeMinute + ":" + timeSecond + " " +
            timeMonth + "/" + timeDay + "/" + timeYear;

     return now;
    }

It seems in the docs he provides info on how to set the default time on a Linux/Unix system so that this library will always be grabbing the correct time by editing some bash files.

When I run the function, having been compiled on Windows, it begins running on 1/1/1970 0:0:0.

He does not provide any documentation for setting the Windows time stamp. How would I go about doing that?

body:
The Adafruit RTClib has a function to use the compiler date and time. You use the TimeLib maintained by Paul Stoffregen. That library does not have such a function, but you can write it yourself. For example with sscanf and setTime. Without external RTC that will only work if you upload a sketch and keep the Arduino always on. I have a clock like that, and since that clock is always on, I never had the need to add a RTC chip. When the Arduino resets, it returns to the date and time when it was compiled.

If you use a Arduino Due or Zero or M0 then they have their own rtc library.

If you want the computer to send the date and time, then you could make a command and send that via the serial port or via Bluetooth.

What kind of date and time do you want ? The local time, including the offset of the Daylight Saving Time ? That is possible, but not easy to make on a Arduino with RTC chip, in that case it is easier to send a command from the computer with the newest date and time.

It that function okay ? The object 'now' disappeares when the function ends, and yet you return that object.


message:
Convert string into char array in Arduino?

I am not that great at Arduino and C++ yet, but I'll give this a shot:

I have a char array that looks like this:

    char PROGMEM bitmap[] = {0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE};

However, I receive this char array from a string, which is basically:

    String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE";

How do I turn my `input` variable with a comma separated char array into the actual array? I need it to be fast and not use a lot of memory. I haven't been able to find a use case like this, because it's very unique.

I feel like this should be super simple to do, but I can't wrap my head around it.

Things I've tried and didn't understand that much:

**1:**

    char delimiter[] = ",";

    char* ptr = strtok_r(text, delimiter);

    while (ptr != NULL) {
      Serial.println(ptr);
      ptr = strtok_r(NULL, delimiter);
    }

>cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'

**2:**

    char buf[4800];
    text.toCharArray(buf, 4800);
    char *p = buf;
    char *str;
    int i = 0;
    char bitmap[115];
    while ((str = strtok_r(p, ",", &p)) != NULL) {
      bitmap[i] = str;
      i++;
    }
    Serial.println(bitmap);

(the total length of my characters are 4799 and the total length of hexadecimals are 114, so I'm just trying something here)

Error: Apparently you can't use  `=`?

**3:**

    char buf[4800];
    text.toCharArray(buf, 4800);
    char *p = buf;
    char *str;
    while ((str = strtok_r(p, ",", &p)) != NULL) {
      Serial.println(str);
    }

This actually prints the strings to the console, but trying to add them to a char array is still a mystery I am trying to solve right as I write this.

**4:**

    char buf[4800];
    text.toCharArray(buf, 4800);
    char *p = buf;
    char *str;
    char *ptr;
    char bitmap[115];
    int i = 0;
    while ((str = strtok_r(p, ",", &p)) != NULL) {
      bitmap[i] = strtol(str, &ptr, 16);
      i++;
    }

    Serial.println(bitmap);

I'm getting a lot closer now. `strtol(str, &ptr, 16)` actually gives me the right integers I need, but it seems like my Arduino crashes when I run this code. It simply reboots it. Error:

>assertion "heap != NULL && "free() target pointer is outside heap areas"" failed: file "/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/heap/./heap_caps.c", line 171, function: heap_caps_free
abort() was called at PC 0x4011c173 on core 1

body:
You note you can easily use `strtok()` to get individual strings of the text representation of the hex values. So now all you need is to convert the string `"0xD7"` or similar into the **number** `0xD7`.

Have a look at `strtol()` function to perform that task.


body:
So after a lot of help and some tweaking, I finally got it to work!

    String text = server.arg(0);

    char buf[text.length()];
    text.toCharArray(buf, text.length());
    char *p = buf;
    char *str;
    char bitmap[960]; //960 is fixed for now, need to count amount of commas + 1
    int i = 0;
    while ((str = strtok_r(p, ",", &p)) != NULL) {
      bitmap[i] = strtol(str, NULL, 16);
      i++;
    }

`bitmap` now contains all the XBM data from the GET request. I ran into some issues, causing the device to restart, because I accidentally forgot that the length of the bitmap array isn't 114 (that's the amount of horizontal pixels of the display). This caused it to overflow by a lot.

Huge thanks to [jose can u c](https://arduino.stackexchange.com/users/27653/jose-can-u-c) for helping me.


body:
When dealing with string containing values separated by comma (or any other *special* character), you use the function `strtok` to *parse* the string. That means, separate each value.

The mechanics is:

 - In the first call you indicate the string to parse and the delimiters. That calls return a pointer to the first token found.
 - After that, you keep calling the same way, but passing NULL as the string to parse.
 - When the call returns a NULL, you are done.

Here is how you do it:

    void setup()

    {
 Serial.begin(9600);

 String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE,0x0,0x1,0xFF,0x10,0x2";
 char *pch;

 Serial.print("Splitting string '");
 Serial.print(input);
 Serial.println("' into tokens:\n");
 // --- Start the strtok scan
 pch = strtok((char *) input.c_str(),",");

 // --- Cycle thru each comma separated hex value.
 while(pch != NULL) {
  //  pch poinst to a string representation of an hex value.
  Serial.print(pch);
  Serial.print(" ->");
  //  convert string to value.
  char *p = pch + 2;        // Skip "0x"
  int val = hex2dec(*p++);  // Convert first hex digit.

  if(*p) {  // Convert an optional second hex digit.
   val = val * 16 + hex2dec(*p);
  }

  Serial.println(val, HEX); // Print the value to check.
  //  Next hex value
  pch = strtok(NULL, ",");
 }
    }

    /*
     * Convert a hex digit to decimal.
     */
    int hex2dec(char d)
    {
     int val = 0;

     if(isDigit(d)) {
      val = (d - '0');
     } else {
      val = 10 + (toupper(d) - 'A');
     }

     return val;
    }


message:
Odd Serial behavior with Uno

I'm not understanding what's going on with my Uno. I have a very simple piece of code. no peripherals are connected. Just a bare genuine uno. I program in VisualMicro for Visual Studio.

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

     char stringy[9] = { 0x7E, 0x00, 0x05, 0x08, 0x01, 0x44, 0x33, 0x04, 0x7B };

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

      Serial.print(stringy[i]);
      //delay(300);
     }

     Serial.println("");
     Serial.print("done");
    }

    void loop()
    {
     while (1) {  }
    }

Without a delay of around 250msec or greater in the for loop, I don't get all the characters. In fact, without the delay, the code doesn't even finish executing. I only get the first character '~'. It doesn't seem to matter what my baud rate is.

This code runs fine without a delay on my Nano. What could possibly be the issue?

body:
You are printing the unprintable.

Do you think it should print:

    ~0581,34{
or

    0x7E 0x00 0x05 0x08 0x01 0x44 0x33 0x04 0x7B

What you will get is

    tilde
    null
    enquiry
    backspace
    start of heading
    comma
    three
    end of transmission
    open brace

I think you can call

    Serial.print(stringy[i], HEX);

To see the number you put in come out.


message:
Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega

I am trying to follow https://arduino.stackexchange.com/questions/25609/need-help-to-set-pwm-frequency-to-25khz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could someone please help?

Given below is the code I have tried based on an answer by @EdgarBonet in the linked post and  I tried on connecting fan pwm on each of the 3 pins 6, 7, 8 one by one and still cannot get the speed to change and the fan is just running at full speed;

 void analogWrite25k(int value)
 {
  OCR4A = value;
  OCR4B = value;
  OCR4C = value;
 }

 void setup()
 {
  TCCR4A = 0;
  TCCR4B = 0;
  TCCR4C = 0;
  TCNT4  = 0;
  TCCR4A = _BV(COM4A1)
      | _BV(COM4B1)
      | _BV(COM4C1)
      | _BV(WGM11);
  TCCR4B = _BV(WGM13)
      | _BV(CS10);
  TCCR4C = _BV(WGM13)
      | _BV(CS10);
  ICR4   = 320;

  // Set the PWM pins as output.
  pinMode( 8, OUTPUT);
 }

 void loop()
 {
  analogWrite25k(10);
  for (;;) ;  // infinite loop
 }

edit2:

Thanks for the hints by @dannyf; I read the datasheet again and below is what I am trying now but even this is not working and I am really unable to figure out if something is not right in this; I am trying to set value of OCR4C only in analogWrite25k method since fan pwm line is connected to digital pin 8 of my Mega;

    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4C1)
          | _BV(WGM41);
    TCCR4B = _BV(WGM43)
         | _BV(CS40);
    ICR4   = 320;         // TOP = 320

body:
easy.

1. find a copy of the datasheet for your mcu;

2. go to the section about your timer;

3. figure out a prescaler setting that yields the maximum roll-over count;

4. pick the timer mode that supports the roll-over count;

5. write your own analogWrite() function;

6. [optional] if you wish to reuse the stock analogWrite(), make sure that roll-over count calculated in 3) is a valid data type for the stock analogWrite(). If not, increase the prescaler in 3) until it is.

7. done.

edit: i decided to give it a try.

the following code:

    void setup() {
      // put your setup code here, to run once:
      pwm1Set(TMR1_PS8x, F_CPU / F_PWM1 / 8);  //ps = 8x, top = F_CPU / F_PWM / 8 = 80
      analogWrite(9, 20);       //dc = 20/80=25%
      analogWrite(10, 40);       //dc = 40/80=50%
    }

    void loop() {
      // put your main code here, to run repeatedly:
    }

produced the following output on an ATMega328p's TIMER1.

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

i'm reasonably sure that the output is indeed 25Khz.

the code itself however is capable of generating pwm at other frequencies.

edit2: the same code on mega2560 generating 25Khz pwm on pin6/7/8:

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

  [1]: https://i.stack.imgur.com/9hOYe.png
  [2]: https://i.stack.imgur.com/JoGp5.png

code used for that is as follows:

      //ps = 8x, top = F_CPU / F_PWM / 8 = 80
      //DC on Pin 6 = 20/80 = 25,
      //DC on Pin 7 = 40/80 = 50,
      //DC on Pin 8 = 60/80 = 75,
      pwm4Set(TMR4_PS8x, F_CPU / F_PWM4 / 8); analogWrite(6, 20);  analogWrite(7, 40);  analogWrite(8, 60);

pwm4Set() is a copy of pwm1Set(). Both are simple enough: only 5 lines of code used.


body:
Found a properly working answer for the question finally; Thanks to KIV's answer on https://arduino.stackexchange.com/questions/44809/need-help-to-set-pwm-frequency-to-25khz-on-pin-8-of-arduino-mega-to-control-spee  an additional usful thing he has added is to allow setting of duty cycle from serial monitor input for convenience while testing;

    void analogWrite25k(int value)
    {
        OCR4C = value;
    }

    void setup()
    {
        TCCR4A = 0;
        TCCR4B = 0;
        TCNT4  = 0;

        // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
        // OC4C as Non-Inverted PWM output
        ICR4   = (F_CPU/25000)/2;
        OCR4C  = ICR4/2;                    // default: about 50:50
        TCCR4A = _BV(COM4C1) | _BV(WGM41);
        TCCR4B = _BV(WGM43) | _BV(CS40);

        Serial.begin(115200);

        // Set the PWM pin as output.
        pinMode( 8, OUTPUT);
    }

    void loop()
    {
        int w = Serial.parseInt();
        if (w>0) {
            analogWrite25k(w);
            Serial.println(w);
        }
    }


message:
A beginner lost at sea, Arduino looking at the sun

I am working on trying to make a LED strip respond to natural Light levels for a sculpture. I have reached a problem in trying to get the code to work when sending PWM to the light strip. Thank you for any suggestions!

    const int analogInPin = A0;
    const int analogOutPin = 9;

    int sensorValue = 0;
    int outputValue = 0;

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

    void loop() {
      sensorValue = analogRead(analogInPin);
      outputValue = map(sensorValue, 0, 1023, 0, 500);
      analogWrite(analogOutPin, outputValue);
      Serial.print("sensor = ");
      Serial.print(sensorValue);
      Serial.print("\t output = ");
      Serial.println(outputValue);
      delay(2);
    }

I am using an NTE 2908 N-channel.

 [![NTE 2908 N-channel Mosfet, Arduino Uno][1]][1]

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

body:
You'd better post also the schematic, but I'm pretty sure you just messed up the circuit.

I think you just put the ground connection for the LED strip in the wrong pin (AREF). If you look, the top-most blue wire goes to the third pin from above in the right connector (which is AREF) instead of the fourth one (which is GND). Move this and it should work

Otherwise, put the schematic on the question


message:
Receive an array of characters using SIM900 module

I tried to receive an array of characters using SIM900, but I couldn't. I can receive just one character like `'G'`, but I want to receive a string `"abcd"`. When I used `char*` to save the SMS, I failed.

Does anyone know how?

My code:

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(7, 8);

    void setup()
    {
        pinMode(3,OUTPUT);
        Serial.begin(19200); // for serial monitor
        SIM900.begin(19200); // for GSM shield
        SIM900power(); // turn on shield
        delay(20000); // give time to log on to network. `
        SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
        delay(100);
        SIM900.print("AT+CNMI=2,2,0,0,0\r");
        // blurt out contents of new SMS upon receipt to the GSM shield's serial out
        delay(100);
    }

    void SIM900power()
    // software equivalent of pressing the GSM shield "power" button24
    {
        digitalWrite(9, HIGH);
        delay(1000);
        digitalWrite(9, LOW);
        delay(7000);
    }

    void loop()
    {
        // Now we simply display any text that the GSM shield sends out on the serial monitor
        if(SIM900.available() >0)
        {
            char *in = SIM900.read();
            if (in =="abcd") digitalWrite(3,HIGH);
            if (in == "00") digitalWrite(3,LOW);
        }
    }

body:
    #use this code and then inform me"
    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(7, 8);

    void setup()
    {
        pinMode(3,OUTPUT);
        Serial.begin(19200); // for serial monitor
        SIM900.begin(19200); // for GSM shield
        SIM900power(); // turn on shield
        delay(20000); // give time to log on to network. `
        SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
        SIM900.write(0x22);
        SIM900.write(0x0D);
        SIM900.write(0x0A);
        delay(100);
        SIM900.print("AT+CNMI=2,2,0,0,0\r");
        // blurt out contents of new SMS upon receipt to the GSM shield's serial out
        delay(100);
    }

    void SIM900power()
    // software equivalent of pressing the GSM shield "power" button24
    {
        digitalWrite(9, HIGH);
        delay(1000);
        digitalWrite(9, LOW);
        delay(7000);
    }

    void loop()
    {
        // Now we simply display any text that the GSM shield sends out on the serial monitor
        if(SIM900.available() >0)
        {
            char *in = SIM900.read();
            if (in =="abcd") digitalWrite(3,HIGH);
            if (in == "00") digitalWrite(3,LOW);
        }
    }


body:
It solved . I used another library that manipulated . And just support sim900
U can get it in this below link and include to your arduino IDE
[This library written by digispark group ][1]

  [1]: http://digispark.ir/files/GSM.zip


message:
Protothread Library Stalling on One Thread

I am trying to use a protothreading library found here

http://harteware.blogspot.com/2010/11/protothread-powerfull-library.html

to perform protothreading with my Arduino so I can "simultaneously" read from the HC-05 Bluetooth chip input to receive information from the master computer which I am connected to over Bluetooth while also processing and transmitting data from the sensors over Bluetooth.

My code looks like this

    /*
     This module uses the L293D chip to modulate and power
     two DC motors controlling the wheels of the FryeBot
    */

    #include <Time-1.5.0\Time.h>
    #include <WiShield\pt.h>

    /*L293D INPUT 7*/
    const int YELLOW_GEAR_MOTOR_BACK = 8;

    /*L293D INPUT 2*/
    const int YELLOW_GEAR_MOTOR_FORWARD = 9;

    /*L293D INPUT 10*/
    const int RED_GEAR_MOTOR_BACK = 10;

    /*L293D INPUT 15*/
    const int RED_GEAR_MOTOR_FORWARD = 11;

    /*
     Establish ratio os the rate of the faster slower gear
     to the faster gear to scale the duty cycle of the
     faster gear
    */
    const float RED_GEAR_SPEED_TO_YELLOW = 0.97;

    /*Constant for full duty cycle for analogWrite*/
    const int FULL_ANALOG_MOTOR_SPEED = 255;

    /* HC05 Setup Data */
    const int pingPin = 7;
    const int HC05PowerPin = 2;

    /* Distance data */
    long duration, cm;

    /* Values for Bluetooth RX/TX */
    char buf[25];

    char current;
    String messageHolder;
    String message;

    /* Protothreads */
    static struct pt pt1, pt2;

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

     /* add setup code here */
     pinMode(YELLOW_GEAR_MOTOR_FORWARD, OUTPUT);
     pinMode(YELLOW_GEAR_MOTOR_BACK, OUTPUT);
     pinMode(RED_GEAR_MOTOR_BACK, OUTPUT);
     pinMode(RED_GEAR_MOTOR_FORWARD, OUTPUT);
     pinMode(HC05PowerPin, OUTPUT);

     PT_INIT(&pt1);
     PT_INIT(&pt2);

    }

    static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
     static unsigned long timestamp = 0;

     PT_BEGIN(pt);

     while (1) {
      collectAndTransmitData();
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
     }

     PT_END(pt);
    }

    void collectAndTransmitData() {
     digitalWrite(HC05PowerPin, HIGH);

     pinMode(pingPin, OUTPUT);
     digitalWrite(pingPin, LOW);
     delayMicroseconds(2);
     digitalWrite(pingPin, HIGH);
     delayMicroseconds(5);
     digitalWrite(pingPin, LOW);

     pinMode(pingPin, INPUT);
     duration = pulseIn(pingPin, HIGH);

     cm = microsecondsToCentimeters(duration);

     Serial.print("TX: ");
     Serial.print(cm);
     Serial.println();

     if (message.indexOf("G") > 0) {

      analogWrite(YELLOW_GEAR_MOTOR_FORWARD, (int)(RED_GEAR_SPEED_TO_YELLOW * (float)FULL_ANALOG_MOTOR_SPEED));
      digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

      digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
      digitalWrite(RED_GEAR_MOTOR_FORWARD, HIGH);
     }
     else if (message.indexOf("S") > 0) {
      digitalWrite(YELLOW_GEAR_MOTOR_FORWARD, 0);
      digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

      digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
      digitalWrite(RED_GEAR_MOTOR_FORWARD, LOW);
     }

     /* Load the distance value into a buffer */
     String sendValue = String(cm);
     sendValue.toCharArray(buf, sizeof(buf));

     /* Write the buffer with a space after for parsing*/
     Serial1.write(buf);
     Serial1.write(' ');
    }

    long microsecondsToCentimeters(long microseconds) {
     // The speed of sound is 340 m/s or 29 microseconds per centimeter.
     // The ping travels out and back, so to find the distance of the
     // object we take half of the distance travelled.
     return microseconds / 29 / 2;
    }

    static int protothreadReadAndParseData(struct pt* pt, int interval) {
     static unsigned long timestamp = 0;

     PT_BEGIN(pt);

     while (1) {
      readAndParseData();
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
     }

     PT_END(pt);
    }

    void readAndParseData() {
     Serial.println("HERE");
     current = Serial1.read();
     Serial.print("RX: ");
     Serial.print(current);
     Serial.println();

     if (current == ' ') {
      message = messageHolder;
      messageHolder = "";
      Serial.print("message: ");
      Serial.print(message);
      Serial.println();
     }
     else {
      messageHolder += current;
     }
    }

    void loop() {
     Serial.println("A");
     protothreadReadAndParseData(&pt2, 20); // by calling them infinitely
     Serial.println("B");
     protothreadCollectAndTransmitData(&pt1, 20); // schedule the two protothreads
    }

The code prints the following in the console when executed.

    A
    HERE
    RX: �
    B
    TX: 522
    TX: 524
    TX: 524
    TX: 524
    TX: 524
    TX: 524

Then continues with TX: ### forever.

I am not sure why the code is not looping back to the first function or at least running it a second time. I am not very clear on exactly how to use this library or who maintains it. The docs on their Github page for their WiShield library which this pt.h is part of are not overly helpful. If you have any experience with other Arduino protothreading libraries let me know so I might try them out. I am not sure where I went wrong with this library in my implementation.

Here is the repo containing the package I am using

https://github.com/nicolaskruchten/arduino/tree/master/libraries/WiShield

body:
In `protothreadCollectAndTransmitData` you have a `timestamp` variable that never gets updated:

    static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
        static unsigned long timestamp = 0;   // <- This never changes
        ....

When the condition is `true` you will need to update `timestamp = millis();`.

    static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
        static unsigned long timestamp = 0;

        PT_BEGIN(pt);

        while (1) {
            PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
            // Updated. Move this here, else it ALWAYS gets called!
            collectAndTransmitData();
            timestamp = millis();   // <- Update timestamp for next time
        }

        PT_END(pt);
    }

But to make sure that is correct, you should look at the macro:

    #define PT_WAIT_UNTIL(pt, condition) \
    do {               \
        LC_SET((pt)->lc);     \
        if(!(condition)) {     \
            return PT_WAITING;    \
        }               \
    } while(0)

(You can ignore the `do/while` - that's just there so you can use a semi-colon.) As you can see, when the condition is `false` a `return` is issued. So it looks like it is safe to do it this way.

Disclaimer: I've never used this threading library. I'm working off of the source code I found here: https://github.com/fernandomalmeida/protothreads-arduino/blob/master/pt.h


message:
Programming a servo on an ATtiny85

Board: "ATtiny25/45/85"

Processor: "ATtiny85"

Clock: "Internal 1 MHz"

Programmer: "Arduino as ISP"

I want to run a servo forwards and backwards on an ATtiny85. The servo library is not compatible with the ATtiny85 so I had to write code from scratch. At this point, the code that makes the servo go forwards (clockwise) is:

    void setup() {
      pinMode(PB1, OUTPUT);
    }

    void loop() {
      digitalWrite(PB1, HIGH);
      delayMicroseconds(1000);
      // 1 millisecond determines the servo going forwards
      digitalWrite(PB1, LOW);
      delay(19);
    }

And the code that makes the servo go backwards (anti-clockwise) is simply by changing the amount of microseconds to:

    delayMicroseconds(2000);

I want to have the servo motor go forwards one cycle for a few seconds and then go backwards for a few. I want this to keep looping. At this point my code is:

    void setup() {
      pinMode(PB1, OUTPUT);
    }

    void loop() {
      digitalWrite(PB1, HIGH);
      delayMicroseconds(1000);
      digitalWrite(PB1, LOW);
      delay(19);
      digitalWrite(PB1, HIGH);
      delayMicroseconds(2000);
      digitalWrite(PB1, LOW);
      delay(19);
    }

This however just makes the servo go back and forward at the same spot forever. I do realise I might need a for loop for this but I am confused as how I will do this.

body:
The servo can't move back and forward in 40 milliseconds. It'll be more like tremble between both.

Try something like this:

    // keep sending 0 position for about 400ms
    for(int i = 0; i<20; ++i) {
      digitalWrite(PB1, HIGH);
      delayMicroseconds(1000);
      digitalWrite(PB1, LOW);
      delay(19);
    }

    // keep sending second position for about 400ms
    for(int i = 0; i<20; ++i) {
      digitalWrite(PB1, HIGH);
      delayMicroseconds(2000);
      digitalWrite(PB1, LOW);
      delay(18);
    }


message:
Variables displayed incorrectly

I am making a keypad and when I try to save the buttons that were pushed they reset back to zero.

    int tmp = 1;
    int digit = 1;
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;
    int code = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(7, INPUT);
      pinMode(2, INPUT);
      pinMode(3, INPUT);
      pinMode(4, INPUT);
      pinMode(5, INPUT);
      pinMode(6, INPUT);
      pinMode(9, OUTPUT);
      pinMode(8, OUTPUT);
    }

    void loop() {
      if (digit > 4) {
        digit = 1;
      }
      for (int i = 2; i <= 7; i++) {
        int tmp = digitalRead(i);
        if (tmp == HIGH) {
          if (digit == 1) {
            int a = i - 1;
          }
          if (digit == 2) {
            int b = i - 1;
          }
          if (digit == 3) {
            int c = i - 1;
          }
          if (digit == 4) {
            int d = i - 1;
            Serial.print(a);
            Serial.print(b);
            Serial.print(c);
            Serial.print(d);
            digitalWrite(8, HIGH);
          }
          digitalWrite(9, HIGH);
          delay(100);
          digitalWrite(9, LOW);
          delay(100);
          Serial.print(i);
          digit++;
        }
      }
    }

body:
Do you know what `int a;` does?

For example you have a global variable `a` and then you have local `a`. Local one hides global one.

In all cases you're changing local variables. Then you're printing global `a`,`b`,`c` and local `d`.


message:
WS2812 (?) RGB LED matrix turns on white

I have an RGB LED 8x8 matrix which is claimed to consist of WS2812. When turning it on, it automatically lights up all LEDs white with full brightness. The LEDs even light up without DIN being connected. I remember reading something about this behaviour and I think it was related to the LEDs being SK6812 or similar rather than WS2812, but I can't find this page anymore, nor anything else describing this behaviour.

My question is, how can I disable the LEDs lighting up when turning power on? Of course I could add some kind of relay to switch them on right before the signal is sent by the Arduino, but is there something simpler?

body:
Use a MOSFET to control the matrix power line and activate the MOSFET only a few milliseconds before turning off your LEDs: this way the few millis intercurring between power on and off control signal will not be noticeable and will reduce the current bootstrap consumption.

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

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

<!-- End schematic -->


message:
ESP8266: Client Server Based Home Automation System

I am working on a home automation project in which I am trying to use Star Topology, where one esp8266 acts as a server and can be accessed from web browser to receive commands from the user, while two or more esp8266 acts as clients which are connected to relays. Upon the request of user, server esp8266 sends command to the respective client to trigger the relay and the client esp8266 replies with the current status of the relay.

Connections isn't a problem so I am keeping those things aside. So far

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

    const char *ssid = "AndroidAP";
    const char *password = "qvdo2440";

    ESP8266WebServer server(80);
    String webPage = "";

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

    void setup() {
      webPage += "
ESP8266 Web Server
";
      webPage += "
Socket #2 <button>ON</button>
     <button>OFF</button>
";

      delay(1000);
      Serial.begin(115200);
      WiFi.begin(ssid, password);
      Serial.println();
      while (WiFi.status() != WL_CONNECTED) {
       delay(500);
        Serial.print(".");
      }
      Serial.print("Configuring access point...");
      WiFi.softAP(ssid, password);
      IPAddress myIP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.println(myIP);
      server.on("/", handleRoot);
      server.begin();
      Serial.println("HTTP server started");
    }

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

This is the code for server side. I cannot think of how to program for client side. Any help would be appreciable.

And yes. I have been through many articles, tried out many things which i found on the internet. But nothing could help me. So i am here for few more suggestions with better elaboration.

body:
I agree with most of 'Look Alterno's comment.  So here it is explained in more detail.

Each ESP runs a web server.
Each ESP will handle

 - GET /root/status
 - POST /root/change?device=x,state=y

When a client requests /root/status information on each relay managed by the device will be displayed.  For satellite ESPs this will mean displaying live data and for the central on it will mean displaying the last known state (it could also request an update at this time).  If you use an array then presenting this information will be quite simple.

When a client posts a change to a device then the satellite ESPs will change the relay state and the central ESP will forward the message onto the satellite.  It should probably also request a status update to check that the change has occurred.

If you steer clear of hardcoding things and use arrays rather than variable1, variable2, variable3 you should be able to make this expandable.  The biggest problem you will have is registering the satellites with the central device, but you could get around that for now by adding a configure page which had a HTML form that allowed you to enter the IP address of the central device and enter the name of the satellite and the name of the things connected to the relay.

Personally I wouldn't use a PC web server, yes it gives you more processing power, but I don't think you really need it for this, I was surprised how good they were.  If you have issues look at using an ESP32 instead of a ESP8266 for the central node.

I hope that helps


message:
Esp32 Https Problem

I am working on a project in which i have to send GET request to my Company's  Https server. I have successfully sent the GET request using NodeMCU v 1.0 (ESP 12E). The **NodeMCU 1.0 (ESP 12E)** Arduino library uses SSL certificate Fingerprint ,host name and url to send the GET request. it is easy to find the fingerprint of Certificate using this website ->  https://www.grc.com/fingerprints.htm

But in ESP 32 Arduino Library i have to pass the SSL certificate . I have no idea how to find the SSL certificate of my Company's website.

The format of the SSL certificate used in ESP 32 Arduino library is given below :

    /*
    const char* ca = \
    "-----BEGIN CERTIFICATE-----\n" \
    "MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \
    "MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \
    "DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \
    "SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \
    "GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \
    "AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \
    "q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \
    "SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \
    "Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \
    "a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \
    "/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \
    "AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \
    "CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \
    "bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \
    "c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \
    "VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \
    "ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \
    "MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \
    "Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \
    "AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \
    "uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \
    "wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \
    "X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \
    "PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \
    "KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \
    "-----END CERTIFICATE-----\n";
    */

Is there any easy way to find the SSL certificate of any website which uses Https instead of simple http ?

Thanks in advance

body:
in chrome:

- press [F12]
- click the "Security" tab
- click the "View Certificate" button under "Security overview"
- click the "details" tab on the "Certificate" popup
- click the "Copy to File..." button
- click the "Next" button
- check the "base64 encoded x509" option
- click the "Next" button
- click the "Browse" button and choose a folder for the export
- enter a file name in the provided space
- click the "Next" button
- click the "Finish" button
- browse to the folder and open the export using a text editor

The export file has the same format, you just need to convert to a C literal usiing end-of-line slashes and quotes, an exercise i'll let you handle. There might be some fancy tool that does all this for you, I'd love to hear about one, but I know this is a fairly universal way to get it done.


body:
Using e.g., openssl is possible. The command could go like this from the shell:
`openssl s_client -showcerts -servername www.theserver.io -connect www.theserver.io:443 -certform DER`

Including `>mycertif.der` at the end of the command, you get the information in a file so you can cut-paste that part of the command output.
Best,


body:
Even if it's an old question... I suggest **not** rely on methods describe here. Of course you can get the SSL certificate from the browser and copy-paste it into your code. But each time the server will renews the certificate, the key change!
If you have a "free" certificate, like the one from Let's Encrypt, used for example in all the shared hosting of all major web hosting companies, the key will change every... 3 months! So you'll have to update your ESP code each 3 months... For testing purpose, that's OK but for real "application" it's not a good option.

So,how can we do?
 - Option 1: add a module on your web server, allowing to have a pre-defined SSL key. You just set the key for a specific folder and copy it to your ESP. My server is an Apache one and it seems this modules don't exist for Apache.
 - Options 2: edit your Apache conf (commonly at etc/apache2/) for your serveur. In many cases, each time a customer access your server with http, Apache will change the call to https.
This is made with a rewrite rule. You can change this like that:

         RewriteCond %{HTTPS} off
         RewriteCond %{THE_REQUEST} !/XXXXXX [NC]
         RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

         RewriteCond %{HTTPS} on
         RewriteCond %{THE_REQUEST} /XXXXXX [NC]
         RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

where XXXX is the name fo the folder in which you will put the script called by your ESP. With that all folder on your site are using https except the one you use with your ESP. Of course this mean your ESP call is done using http and not https but in many cases we have to use ESP+https not for real security reason but because the web site is in https.


message:
Where to use "static volatile bool"?

Why in the piece of code below we use "static volatile bool"?

    static volatile bool wifi_connected = false;

taken from here: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino

body:
`static` means that the global will only be accessible inside the current translation unit.

`volatile` means that `while(!wifi_connected){/*...*/}` cannot be optimized to `if(!wifi_connected)while(true){/*...*/}`

These things are orthogonal. So you would use static volatile when you need both properties.


message:
Xbee AT Commands failing. Something wrong with Serial? Tx commands working fine

The Xbee API library is working fine for TxRequests on my Arduino, but AT commands are failing every time. I've been at this for three days.

It seems that there is some sort of conflict happening with my hardware serial port, because if I try to repeat the command a second time (after a 3sec delay), I see that the 2nd transmission (which should trigger the "D_in" light on my Xbee shield to flash) never gets sent. Then if I try to load and execute the sketch again (this shield on the nano allows me to do so with the Xbee still plugged in), I get an avrdude error suggesting that my arduino serial is busy. My PC should be out of the picture here, since I have no Serial.print() functions and the cable is plugged into a wall adapter with power only.

Basically I get no response and the parameter I'm trying to change remains unchanged. I'm at a total loss for why this is not working. Heres my code:

    #include <XBee.h>

    XBee xbee = XBee();

    uint8_t D3[] = { 'D', '3' };
    uint8_t high[] = { 0x05 };/////for DI03 pin parameter
    uint8_t low[] = { 0x04};////for DI03 pin parameter

    AtCommandRequest AtRequest = AtCommandRequest();
    AtCommandResponse atResponse = AtCommandResponse();

    void setup()
    {
     Serial.begin(9600);
     xbee.setSerial(Serial);
     delay(10000);

     AtRequest.setCommand(D3);
     AtRequest.setCommandValue(low);
     AtRequest.setCommandValueLength(sizeof(low));
     xbee.send(AtRequest);

     delay(3000);

     AtRequest.setCommand(D3);
     AtRequest.setCommandValue(low);
     AtRequest.setCommandValueLength(sizeof(low));
     xbee.send(AtRequest);

    }

    void loop()
    {

    }

And in addition, here's the code for the Tx example that works just fine:

    /**
    * Copyright (c) 2009 Andrew Rapp. All rights reserved.
    *
    * This file is part of XBee-Arduino.
    *
    * XBee-Arduino is free software: you can redistribute it and/or modify
    * it under the terms of the GNU General Public License as published by
    * the Free Software Foundation, either version 3 of the License, or
    * (at your option) any later version.
    *
    * XBee-Arduino is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    * GNU General Public License for more details.
    *
    * You should have received a copy of the GNU General Public License
    * along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
    */

    #include <XBee.h>

    /*
    This example is for Series 1 XBee
    Sends a TX16 or TX64 request and checks the status response for success
    Note: In my testing it took about 15 seconds for the XBee to start reporting success, so I've added a startup delay
    */

    XBee xbee = XBee();

    unsigned long start = millis();

    // allocate two bytes for to hold a 10-bit analog reading
    uint8_t payload[5] = { 0x41, 0x42, 0x43, 0x44, 0x45 };

    // with Series 1 you can use either 16-bit or 64-bit addressing

    // 16-bit addressing: Enter address of remote XBee, typically the coordinator
    Tx16Request tx = Tx16Request(0x03, payload, sizeof(payload));

    // 64-bit addressing: This is the SH + SL address of remote XBee
    //XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x4105B41E);
    // unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
    //Tx64Request tx = Tx64Request(addr64, payload, sizeof(payload));

    TxStatusResponse txStatus = TxStatusResponse();

    int statusLed = 11;
    int errorLed = 12;

    void flashLed(int pin, int times, int wait) {

     for (int i = 0; i < times; i++) {
      digitalWrite(pin, HIGH);
      delay(wait);
      digitalWrite(pin, LOW);

      if (i + 1 < times) {
       delay(wait);
      }
     }
    }

    void setup() {
     pinMode(statusLed, OUTPUT);
     pinMode(errorLed, OUTPUT);
     Serial.begin(9600);
     xbee.setSerial(Serial);
    }

    void loop() {

     // start transmitting after a startup delay.  Note: this will rollover to 0 eventually so not best way to handle
     if (millis() - start > 10000) {

      xbee.send(tx);

      // flash TX indicator
      flashLed(statusLed, 1, 100);
     }

     // after sending a tx request, we expect a status response
     // wait up to 5 seconds for the status response
     if (xbee.readPacket(5000)) {
      // got a response!

      // should be a znet tx status
      if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
       xbee.getResponse().getTxStatusResponse(txStatus);

       // get the delivery status, the fifth byte
       if (txStatus.getStatus() == SUCCESS) {
        // success.  time to celebrate
        flashLed(statusLed, 5, 50);
       }
       else {
        // the remote XBee did not receive our packet. is it powered on?
        flashLed(errorLed, 3, 500);
       }
      }
     }
     else if (xbee.getResponse().isError()) {
      //nss.print("Error reading packet.  Error code: ");
      //nss.println(xbee.getResponse().getErrorCode());
      // or flash error led
     }
     else {
      // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
      flashLed(errorLed, 2, 50);
     }

     delay(1000);

    }

body: Just a thought from a point of ignorance.. When I use serial comm, I always use an interrupt watching loop.  When data hits UART, a data available pin throws an interrupt that causes the loop to read the input register.


body: So it turns out that it was working the whole time. The problem was that that the values were not being written to the xbee, only changed. Hence, hen I would check the radio in XCTU, the values would have reverted to previous. I had no idea I needed to be calling a "write" function to save the parameters to the radio.


message:
DS18B20 setting resolution without addressing

As i understand the dallas library, there are two ways of referencing the sensor, one is to refer to the address, and the other is just to grab it as it is indexed.(gettempbyindex)

I want to know how to set the resolution of the sensor when i'm using the gettempbyindex method, all the examples i can find seem to only set resolution when specifying the address explicitly..

Is it even possible?

body:
You can use [getAddress](https://github.com/milesburton/Arduino-Temperature-Control-Library/blob/7cd1b0d37a88cb559c858eb48006611fb6bd4fe6/DallasTemperature.h#L60): `bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index)`

If you want to set the resolution for all devices, you can just use `void DallasTemperature::setResolution(uint8_t newResolution)`. (It will call getAddress for all indices.)


message:
How can i build mouseless technology with arduino?

I want to build mouseless technology with arduino as shown in this [link][1]

Can anyone tell me how to approach this with arduino? Or what can be the logic behind it?

  [1]: http://www.pranavmistry.com/projects/mouseless/

body:
Your question is far far far too broad. No one is going to come here, post all the electrical schematics you need, all the code you need, and walk you through step by step. That's not how this works. The stack exchange requires that the poster make some effort to make progress in thier project before posting specific problems they are having.

That being said I will say that what you want to achieve is not possible on only an arduino. The method you posted in the video requires a lot of image processing to track the blobs. This is not something a microcontroller such as the arduino can achieve. A more powerful Intel based device may have some potential for your project but I doubt it.

I once did image processing with the raspberry pi. The pi itself is still not powerful enough to perform real time image processing to a good level, however it's a possibility that it could work (my image processing was more complicated than processing a binary image and tracking dots).

The ideal solution for you would be to do exactly what this guy has done. Build an application on a laptop or desktop computer which has enough power for the image processing. I suggest taking this route first even if downscaling to a raspberry pi is possible in the future, it will introduce you to image processing, and at least you know that it CAN work, as there is a working example.

Look up OpenCV if you havnt already, download, build it, follow tutorials and start from there! Then I think you should aim to build an application that tracks white objects in the frame. And that would be your first step to completion.


message:
Is it possible for Arduino firmware to recognise only one computer?

Is it possible to adjust the Arduino firmware to recognise only one PC computer? On other computers it would show driver not recognised or driver not found.

E.g.: My computer should see the Arduino normally, and it should not work if I connect the same arduino to other computers.

body:
No.

However, it is possible to place unusual and/or secret requirements on the computer's drivers or application software - however those software components could be present on multiple computers unless you also take measures to node lock them.

- You could customize the USB VID/PID and descriptors, causing the device not to be recognized by a usual driver

- You could alter the behavior of the USB interface (or bootloader and sketch) to require unusual operations - either obscure, or even secret to the level of unique-per-unit cryptography

- Or most simply, you could just use a board without a USB interface and bring your own.  Especially if you lock the flash, there's not a whole lot others can do except entirely erase your work and be left with an unusually expensive ATmega evaluation board.

Do note also that most operating systems make it possible to easily intercept the raw USB traffic going to/from devices, so someone who can see it in operation can learn a lot about how it is working.

If you want to play games with odd USB implementations, you'll probably do better with a direct USB board like a Leonardo - and you will certainly want to have an ISP setup to recover it, as your efforts will no doubt break it many times before you get something on there which works as intended.


message:
just a silly doubt about glowing an LED

what will happen if i insert the anode of a LED to pin 12 and cathode of the LED to pin 11 and set pin 12 to high and pin 11 to low,will the led glow??

body:
Yes it will, try it. This is one of the way to use a LED as a light sensor and light source by connecting it to two different Digital pins.

Ref.: https://playground.arduino.cc/Learning/LEDSensor


body:
What will happen is you will damage your LED and/or your Arduino since you haven't mentioned a current-limiting resistor (220 ohms could well be suitable).

However the general concept is perfectly sound. You could, for example, have two LEDs, wired in opposite directions. By bringing one pin LOW and the other HIGH, one LED would light up, and by reversing the output to the pins the other LED would light up. If both pins were either HIGH or LOW then neither LED would light up, as there would be no voltage difference between the leads.

There is a [calculator for LED resistors](http://led.linear1.org/1led.wiz).


message:
Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan

This question is not same as the other one and this is more about employing the pwm signal to drive a CPU fan;

I am trying to follow the answer by Edgar Bonet on the question https://arduino.stackexchange.com/questions/25609/need-help-to-set-pwm-frequency-to-25khz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4 and use this pwm signal to control the speed of a 4-wire cpu fan(with black, yellow, green and blue wires);

Following is my updated code for generating the pwm signal on timer 4

 void analogWrite25k(int value)
 {
  OCR4C = value;
 }

 void setup()
 {
  TCCR4A = 0;
  TCCR4B = 0;
  TCNT4  = 0;
  TCCR4A = _BV(COM4C1)  // non-inverted PWM on ch. C
     | _BV(WGM41);  // mode 10: phase correct PWM, TOP = ICR4
  TCCR4B = _BV(WGM43)
    | _BV(CS40);   // prescaler = 1
  ICR4   = 320;      // TOP = 320

  // Set the PWM pin as output.
  pinMode( 8, OUTPUT);
 }

 void loop()
 {
  analogWrite25k(10);
  for (;;) ;  // infinite loop
 }

I have connected pin 8 on the mega to the pwm input on the fan(blue wire) but I dont see any variation in fan speed and fan seems to run at full speed;

I dont really have any means or tools to verify if its really generating a 25khz pwm signal but fan speed is not changing or if its not generating a 25khz pwm signal because of which there is no change in the speed of fan;

I am stuck at this point and any help on this would he highly appreciated;

body:
I've just tested your setting with older "Alpine 64 GT" CPU Fan and it works as expected. I've just added parsing integers sent from serial monitor, so I don't have to change code anymore.

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

    void analogWrite25k(int value)
    {
        OCR4C = value;
    }

    void setup()
    {
        TCCR4A = 0;
        TCCR4B = 0;
        TCNT4  = 0;

        // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
        // OC4C as Non-Inverted PWM output
        ICR4   = (F_CPU/25000)/2;
        OCR4C  = ICR4/2;                    // default: about 50:50
        TCCR4A = _BV(COM4C1) | _BV(WGM41);
        TCCR4B = _BV(WGM43) | _BV(CS40);

        Serial.begin(115200);

        // Set the PWM pin as output.
        pinMode( 8, OUTPUT);
    }

    void loop()
    {
        int w = Serial.parseInt();
        if (w>0) {
          analogWrite25k(w);
          Serial.println(w);
        }
    }


message:
Reading FAN tachometer/RPM on 4 wire fan using arduino

I am following the wiring and code at https://playground.arduino.cc/Main/ReadingRPM but using pin 9 to read the speed instead of pin 2 and I have added a 10K pull up resistor between pin 9 and +5V as well; I dont see any interrupts firing even though the fan is running;

The fan is a standard intel cpu fan with 4 wires(black, yellow, green, blue) and the green wire is the sense/tach wire and I have connected it to pin 9 as well;

Need some help or expert advise; I am not sure if the approach works fine or not;

body: There are no interrupts on pin 9 (unless you are using Pin Change interrupts...?). You have to use pin 2 (interrupt 0), or pin 3 (interrupt 1) (also, on the Mega: 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2)).


message:
How to get elapsed seconds since Jan 1, 1970?

I am building a time-critical system using Arduino. Is there any way to get the **elapsed seconds** like `time.h` of **C** in Arduino? I tried `time(NULL)` but it returns `0`. Then moved forward to use `now()` in `Time.h`. But the result persists.

How can I get the elapsed seconds since Jan 1, 1970 until now?

body:
An arduino does not have a real time clock (RTC) built in. Every time it restarts it will reset the millis counter.

You will need to add a RTC peripheral that you can poll to find the current date and time.


body:
You must use an RTC module like DS3231 or DS1307 for such purposes and there are good libraries available for these modules;

Unlike the standard return value of milli seconds elapsed since Jan 1 1970 00:00 on a computer, **the millis() function on arduino just returns the number of milliseconds since the board began running the current program** and this number will overflow (go back to zero), after approximately 50 days as per the official documentation at https://www.arduino.cc/en/Reference/Millis

While millis() can be used for very basic time controlled operations, its not really reliable to be used for time critical operations;


body:
There is an 1307 RTC module emulator for Arduino: [DS1307Emulator][1].
You can set this emulator running and save seconds to `struct tm *timeStructure` and afterwards converting the structure to a `time_t` variable using time.h functions

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

    DS1307Emulator.init(13);
    DS1307Emulator.bufferUserData();
    DS1307Emulator.writeToRTC(0x00); // set address 0
    DS1307Emulator.writeToRTC(0x00); // start the RTC issuing the clock run command at address 0
    DS1307Emulator.setUserData();

Adresses are as follows:

- 0x00 - seconds
- 0x01 - minutes
- 0x02 - hours

If you want to use weekdays, date, year etc. refer to the DS1307 datasheet or check examples on the link I provided.

For reading seconds:

    DS1307Emulator.bufferUserData();
    DS1307Emulator.writeToRTC(0x00);
    temp = DS1307Emulator.readUserData();

`temp` now holds seconds in binary format, you may want to convert them to dec.

Check out examples in the link I gave for full operation.

  [1]: https://github.com/thexeno/DS1307-Emulator-Arduino-Library


body:
The accepted answer is not the only (nor best) answer. It depends what you have in hand.
The [Time library][1] will allow your arduino to keep the current time, it just need to be set the time periodically (because of clock shifting issues)
There are several ways you can get the current time:

* Use a GPS module
* Get time from NTP server if you have network access to one, using an Ethernet shield or may be wifi
* Use a custom Serial interface
* Use a GSM service
* Use a RTC module, may be the most popular and standalone, like the DS3231. However these kind of module will also require some adjustment in the long term, and they require a backup battery (often a coin like CR2032) to keep time when module is not externally powered.
* Use a few push buttons and LCD to have the user manually input it.
* Use a light sensor to see when it is the brightest time of the day and using azimuth calculation determine the hour of the day (ok, I might be going to far here, but consider a solar powered device in the middle of nowhere)

I sorted them in the order I would choose it if I have several options available.
Those are a few ways that come to my mind

  [1]: https://playground.arduino.cc/Code/Time


message:
Use ESP-01 with Arduino Uno/Nano, with the ESP8266WiFi library

There is this library - https://github.com/esp8266/Arduino
That provides a more user-friendly API for WiFi capabilities with the ESP8266.

However, all tutorials that I found so far for this library show how to program the ESP8266 (usually 12) directly. That is not what I'm looking for.

My current setup is having an Arduino Uno/Nano where the ESP8266 is connected to, say, GPIO8 and GPIO9 (RX, TX) and I use SoftwareSerial to communicate with it with AT commands. So I want to keep all the logic in my Arduino, but use ESP-01 only to provide WiFi capabilities to my Arduino.

However in that library I don't see the option to set the serial port pins (RX and TX) so I'm not sure if that's even possible.

In short - I want to use this library, but not program the ESP directly. Also, I'm using an ESP-01 and not 12.

Thanks.

body:
You cannot use that "library". Simply because that isn't a library, that is a *core*. It's the entirety of the Arduino API designed to run on an ESP8266.

You can use it to program the ESP8266 directly and nothing else. No part of that has anything at all to do with Arduino boards like the Uno.


body:
You can infact connect ESP as a serial device to the arduino and use AT commands supported by the ESP to interact with it and achieve what you want;

For ESP-01 read the detail on http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/

 Please read the following instructable which has detailed explanation on how to connect ESP12 also if interested;
http://www.instructables.com/id/ESP-12E-ESP8266-With-Arduino-Uno-Getting-Connected/


message:
Sim800l gsm module cannot connect gprs data

I am a rookie to arduino. I am trying to access MQTT server using Sim800l coreboard GSM module with Adafruit Fona/Tinygsm library but failed.So I decided to check http GET/POST request with AT command first.In AT commands all the basic commands following www.exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L  works fine  but whenever I make a GET request by "AT+CIPSTART=" module restart itself.[![by AT commands][2]][2]I also tried seeduino library GPRS_HTTP example, it gives me "error:CIPSTART" and restarts module.Though this code worked one time only,this is the code

    #include <gprs.h>
    #include <SoftwareSerial.h>

    char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt
    HTTP/1.0\r\n\r\n";
    char buffer[512];

    GPRS gprs;

    void setup() {
    Serial.begin(9600);
    while(!Serial);
    Serial.println("GPRS - HTTP Connection Test...");
    gprs.preInit();
    while(0 != gprs.init()) {
     delay(1000);
     Serial.println("init error");
    }
    while(!gprs.join("gpinternet")) {  //change "cmnet" to your own APN
      Serial.println("gprs join network error");
      delay(2000);
    }
    // successful DHCP
    Serial.print("IP Address is ");
    Serial.println(gprs.getIPAddress());

    Serial.println("Init success, start to connect mbed.org...");

    if(0 == gprs.connectTCP("mbed.org", 80)) {
      Serial.println("connect mbed.org success");
    }else{
      Serial.println("connect error");
      while(1);
    }

    Serial.println("waiting to fetch...");
    if(0 == gprs.sendTCPData(http_cmd))
    {
    gprs.serialDebug();
    }

    //  gprs.closeTCP();
    //  gprs.shutTCP();
    //  Serial.println("close");
    }

    void loop() {

    }

also tried this commands and module got restarted after AT+HTTPACTION=0 this last command
[![enter image description here][5]][5]

module power and sim configure are fine as far I know,please help me find out what am I doing wrong?Sorry for making this long.please ask me if I couldn't make the question clear.TIA

  [2]: https://i.stack.imgur.com/cIJCG.png

  [5]: https://i.stack.imgur.com/cckvd.png

body: I get it now , a stable power source is the answer. arduino with usb can give right amount of Volts but it lacks stable power(amps i guess) while making a TCP connection, that's why module keep restarting.Although it works fine with call, text etc. powering arduino with an AC adapter solves my problem ,now it can connect to mqtt too.Thanks


message:
Adafruit Feather 32u4 Bluefruit LE and HC-05 Bluetooth module

Is it possible to connect an Adafruit Feather 32u4 Bluefruit LE with an HC-05 Bluetooth module?

I am making a heart rate monitor using an Adafruit Feather, but it is unable to send the data to LABView for processing as it uses BLE. I do not have the means to buy a Bluetooth dongle to work around the issue.

However, I do have an HC-05 Bluetooth module that can be read by VISA on LABView.

Therefore I would like to ask if it is possible to connect my Adafruit Feather to my HC-05 module and send the data through the HC-05 instead of the built-in BLE.

Thank you!

body: HC-05 does not support BLE as far as I know but you can use a HM-10 if you can get your hands on one; Its almost about the same cost as a HC-05, maybe a little more;


message:
Arduino protecting analog input with internal voltage reference

Usually a common way to protect an analog input consists on reducing voltage and current in the following way:

Current limiting components, as Resistors or inductors and voltage limiting components as diodes, zener, tvs.

In this case for components availability I have used two resistors and a zener diode.

The circuits aims to accept a 0-10V input and read it with the internal reference voltage 1,1V.

The question is the following: Assuming I want to use a 2,2V zener diode as overvoltage protection and 1,1V internal voltage reference, can I consider it safe or the 2,2V of zener will be too much for the 1,1V reference?

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

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

<!-- End schematic -->

NOTES: I am using 2,2V zener diode because is the smallest size I can found.
I could use two normal diodes to reach 1,4V but maybe it will be too much for 1,1V reference and the result could be the same.
I could also add an external reference, but I would like to know if I can have problems with this configuration.

body:
Yes, it is safe.  The reference voltage is only used as a comparison. The ADC is still powered by, and limited by, the chip's supply voltage (5V).

The AREF voltage has no bearing on what limits there are on voltages you can apply to a pin. All that will happen is that voltages above 1.1V will register as 1023. You can go right up to 5V safely.


body:
As far as I know, no one uses a zener diode in a analog circuit that is used to measure a voltage. Well, at least no one who is serious and knows what he/she is doing.

The zener diode will start leaking at a lower voltage and it might introduce noise. I never use a zener diode in a analog input circuit that is used to measure something.

What is the maximum positive and negative voltage that you want to protect the Arduino against ?

Suppose using a 5V ATmega chip, with R1 = 100k, R2 = 10k, C1 = 10nF, with 1.1V as reference (and no extra ESD or clamping diodes and no zener diode). Then you are protected up to **160 V**.
That is a constant voltage of 160 V that is allowed, as long as R1 can dissapate the heat.
That means without the zener and better choosen values of the resistors, it becomes more accurate and safer and more sturdy.

Calculation: A0 can be up to 5.5V. Then the internal diodes start to conduct, and it is allowed to push 1mA into the pin.
Current R2 = 5.5 / 10k.
Current into pin = 1mA.
Voltage over R1 = 100k * ((5.5/10k) + 1mA).
External signal = 5.5 + voltage over R1.

Suppose a leakage current for a 2.2V at 1V is 0.02mA. That seems a reasonable number from what I can find. That will influence your measurement by maybe 2 percent (I'm not sure, I didn't do the calculation). That would mean that of the 10-bit resolution you dropped to 6-bit resolution (I'm also not sure about this one).
To protect the analog input, instead of a 2.2V zener, a 5V zener would be more appropriate (that is: when going down the wrong path to use a zener). The 1N4733A has a leakage current of 10 µA at 1V, and that will still influence the analog signal and still cause a less accurate voltage measurement.


message:
Dust sensor code with a few errors

I'm fairly new to this and I'm having trouble with a code for a dust sensor. Getting a couple of errors. I downloaded this code from GitHub.
Anyone have any idea how to fix any of these errors? Any help is appreciated.
Sorry if this formatted wrong, this is also my first post. Thanks for your time

    // SDS011 dust sensor example
    // -----------------------------
    //
    // By R. Zschiegner (rz@madavi.de).
    // April 2016

    #include "SDS011.h"
    #include<SoftwareSerial.h>
    SoftwareSerial myserial(0, 1);
    SDS011(byte pin_rx, byte pin_tx)
    float p10,p25;
    int error;

    SDS011 my_sds;

    void setup() {
      my_sds.begin(0, 1);
      Serial.begin(9600);
      while (!Serial) {
        ;
      }
    }

    void loop() {
      error = my_sds.read(&p25,&p10);
      if (! error) {
        Serial.println("P2.5: "+String(p25));
        Serial.println("P10:  "+String(p10));
      }
    delay(100);
    }

here are the errors I'm getting

    code:10: error: expected ')' before 'pin_rx'

     SDS011(byte pin_rx, byte pin_tx)

                 ^

    C:\Users\Nick\Desktop\code\code.ino: In function 'void loop()':

    code:26: error: 'p25' was not declared in this scope

       error = my_sds.read(&p25,&p10);

                            ^

    code:26: error: 'p10' was not declared in this scope

       error = my_sds.read(&p25,&p10);

                                 ^

    exit status 1
    expected ')' before 'pin_rx'

body:
You have to use the begin command. Instead of:

    SDS011(byte pin_rx, byte pin_tx)

    ...

    SDS011 my_sds;

Use

    SDS011 my_sds;

(Thus remove the first line: SDS011(byte pin_rx, byte pin_tx)).

And in setup add:

    my_sds.begin(0, 1);

This follows the library function of SDS011:

 void begin(uint8_t pin_rx, uint8_t pin_tx);

Other errors: because you forgot the ; in

    SDS011(byte pin_rx, byte pin_tx)

the next line:

    float p10,p25;

is misinterpreted, and p10 and p25 are not known. Therefore errors are shown while trying to use p10 and p25.

These errors will go when changing the begin code as described earlier.


body:
Your code should be like below; there are multiple syntax and semantic errors in the code you have posted;

Below is the edited and working code;

 #include <SDS011.h>

 float p10,p25;
 int error;

 SDS011 my_sds;

 void setup() {
   my_sds.begin(0, 1);
   Serial.begin(9600);
   while (!Serial) {
  ;
   }
 }

 void loop() {
   error = my_sds.read(&p25,&p10);
   if (! error) {
  Serial.println("P2.5: "+String(p25));
  Serial.println("P10:  "+String(p10));
   }
   delay(100);
 }


message:
Run Stepper with A4988 driver in highest resolution

I have a Bipolar Stepper Motor (12V, 350mA, 28oz-in NEMA-17) and would like to run it in the highest resolution (Sixteenth Step) with the A4988 Driver. According to multiple sources I read I need to "put 5V" to the MS 1,2,3 pins. What does this mean/How can I achieve this ?

Do I need to hook up the MS 1,2,3 to the digital pins of the Arduino and write Digital High. Or do I need to hook all of them to 5V together ? And should the code look like this ? Is this safe/good pratice ?

    int MS1Pin = 8;                 // Set MS Pins
    int MS2Pin = 9;
    int MS3Pin = 10;

    void setup()
    {
      pinMode(MS1Pin, OUTPUT);      // sets the digital pin as output
      pinMode(MS2Pin, OUTPUT);      // sets the digital pin as output
      pinMode(MS3Pin, OUTPUT);      // sets the digital pin as output
    }

    void loop()
    {
      digitalWrite(MS3Pin, HIGH);
      digitalWrite(MS2Pin, HIGH);
      digitalWrite(MS1Pin, HIGH);
    <<MY CODE here>>

    }
Sorry for these beginner questions, I just don't want to fry the Chip and this to work.

Thank you.

body:
You can drive the MS pins from the Arduino if you want, but there is no need.  You can just hook them all up to 5V.

Have you seen this page, there seems to be load of details that you might find relevant.
https://www.pololu.com/product/1182


message:
redefining delay and delaymicros as personal function

Is it possible to redefine delay and delaymicros function with #define ?
I want to use timer2 interrupt instead of these.

Something like this:

    #define delay(unisgned long ms) countMicros(uint16_t top, uint16_t storageVar)

    setup(){}

    loop(){
     delay();// function countMicros is called instead.
     }
    void countMicros(uint16_t top, uint16_t storageVar){
    //...}

body:
Not exactly like that. You will have to manage the different sets of
parameters, i.e. convert the incoming `ms` into the `top` and
`storageVar` that would be appropriate for calling `countMicros()`.
Maybe something like this:

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

    #define delay(ms) mydelay(ms)

    void mydelay(unisgned long ms) {
        uint16_t top = some expression;
        uint16_t storageVar = another expression;
        countMicros(top, storageVar);
    }

where both expressions are a function of `ms`.

If the expressions are really simple, you could even put the whole thing
inside a single macro, as in

    #define delay(ms) countMicros(some expression, another expression)


message:
Get a LED to fade out

I want to light an LED in a sketch and then have it fade out.
I tried to use analogWrite and have it decrease from a value of 255 to 0 using a for() loop, but I can't seem to get it to work.
Using digitalWrite I can turn it on and off but cant get it to fade out.
Can anyone help please.

    const int ledPin1 = 2;
    const int ledPin2 = 3;
    const int ledPin3 = 9;
    int j = 0;

    void setup() {
        pinMode(ledPin1, OUTPUT);
        pinMode(ledPin2, OUTPUT);
        pinMode(ledPin3, OUTPUT);
    }

    void loop() {
        j = 255;
        delay(1000);
        if (j >= 5);
        {
            analogWrite(ledPin3,j);
            delay(10);
            j = j - 5;
        }
        delay(1000);
    }

body:
Not all output pins are able to perform PWM ("AnalogWrite").

> On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

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

Note that the PWM-enabled ports are marked by a "~" on the board.

If you try analogWrite, e.g., on port 4, you'll get your observed switch behaviour.


body:
Problems noted in comments:

    void loop() {
        j = 255;             // Resets j EVERYTIME
        delay(1000);
        if (j >= 5);         // Semi-colon here makes this a null statement
        {
            analogWrite(ledPin3,j);  // j is always 255 (see line 1)
            delay(10);
            j = j - 5;       // No effect as j is reset in line 1
        }
        delay(1000);
    }

Here's a simple fix:

    int j = 255;   // Start at 255

    void loop() {
        analogWrite(ledPin3, j);   // Set the brightness
        delay(10);
        j -= 5;
        if (j <= 0) j = 255;       // Reset j?
    }


message:
Arduino core structure and timer usage

I needed to use TC1 for input capture, but also analogWrite() and an approximate 1 ms interrupt to poll the user interface (encoder, button).

The Arduino Nano's [ATmega328p][1] ([datasheet][2], beware: a lot of bit symbol typos) has three timers:

 1. TC0
 2. TC1
 3. TC2

It is not easy to find information on the "Arduino core" structure and it's use of peripherals. The [Arduino Reference][3] does not seem to refer to any information. Nor does [Arduino Hacking][4].

Some info can be found on

https://arduino-info.wikispaces.com/Timers-Arduino

but I am not sure it's up to date. For instance, I find disabling TC2 also disables the `analogWrite()` PWM.
Trying to use TC0 results in an error, as `TIMER0_OVF_vect` is already being used ("multiple definition of `__vector_16'").

How can I use the timers (and their interrupts) that are already used for the core?

  [1]: http://www.microchip.com/wwwproducts/en/ATmega328P
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf
  [3]: https://www.arduino.cc/en/Reference/HomePage
  [4]: https://www.arduino.cc/en/Hacking/HomePage

body:
"Reimplementing" the interrupt handlers to free Timer/Counter resources would require changes to the Arduino core firmware.
But there may be a workaround:

The source code shows how `init()` and `loop()` are used:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp

and the basic timer initialization is here:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L45

and `init()` [is there as well][1], which also configures all the other timers for *phase-correct PWM*...

`analogWrite()` is in https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_analog.c

I thought that at just 490/980 Hz it might use software-PWM, but in fact it selects the corresponding timer *output compare* pin (that also means the CPU can be powered down while the PWM still is being generated).

It does that via a runtime lookup in the board header's `digital_pin_to_timer_PGM`, e.g. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/standard/pins_arduino.h

which seems to be a (conditional) list of all pins.

So there is a limited, indirect choice on which timer is being used for PWM:
PD5 and PD6 are served by TC0, so using one of these as `analogWrite()` output pin frees TC2 for my purposes (~1 kHz polling).

Works for me!

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L241


body:
Here is a summary of all this. On an ATmega328P (Arduino Uno, Nano,
etc.), the Arduino core library uses the timers as follows:

* Timer 0
  * timing and delay functions, using the `TIMER0_OVF` interrupt
  * “fast” PWM at 980 Hz on pins 5 and 6 (PD5 and PD6)
* Timer 1
  * “phase-correct” PWM at 490 Hz on pins 9 and 10 (PB1 and PB2)
* Timer 2
  * “phase-correct” PWM at 490 Hz on pins 3 and 11 (PD3 and PB3)

All three timers have their prescalers set to 64. `TIMER0_OVF` is the
only timer interrupt enabled by default.

Note that libraries can use the timers for their own purposes. `Servo`
for instance uses Timer 1 for doing interrupt-based PWM.


message:
String to unsigned long conversion

I'm trying to use `strtoul()` to convert an Arduino **S**tring to an unsigned long *(like the return of `millis();`)* using the following code snippet:

    unsigned long foo (String time)
    {
      unsigned long mili;
      char Tim[9]="";
      uint16_t timsize = time.length()+1;
      char TIM[timsize];
      time.toCharArray(TIM,timsize);
      mili=strtoul(TIM,timsize,10);
      return mili;
    }

The code seems to work. However, I'm getting the following warning:
>invalid conversion from 'uint16_t {aka unsigned int}' to 'char**' [-fpermissive] `mili=strtoul(TIM,timsize,10);`

----------

My question is twofold:

 1. Is there a better way to convert a **S**tring to unsigned long without first converting to a C string?

 2. If not, how can I eliminate this error?

body:
Arduino `String` class provides method `c_str()`. So you don't have to convert it to C string, as it's already stored as a C string internally.

And as mentioned in comments, the second parameter of `strtoul` is:

> **endptr**

    Reference to an object of type `char*`, whose value is set by the function to the next character in str after the numerical value.

    This parameter can also be a null pointer, in which case it is not used.

 Basically you can reduce whole foo to the:  `return strtoul(time.c_str(), NULL, 10);`


message:
Arduino Uno simple LED example with pointers

I am new to Arduino and I have recently started off by trying to turn on an LED connected to pin 13 on my Arduino Uno using pointers.

I opted to do this with pointers because this would give me a better understanding on what really goes behind when I use predefined Arduino functions.

My simple code looks like this,

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

    uint8_t *data = (uint8_t *) 0x05; //PortB data register ptr (Since pin 13 is PB6)
    uint8_t *dir = (uint8_t *) 0x04;  //PortB dir register ptr (Since pin 13 is PB6)

    void setup() {
        *dir = 0x40;  //PB6 direction set to O/P
        *data = 0x40; //PB6 data set to 1 to turn on the LED
    }

    void loop() {
      *data = 0x40;
    }

I tried the same program using   pinMode(13, OUTPUT) and digitalWrite(13, LOW) functions and it works fine. But I do not understand what could be wrong with my pointers. If you find anything wrong, kindly let me know.

body:
Port definitions in AVR-Libc are done via black magic. Don't attempt to replicate them as a beginner. That being said...

"How do I pass an IO port as a parameter to a function?"

    volatile uint8_t *data = &PORTB;
    volatile uint8_t *dir = &DDRB;


body:
You made two small mistakes:

1. The addresses of the I/O registers are `0x24` for `DDRB` and `0x25`
   for `PORTB`. The numbers you used are I/O port numbers, but since
   pointers are supposed to point to memory, you have to use the
   memory-mapped addresses instead.
2. Pin 13 is `PB5`, not `PB6`.

With these two mistakes fixed, your code works as expected. There are
still two issues however:

1. Under some circumstances, the compiler can optimize away some writes
   to these registers. You have to qualify the pointers as “pointer to
   `volatile` data” in order to avoid this. Even if your simple example
   does not show this problem, it is always safer to use the qualifier.
2. The compiler generates inefficient code. Not as inefficient as
   `digitalWrite()`, but still... It knows how to optimize, but it is
   prevented to do so by the fact that your pointers are modifiable. You
   should qualify them as `const` if you want to benefit from compiler
   optimizations.

With those fixes, your pointer definitions would look like:

    volatile uint8_t * const data = (uint8_t *) 0x25;
    volatile uint8_t * const dir  = (uint8_t *) 0x24;

and access to them gets compiled into efficient `in` ans `out` assembly
instructions.

That being said, if you want to do direct port access, I would recommend
doing it the avr-libc way:

    void setup() {
        DDRB  = _BV(PB5);
        PORTB = _BV(PB5);
    }

    void loop() {
        PORTB = _BV(PB5);
    }

The way the AVR-libc defines the I/O registers is roughly equivalent to

    #define PORTB (* (volatile uint8_t *) 0x25)


message:
How to have code/sketch that's easily toggleable to work on different nodes

i have a question about best practice to achieve what i want to do. I would like to have a sketch setup, and then to be able to deploy to different devices of the same type, but each device/node will have a few different parameters, like ip address and mqtt topic etc,

What would be the quickest way to be able to upload new changes to all of my nodes without having to track my changes and update each seperate sketch for each node?

I was thinking about using some IFDEF statements if i can figure out how to? would that be the best way to go or is there something better?

Thx in advance

body:
You can put the per-node parameters in a external EEPROM and load them during `setup()`. For example the IP address is the first 16 bytes of the eeprom (IPv6), the next bytes would the the topic, etc..

That way every node has exactly the same sketch and the customization is in the eeprom that you could put in a socket and possibly have a separate programmer for them.

EEPROMs with I2C interface are easy enough to get and can store 64kB. Which should be more than enough for most things.


message:
Using an ESP8266 with an Arduino Uno - can't get AT command to work

I am trying to connect an ESP8266 to my Arduino Uno.

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

Connections:

    RX -> RX
    TX -> TX
    CH_PD -> 3.3v (Arduino 5v using voltage regulator)
    VCC -> 3.3v
    GND -> GND

I am running the RX and TX pins through a logic converter, dropping those down to 3.3v. Also, I have read that normally RX goes to TX and vice versa, but since I am trying to communicate with the chip using my computer (not the arduino) it needs to be the other way around.

I can't get the `AT` command to work on any baud rate. I was paying attention mostly to 9600, 115200, and 57600...I checked some others but it seemed like from reading these are the most common.

I used a multimeter to check the voltage of the RX/TX pins and after the logic converter my meter says it is outputting 3.2 volts (is this two low for serial to work?) Is their some +/- in the reading and it is actually 3.3v?

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

How do I go about troubleshooting this? Is it possible the AT firmware isn't loaded onto my chip? (I purchased it new, and recently).

**UPDATE:**

I'm reading about my logic level converter [here][3], and I'm wondering if I have it setup right. My converter is labeled with HV -> HV4 and LV -> LV4 (you can see in the below picture). I'm wondering about where it says:

`The middle section of the board is where the reference supply for your high and low voltages should go. Supplying voltage to all four of these pins is required. If you’re converting 3.3V to 5V (and vice-versa), for example, you’d run 5V into the “HV” side, and 3.3V into the “LV” input. Make sure each is grounded too!`

So I need to provide power ("reference" power)? Some diagrams I have seen do this but I wasn't sure why:

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

**UPDATE**

I provided the reference supply and it up'd my voltage reading from 3.2 to 3.27 (I can assume it has enough voltage now?). I still can't connect with `AT` - on one of the baud rates I was getting stuff like `!?` as output.

**UPDATE**

I changed what pins were being used by RX/TX on my logic level converter, and now when I type `AT` on baud 115200, it outputs `AT`. Below is what it looks like for this configuration:

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

Do the soldered connections look good on the logic level converter?

  [1]: https://i.stack.imgur.com/4502z.jpg
  [2]: https://i.stack.imgur.com/hSDyJ.jpg
  [3]: https://learn.sparkfun.com/tutorials/using-the-logic-level-converter
  [4]: https://i.stack.imgur.com/xbuX7.png
  [5]: https://i.stack.imgur.com/iVOEt.jpg

body: After writing such a long question, hopefully this is useful to someone else: After changing the logic converter channels (not sure why the first two weren't working) I was receiving `AT` as output - the only thing I needed to do after that was change `No line ending` to `Both NL & CR` and I am receiving `AT OK` now.


body:
Try loading the ESP8266-01/12F firmware once more from the Espressif and see if it's working correctly. Hope you know how to change to firmware/programing mode?

(GPIO 0->ground)->rest->burn program->GPIO0->high->power reset)