body:
I am sorry for posting this question for the nth time but I am still not able to find a solution for this error.

I am trying to upload the WiFiScan(Arduino IDE example program)program code to ESP8266 using Arduino Mega 2560. I followed the procedure given [here](https://diyhacking.com/esp8266-tutorial/). And I tried uploading it with "Generic ESP8266 Module" and "Adafruit HUZZAH ESP8266" selected as the Board. But I am still getting the following error.

    trying to connect
      espcomm_send_command: sending command header
      espcomm_send_command: sending command payload
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed

Edited to add:
[![enter image description here][1]][1]

**Connections-**

**ESP8266 - Arduino Mega2560**

Tx - Tx1(Pin 18)

Rx - Rx1(Pin 19)

Gnd - Gnd

Vcc - 3.3V (Directly from Arduino's 3.3V pin)

CH_PD - 3.3V (Directly from Arduino's 3.3V pin)

GPIO0 - Push button K2 (refer photo)

RST - Push button K1

While pressing the K2 button(Flash button - GPIO0), I clicked the K1 button(Reset button - RST) and then released K2. According to the document, this should bring the ESP8266 to flash mode. Now when I upload the code, it throws the above error.

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

title: Error while uploading code to ESP8266 through Arduino Mega 2560

Answers: 1

body:
After googling for several hours, I was able to figure out the reason. Thanks to this [link][1]. Transferring data to ESP8266 with Arduino acting as USB to Serial converter did not work. Using a USB to TTL converter, and following this [link][2] you can easily transfer data to ESP8266.

  [1]: https://github.com/esp8266/Arduino/issues/1207
  [2]: https://diyhacking.com/esp8266-tutorial/


body:
I need some information for the TFT screen 2.8 and arduino mega.
The screen works very well and displays the data.
The small problem I encounter is for the text display, the page is reloading every second and this makes a small black screen every second.
I would like to know if it was possible to reload only one part of the screen display?

See in video
https://youtu.be/vxSa6xkH0vU

My `loop()`

    void loop(void) {
       tft.fillScreen(BLACK);
      unsigned long start = micros();
      tft.setCursor(0, 0);
      tft.setRotation(3);
      dt = clock.getDateTime();
      clock.forceConversion();

      // Go
      tft.println();
      tft.setTextColor(GREEN);
      tft.setTextSize(5);
      tft.println("Info");
      tft.println();
      tft.setTextSize(2);
      tft.println(clock.dateFormat("d-m-Y H:i:s", dt));
      tft.println();
      tft.setTextSize(2);
      tft.println("Temperature: ");
      tft.println(clock.readTemperature());

      delay(1000);
    }

title: Reload only one variable in loop()

Answers: 1

body:
You can use [`tft.rect(x,y,width,height)`][1] to clear only a portion of the screen. Make sure to set `tft.fill` before calling it.

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


body:
Hi dears I'm trying to do project to control app base gsm control by arduino mega 2560 gsm module SIM900A

To send SMS to open Led than reply SMS to give as the status I mean send SMS then I received SMS from GSM module  by this code same time work but same time not work also same time send SMS1111 received SMS2222 status.
I hope it is clear.

    #include <SoftwareSerial.h>
    #include <string.h>
    #include "SIM900.h"
    #include <TinyGPS.h>
    #include "sms.h"
    SoftwareSerial GSMSerial(12, 13);
    byte buffer[128];
    int count = 0;
    const int Led4 = 43;
    const int Led1 = 44;
    const int Led2 = 45;
    const int Led3 = 50;
    void SIM900power()
    {
    }
    void setup() {
        pinMode(Led1, OUTPUT);
      pinMode(Led2, OUTPUT);
      pinMode(Led3, OUTPUT);
      pinMode(Led4, OUTPUT);
      GSMSerial.begin(19200); // the SIM900 baud rate
      Serial.begin(9600); // the Serial port of Arduino baud rate.
      Sim900_Inti();
    }
    void loop() {
      GSMSerial.listen();
      if (GSMSerial.available()) // If date is comming from from GSM shield)
      {
        while (GSMSerial.available()) // reading data into char array
        {
          buffer[count++] = GSMSerial.read(); // writing data into array
          if (count == 128)break;
        }
        Serial.write(buffer, count); // if no data transmission ends, write         buffer to hardware serial port
    Cmd_Read_Act(); //Read the 'COMMAND' sent to SIM900 through SMS
    clearBufferArray(); // call clearBufferArray function to clear the storaged data from the array
    count = 0; // set counter of while loop to zero
      }
      if (Serial.available()) // if data is available on hardwareserial port ==>     data is comming from PC or notebook
        GSMSerial.println(Serial.read()); // write it to the GPRS shield
    }
    void clearBufferArray() // function to clear buffer array
    {
      delay(1000);
      for (int i = 0; i < count; i++)
      {
        buffer[i] = NULL; // clear all index of array with command NULL
        delay(100);
      }
      for (int n = 0; n < count; n++)
      {
        buffer[n] = NULL; // clear all index of array with command NULL
        delay(100);
      }
      for (int m = 0; m < count; m++)
      {
        buffer[m] = NULL; // clear all index of array with command NULL
        delay(100);
      }
      for (int p = 0; p < count; p++)
      {
        buffer[p] = NULL; // clear all index of array with command NULL
        delay(100);
      }
    }
    void Sim900_Inti(void)
        {
         GSMSerial.println("AT+CMGF=1"); // Set GSM shield to sms mode
      Serial.println("AT+CMGF=1");
      delay(500);
      GSMSerial.println("AT+CNMI=2,2");
      Serial.println("AT CMGF=1");
      delay(500);
    }
    void Cmd_Read_Act(void) //Function reads the SMS sent to SIM900 shield.
    {
      char buffer_i[128];
      for (int i = 0; i < count; i++)
      {
        buffer_i[i] = char(buffer[i]);
      }
      if (strstr(buffer_i, "1111")) //Comparing password entered with password     stored in program
      {
              digitalWrite(Led1, HIGH);
       SMS_1111();
      }
      char buffer_n[128];
      for (int n = 0; n < count; n++)
      {
        buffer_n[n] = char(buffer[n]);
      }

      if (strstr(buffer_n, "2222")) //Comparing password entered with password     stored in program
      {
              digitalWrite(Led2, HIGH);
       SMS_2222();
      }
          char buffer_m[128];
      for (int m = 0; m < count; m++)
      {
        buffer[m] = char(buffer[m]);
      }
      if (strstr(buffer_m, "3333")) //Comparing password entered with password     stored in program
      {
       digitalWrite(Led3, HIGH);
       SMS_3333();
      }
      char buffer_p[128];
      for (int p = 0; p < count; p++)
      {
        buffer[p] = char(buffer[p]);
      }
      if (strstr(buffer_p, "4444")) //Comparing password entered with password stored in program
          {
        digitalWrite(Led4, HIGH);

       SMS_4444();
      }
    }
      void SMS_1111() // complet liter Replay SMS TO Know Led1 Is ON
     {
     }
     void SMS_2222()// complet liter
    {
    }
    void SMS_3333()// complet liter
    {
    }
    void SMS_4444()// complet liter
    {
    }>

title: Home devices control system using gsm and arduino mega2560

Answers: 1

body:
For the `3333` and `4444` you are doing

    buffer[m] = char(buffer[m]);

and

    buffer[p] = char(buffer[p]);

which does nothing.

You probably meant

    buffer_m[m] = char(buffer[m]);

and

    buffer_p[p] = char(buffer[p]);


body:
Using `WiFi.BSSID` and `WiFi.BSSIDstr` gives me some weird mac address.

the code is:

    #include "ESP8266WiFi.h"
    #include "ESP8266WiFiScan.h"

    void setup() {
    Serial.begin(115200);
    //WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);
    Serial.println("Setup done");
    Serial.println(WiFi.macAddress());
    }

    void loop() {
       int n=WiFi.scanNetworks();
       Serial.println(n);
       for (int network = 0; network < n; network++){
          Serial.println(WiFi.SSID(network));
          Serial.println(WiFi.RSSI(network));
          uint8_t* mac=WiFi.BSSID(n);
          char APmac[13];
          APmac[0]=0;
          for (int i=0; i<6;i++) {
            char buffer[3];
            sprintf(buffer, "x", mac[i]);
            strncpy((char *)(APmac+(i*2)), buffer, 3);
            Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
          }
          Serial.println(APmac);
          Serial.println(WiFi.BSSIDstr(n));

      }
      Serial.println();
      Serial.println();
      delay(10000);
    }

The current output is 6D:98:C9:00:00:00 which is completely off. It duplicates this output for other APs too. Is this a hardware problem? I've seen other people using the same codes and it works for them. For reference `WiFi.SSID();` and `WiFi.RSSI();` both spits out correctly.

edit: I was testing both output to see which ever one was correct and unfortunately they're both wrong

title: ESP8266 Wemos D1 Retrieving Wrong AP Mac Address

Answers: 1

body:
This seems wrong, you are trying to get String to interpret a byte, but are passing in a pointer to a byte:

    String digit = String(*mac, HEX);

Try changing your example to:

    uint8_t* mac=WiFi.BSSID();              // Gather the byte array
    String APmac;
    for (int i=0; i<6;i++) {
       String digit = String(mac[i], HEX);  // String() should see an int, not a pointer to a byte, with the directive to print it in HEX format
       if (digit.length() <2)
         APmac += String("0")+digit;        // Corrected capitalization error
       else
         APmac +=digit;                     // Corrected capitalization error
       //mac++;                             // Not necessary
       Serial.print("["); Serial.print(i); Serial.print("]");
       Serial.println(mac[i], HEX);
    }
    Serial.println(APmac);                  // Print the constructed String
    Serial.println(WiFi.BSSIDstr());        // Print the pre-formatted string

Consider not using the String object, which may help condense the code a bit:

    uint8_t* mac=WiFi.BSSID();
    char APmac[13];
    APmac[0]=0;
    for (int i=0; i<6;i++) {
       char buffer[3];
       sprintf(buffer, "x", mac[i]);
       strncpy((char *)(APmac+(i*2)), buffer, 3);
       Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
    }
    Serial.println(APmac);
    Serial.println(WiFi.BSSIDstr());


body:
I am trying to use my HC05 so my Arduino can communicate with my Windows 10 PC. I have a program written using the Window API for Serial Communication but the problem is it looks like the Arduino/HC05 can only send or the API can only read one character at a time. It is the same with Arduino; I send an entire string with the API and the Arduino has to read/parse it character by character. I was wondering if there was a solution to this problem or if I will need to develop some sort of coding protocol (like space to separate messages) to send messages. (The other issue is that it will take an age to send long messages this way.)

Windows File Reading API
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364232(v=vs.85).aspx

Here is the PC side file.

    do {
  // check for data on port and display it on screen.
  ReadFile(file, buffer, sizeof(buffer), &read, NULL);
  int i;
  sscanf(buffer, "%d", &i);
  std::cout << i << std::endl;

  if (read) {
   //WriteFile(screen, buffer, read, &written, NULL);

   //When space seen, add the string to data
   if (buffer[0] == ' ') {
    int convertedDatum = std::stoi(datum, &sz);
    if (convertedDatum < 12) {
     //WriteFile(file, "S " , 2, &written, NULL);
     //WriteFile(screen, "S", read, &written, NULL);
    }
    else {
     //WriteFile(file, "G ", 2, &written, NULL);
     //WriteFile(screen, "G", read, &written, NULL);
    }
    data.push_back(convertedDatum);
    datum = "";

Arduino-side test code

    void loop() {

 while (true) {
  String sendValue = String(100);
  sendValue.toCharArray(buf, sizeof(buf));

  Serial1.write(buf);
  Serial1.write(' ');
  delay(4000);
 }
What I am seeing on the console on the PC which is represented by the **screen** variable when I debug is when I break at the line

    std::cout << i << std::endl;
1-Continue-0-Continue-0
or on the console

    1
    0
    0
    0
    0
    0
    ...

I am pretty sure that I have seen entire strings sent at once with the Android Bluetooth API so I am not sure exactly if the same can be done with Windows or if the Windows VC++ API's are incapable.

title: Reading/Writing Strings with Bluetooth Windows API

Answers: 1

body: Serial is only ever a character at a time. That is what serial is. If you want to impose some structure on top of that then it is up to you to define that structure.


body:
Question given in the title. I'm trying to dynamically allocate the size of an array on runtime on an arduino pro micro. I've tried realloc, malloc and the c++ variant delete and new without success. This is my current test code:

    int* test = 0;

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

    void loop() {
      Serial.println("test");
      if(test != 0){ //c++ delete and new attempt
        delete [] test;
      }
      test = new int[2];
      //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
      //test = (int*) malloc(2*sizeof(int));          //malloc attempt
      test[0] = 1;
      test[1] = 2;
      int answer = test[0] + test[1];
      Serial.println(" " + answer);
      Serial.print(" " + test[0]);
      Serial.println(" " + test[1]);
      Serial.println("test");
      delay(100000000000);
    }

All of my attempts result in either some garbage in the serial or in most cases:

    test

    test

Does anyone know what I'm doing wrong?

title: How to dynamically allocate arrays

Answers: 2

body:
`serial.println` doesn't work that way. Or more precisely `+` with string literal and an `int` does **not** create a concatenated string. Instead it treats the string literal as a `char*` and then does pointer arithmetic on it.

      Serial.print(" ");
      Serial.println(answer);
      Serial.print(" ");
      Serial.print(test[0]);
      Serial.print(" ");
      Serial.println(test[1]);
      Serial.println("test");
      delay(100000000000);

body:
This works:

    int* test = 0;

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

    void loop() {
      Serial.println("test");
      if(test != 0){ //c++ delete and new attempt
        delete [] test;
      }
      test = new int[2];
      //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
      //test = (int*) malloc(2*sizeof(int));          //malloc attempt
      test[0] = 1;
      test[1] = 2;
      int answer = test[0] + test[1];
      Serial.println(answer);
      Serial.print(test[0]);
      Serial.println(test[1]);
      Serial.println("test");
      delay(100000000000);
    }

In C/C++, you can't add/concatenate Strings and int.


body:
It's the first time I use an ESP8266 and I didn't manage to get a proper response in the Arduino serial monitor. I only see weird characters, when I move the 3.3V wire.

You can see the connections in the following picture:

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

The code I run is the following one:

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

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

    void loop()
    {
        String B= ".";
        if (BT1.available())
        {
            char c = BT1.read();
            Serial.print(c);
        }
        if (Serial.available())
        {
            char c = Serial.read();
            BT1.print(c);
        }
    }

Maybe it's something really stupid. I am a total beginner, so I appreciate any help.

EDIT: I think power supply is 3.3V[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/KwsMQ.jpg
  [2]: https://i.stack.imgur.com/OBmjx.jpg

SOLUTION: the problem was the power supply. I tried exactly the same using the 3.3V from the arduino instead of the power supply and it works perfectly!

title: ESP8266 not working properly

Answers: 2

body:
You may well have killed the ESP by supplying it 5v, you have to have a logic level shifter, as Juraj says.

Assuming it's not dead then your next problem is there have been posts about that hardware setup and SoftwareSerial doesn't work at high speed. I can't tell you what it is that doesn't work because turning the speed of the link cures the problem, try 9600 maximum.

[Edited to be less accusational, which was not the original intent]

**[Update]**

Please see the datasheet here:
https://www.mikrocontroller.net/attachment/231858/0A-ESP8266_Specifications_v4.pdf

The table in section 8.4.4 says that the maximum input voltage is 3.6V
Just after that it says all digital pins are "protected from over-voltage with a snap-back circuit". This snap back voltage is typically 6V.  So does that mean the GPIO are safe up to 6V?

(It might be that this datasheet has been superseded, I am unable to access the EspressIF site at the moment).

body:
**Step 1:** Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module. A voltage divider circuit is used to drop the Arduino 5V to ESP8266 3.3 V.

Step 2: Here is the schematic Diagram, in my code I used Digital pin 2 as a Tx and D3 as an RX. [![enter image description here][1]][1]

[Click Here for Necessary At Commands][2]

  [1]: https://i.stack.imgur.com/8A55m.jpg
  [2]: http://www.electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html


body:
I have been looking at this for hours and can't figure it out... Take the following code I ran on an Arduino Mega:

    #define MINUTES 0
    #define SECONDS 1
    #define MILLIS  2
    #define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

    unsigned long calculate_ms(int , int , int );

    int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

    void setup() {
      Serial.begin(115200);
      delay(1000);
      Serial.println("Values of selected_turn_delay:");
      Serial.print("minutes: ");
      Serial.println(selected_turn_delay[MINUTES]);
      Serial.print("seconds: ");
      Serial.println(selected_turn_delay[SECONDS]);
      Serial.print("milliseconds: ");
      Serial.println(selected_turn_delay[MILLIS]);

      unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result2 = calculate_ms(0,45,0);
      unsigned long result3 = calculate_ms(0,30,0);
      unsigned long result4 = calculate_ms(0,31,0);
      unsigned long result5 = calculate_ms(0,32,0);
      unsigned long result6 = calculate_ms(0,33,0);
      unsigned long result7 = calculate_ms(0,34,0);
    }

    void loop() {
    }

    unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
      Serial.println("------------");
      Serial.println("In calculate_ms");
      Serial.println("------------");
      unsigned long calculated_total_milliseconds = 0;
      unsigned long minute_to_seconds = 0;
      unsigned long seconds_to_ms = 0;

      Serial.println("Input:");
      Serial.print("minutes: ");
      Serial.println(minutes);
      Serial.print("seconds: ");
      Serial.println(seconds);
      Serial.print("milliseconds: ");
      Serial.println(milliseconds);

      calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

      Serial.print("Calculates ms:");
      Serial.println(calculated_total_milliseconds);
      return(calculated_total_milliseconds);
    }

It gives me the following results:

    Values of selected_turn_delay:
    minutes: 0
    seconds: 45
    milliseconds: 0
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:4294946760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:4294946760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:4294946760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 30
    milliseconds: 0
    Calculates ms:30000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 31
    milliseconds: 0
    Calculates ms:31000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 32
    milliseconds: 0
    Calculates ms:32000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 33
    milliseconds: 0
    Calculates ms:4294934760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 34
    milliseconds: 0
    Calculates ms:4294935760

What am I missing why is the calculation for values above 32s out of wack ?

Tried the same code adapted for gcc:

    #include <stdio.h>

    #define MINUTES 0
    #define SECONDS 1
    #define MILLIS  2
    #define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

    unsigned long calculate_ms(int , int , int );

    int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

    int main(void) {
      printf("Values of selected_turn_delay:\n");
      printf("minutes: ");
      printf("%d\n",selected_turn_delay[MINUTES]);
      printf("seconds: ");
      printf("%d\n",selected_turn_delay[SECONDS]);
      printf("milliseconds: ");
      printf("%d\n",selected_turn_delay[MILLIS]);

      unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result2 = calculate_ms(0,45,0);
      unsigned long result3 = calculate_ms(0,30,0);
      unsigned long result4 = calculate_ms(0,31,0);
      unsigned long result5 = calculate_ms(0,32,0);
      unsigned long result6 = calculate_ms(0,33,0);
      unsigned long result7 = calculate_ms(0,34,0);
    }

    unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
      printf("------------\n");
      printf("In calculate_ms\n");
      printf("------------\n");
      unsigned long calculated_total_milliseconds = 0;
      unsigned long minute_to_seconds = 0;
      unsigned long seconds_to_ms = 0;

      printf("Input:\n");
      printf("minutes: ");
      printf("%d\n",minutes);
      printf("seconds: ");
      printf("%d\n",seconds);
      printf("milliseconds: ");
      printf("%d\n",milliseconds);

      calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

      printf("Calculates ms:");
      printf("%lu\n",calculated_total_milliseconds);
      return(calculated_total_milliseconds);
    }

And it works great:

    Values of selected_turn_delay:
    minutes: 0
    seconds: 45
    milliseconds: 0
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 30
    milliseconds: 0
    Calculates ms:30000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 31
    milliseconds: 0
    Calculates ms:31000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 32
    milliseconds: 0
    Calculates ms:32000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 33
    milliseconds: 0
    Calculates ms:33000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 34
    milliseconds: 0
    Calculates ms:34000

It has to be something obvious, but I can't find it...

title: Unsigned long overflow? Or something else?

Answers: 1

body:
Ok well, 'before bed illumination'...

Changing:

    calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

for

    calculated_total_milliseconds = (milliseconds + (seconds * 1000UL) + ((minutes * 60) * 1000UL));

Make it work:

    Values of selected_turn_delay:
    minutes: 0
    seconds: 45
    milliseconds: 0
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 30
    milliseconds: 0
    Calculates ms:30000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 31
    milliseconds: 0
    Calculates ms:31000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 32
    milliseconds: 0
    Calculates ms:32000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 33
    milliseconds: 0
    Calculates ms:33000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 34
    milliseconds: 0
    Calculates ms:34000


body:
This can be a silly question but I'm having a trouble with serial communication between arduino nano with other serial device. Please help me to handle it.

I'm currently doing a RF communication project using arduino nano and radio telemetry which is using serial communication. I tried to use SoftwareSerial but unfortunately, every pin is being used on arduino nano to control other extra devices. So I decided to have serial communication via usb port of arduino nano

Firstly, I directly connected rx and tx wire of RF device with D- and D+ of B type mini USB. but it did not work

Secondly, I tried to connect rx and tx wire with arduino nano via UART to USB bridge, cp2102 module. I soldered a female USB - male mini USB wire for this connection. but It did not work. the wiring that I build seems like the picture below. [![connection reference picture][1]][1]

Did I miss something? It doesn't work theoretically anyway?

Please help

Thank you in advance

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

title: using UART bridge module to have serial communication through usb port of arduino nano

Answers: 1

body:
This is not possible - USB is not an ambidextrous protocol, rather there are distinct Host and Device roles, and while a few chips can switch-hit between them, the USB interface chips commonly used on Nano-style boards are strictly device only, and therefore cannot communicate with another USB device such as a USB-serial adapter.  There may well even be a duplicate here somewhere of a similar question having been asked before.

What you should probably do is just use the ATmega UART that interfaces to the USB chip, to talk to your external device directly (or through level translation and possibly inversion if it requires that).  The transmit side is no problem, however you will need to give some though to the receive side, as only one thing (the USB chip, or your external device) can drive that ATmega pin at a time.  Many of the official Arduino designs have a resistor there, which lets an external driver dominate over the on-board USB serial chip, but your board may or may not have that - if not, you may need to modify it.

And of course such a scheme requires that you disconnect the external device when uploading a new sketch via bootloader.

Another option would be instead of a traditional USB-serial converter, to use some sort of embedded USB host and have that convert to serial - the Kinetis KL25Z chip does this well, as does its close cousin on the Teensy-LC.  But at that point, you might as well just replace the Arduino Nano with a better chip having more pins, or even the ATmega328PB which has a second hardware UART.


body:
I am trying to do fuse setting on ATmega328P-PU chips using an [avr programmer][1].

I was successfully able to do fuse setting on 3 ATmega328P-PU chips (which I bought from one of the sites - I forgot). So I bought three more [from Amazon][2].

When I execute `avrdude -c usbasp -p m328p` on the previous 3 chips, I got this response, and was able to do fuse setting.

>avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: AVR device initialized and ready to accept instructions

>Reading | ################################################## | 100% 0.00s

>avrdude: Device signature = 0x1e950f (probably m328p)

>avrdude: safemode: Fuses OK (E:FF, H:D9, L:E2)

>avrdude done.  Thank you.

But when I execute the same command on the 3 chips I recently bought, I am getting this.

    avrdude -c usbasp -p m328p

    avrdude: warning: cannot set sck period. please check for usbasp firmware update.
    avrdude: error: program enable: target doesn't answer. 1
    avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

    avrdude done.  Thank you.

I triple-checked the wiring and soldering area. They all look fine.

Is this because the 3 chips I recently bought have a bootloader?

The description for the chip that works is here.

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

  [1]: https://www.amazon.com/gp/product/B071P2LCC9/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.com/gp/product/B018ZR3F7O/ref=oh_aui_detailpage_o04_s01?ie=UTF8&psc=1
  [3]: https://i.stack.imgur.com/nqalo.png

title: Arduino - fuse setting problem on ATmega328P-PU

Answers: 1

body:
The chips configured with a bootloader would also have the fuses set for an external clock (the factory default is the on-chip oscillator). Without an external clock they won't work.

I have a [sketch that uploads files](http://www.gammon.com.au/uploader) that also can provide an external clock for this eventuality.

As mentioned on that page an 8 MHz clock is provided on pin D8 of the programming board, so you can connect to D8 on the Uno which you are running the sketch on to pin 9 on the actual Atmega328P chip.

Alternatively find a 16 MHz crystal or resonator and connect that between pins 9 and 10 of your Atmega328P which will provide the clock that it is expecting. If you use a crystal you should also run 22 pF capacitors between each leg and ground, like in this image:

[![Atmega328 with crystal][1]][1]

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


body:
I would like to know if this is possible.

I am using an ESP8266-ESP01, which only has 2 digital pins. I have a project that needs 3 digital pins so I have planned to use my Arduino, so I can use more digital pins. My plan is instead of plugging the sensor in the GPIO1 of the ESP8266, I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266 and be uploaded to an online cloud.

I can read the sensor data in the Arduino but I don't know how to transfer the data to the ESP8266 so the wifi module would just receive it and send it to the online cloud.

If anyone can help me to get some idea specifically on sending the data from Arduino to the ESP and receiving the data from the Arduino.

Thank you.

title: Use Arduino Uno digital pins instead of ESP8266

Answers: 3

body:
Use the ESP's two digital pins to talk to the Arduino using SoftwareSerial. Be careful however: your Arduino (possibly, probably) runs on 5V, the ESP on 3.3V. I have an Arduino clone that can be switched between 3.3V and 5V, which makes things easier.

After that all you need is to send the sensor readings to the ESP via SoftwareSerial.

body:
DDA's answer is perfectly correct.
Like he says you need to check the voltage and use a logic level shifter.

However looking at it from another angle there are a whole range of ESP that have an increasing number of digital pins.  You could look at using an ESP-5, or an ESP-12E, these have different forms and increasing number of digital pins.

You could also look at the Wemos range, I believe there is an UNO form board and there is the Wemos D1-Mini, which has 10 digital and 1 analog.

Running on two boards is usually more of an issue than running on one board, god help you if you have synchronisation issues!

body:
> I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266

Easy:

1. Program the Arduino as a master (I2C, or UART + interrupt) and the ESP as a slave. Connect the sensors to it. Once the data is read on the Arduino, it is sent to the ESP.

2. Put an I2C IO expander IC on the ESP and you don't have to deal with the Arduino at all.


body:
I am making a learning toy which kids can play with and learn basics of programming. But i am tired of keep replacing the AA batteries as they run out in few days. So i am thinking of using rechargeable battery. But i am very worried to use it considering it is kids toy and people says lipo and li ion battery can explode. There are dangers or over charge and heat etc.

**Is it safe to use them? Which one to use?**

I am using **Arduino pro mini** 3.3v and some times 5v.

I was planning to use: [XCSOURCE 5 pcs 1A 5V Micro USB TP4056 Lithium Battery Power Charger Board Module TE420][1]

I think some users have misunderstood the question and have voted this question to be closed. This questions is very much to deal with programming also apologies if i have not made it clear.

 - We can get the battery level in the code, but is there any way in code we can some how turn off the charging when the battery has been fully charged.

 - I am under impression (might be wrong, you can correct me), normal
   battery single AA cell dies after some time on heavy use (using dc motor etc). But
   rechargeable batteries are bigger with multiple cells in it they will
   last longer. So if i am running some code in a loop for long time
   will the battery get over heated will it be a problem.

  [1]: https://www.amazon.co.uk/XCSOURCE-Lithium-Battery-Charger-TE420/dp/B01DRT4PWY/ref=sr_1_1?s=electronics&ie=UTF8&qid=1505294735&sr=1-1&keywords=XCSOURCE 5 pcs 1A 5V Micro USB TP4056 Lithium Battery Power Charger Board Module TE420

title: Arduino for kids toy with Battery (safe), Can Arduino overheat the Battery with long running code

Answers: 1

body:
Probably the easiest/cheapest and safest option is to buy a original USB Power Bank and there you have it. Power banks for cellphones/tablets have overvoltage/overcharge/undercharge protection on them and they are also completely sealed, so it should be perfectly safe to handle one of those to your kids (Of couse not some cheap chinese crap).

They can then charge the power bank over USB on any PC or Wall charger and then use it for hours/days.

If I'm allowed to give you a tip, you could eventually pick one of these [here][1], they are pretty good in my opinion.
[![TP-Link Power Bank][2]][2]
Of course there are a ton of others around, so you can just pick one which fit your needs.

On your case you just cut a USB cable and plug the ends on the Pro Mini. If a short is detected, Power banks often just shut off and only turn on when they are charged again (You might try this first). If you use a 3.3V Pro Mini, just put a voltage limiter between it. You might also write "3.3V" on the voltage limitor and "3.3V" on the 3.3V version of the Arduino and teach your kids that if the Arduino has "3.3V" written on it, they should put that "3.3V" voltage limitor before it (or just not use 3.3V variants for ease of use).

  [1]: https://www.google.com.br/search?q=TP Link 10400mah Power Bank
  [2]: https://i.stack.imgur.com/qX7o8.jpg


body:
I have used below program for ESP8266 as ISP to upload a program to an ATmega16.

**ISP program uploaded in ESP8266**

    #include <SPI.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266mDNS.h>
    #include <ESP8266AVRISP.h>

    const uint8_t reset_pin = 5;
    const uint16_t port = 328;

    ESP8266AVRISP avrprog(port, reset_pin);

    void setup() {
        Serial.begin(9600);//115200
        Serial.println("");
        Serial.println("Arduino AVR-ISP over TCP");
        avrprog.setReset(false); // let the AVR run

        // listen for avrdudes
        avrprog.begin();
    }

    void loop() {
        static AVRISPState_t last_state = AVRISP_STATE_IDLE;
        AVRISPState_t new_state = avrprog.update();
        if (last_state != new_state) {
            switch (new_state) {
                case AVRISP_STATE_IDLE: {
                    Serial.printf("[AVRISP] now idle\r\n");
                    Serial.println("idle...");
                    // Use the SPI bus for other purposes
                    break;
                }
                case AVRISP_STATE_PENDING: {
                    Serial.printf("[AVRISP] connection pending\r\n");
                    Serial.println("pending...");
                    // Clean up your other purposes and prepare for programming mode
                    break;
                }
                case AVRISP_STATE_ACTIVE: {
                    Serial.printf("[AVRISP] programming mode\r\n");
                    Serial.println("Active...");
                    // Stand by for completion
                    break;
                }
            }
            last_state = new_state;
        }else{
          Serial.println("newstate not equal to old");
        }
        // Serve the client
        if (last_state != AVRISP_STATE_IDLE) {
            avrprog.serve();
            Serial.println("serve..");
        }
    }

Then I have changed the board to ATmega16 and used programmer as `AVR ISP` and fetched/written below simple blink program to upload in ATmega16.

    void setup() {
      // initialize digital pin 13 as an output.
      pinMode(1, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);              // wait for a second
      Serial.println("light on");
      digitalWrite(1, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);              // wait for a second
      Serial.println("light off...");
    }

Tried uploading blink program to ATmega16 using ESP8266 as ISP by **Sketch =>Upload Using Programmer**. This resulted to compilation followed by uploading status in Arduino IDE for longer period. I didn't get any response after 10 mins of time. Then i have tried opening Serial Monitor which shows `newstate not equal to old`.

I am not sure what went wrong in my coding? How can I debug this issue ?

title: ESP8266 as ISP program for ATMega16

Answers: 1

body:
### 1. Uploading the sketch to your ESP8266
- Tools > Board > select the appropriate ESP8266 board
- File > Examples > ESP8266AVRISP > Arduino_Wifi_AVRISP
- Change lines 7 and 8 to match the SSID and password of your WiFi router
- Sketch > Upload
- After the upload completes unplug the ESP8266 from your computer.

### 2. Generating the .hex file and the upload command
- Open the sketch you want to upload to your ATmega16
- Tools > Board > ATmega16
- File > Preferences > Show verbose output during: > upload (check)
- Sketch > Upload
- The sketch will compile and then the upload will fail. This is the expected behavior. The goal of this process is to generate the .hex file that will be uploaded and the correct upload command.
- Scroll the black console window at the bottom of the Arduino IDE window up until you see a line that looks something like:

>

    E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM54 -b115200 -D -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

### 3. Connecting the ESP8266 to the ATmega16
Connect the ESP8266 to your ATmega16 board as follows:

    +----------+-----------+
    | ESP8266  | ATmega16  |
    +----------+-----------+
    | GPIO12   | MISO      |
    | GPIO13   | MOSI      |
    | GPIO14   | SCK       |
    | GPIO5    | RESET     |
    +----------+-----------+

You also need to power the ATmega16. It is recommended to use 3.3 V since this is what the ESP8266 is running at. Make sure the ground of the ESP8266 is connected to the ground of the ATmega16.

### 4. Starting the ESP8266AVRISP
- Plug the ESP8266's USB cable back in to your computer
- Tools > Serial Monitor
- Select 115200 from the baud rate menu in the bottom right corner of Serial Monitor
- You should see something like

>IP address: 192.168.0.100
Use your avrdude: avrdude -c arduino -p <device> -P net:192.168.0.100:3000 -t # or -U ...

### 5. Uploading via ESP8266AVRISP

- The second line you saw in the Serial Monitor in step 4 is the sketch's attempt to give you the AVRDUDE command you need to run to upload to your ATmega16 via the ESP8266AVRISP. Unfortunately they got a bit vague at the end. Apparently they are trying to steer you towards using AVRDUDE in [terminal mode](http://www.nongnu.org/avrdude/user-manual/avrdude_7.html) via the `-t` option but also mentioning that `-U` might be preferred. I recommend the latter since the Arduino IDE has helpfully generated the `-U` command for you already.
- Since you need to run a custom AVRDUDE command to upload to your ATmega16 over the network you will not be able to do the upload via the Arduino IDE. Start the command line on your computer.
- Now you need to merge the upload command you generated when you did the intentionally failed upload to the ATmega16 in step 2 with the command that was printed to Serial Monitor in step 4. In my examples, this merged command would be:

>

    E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -c arduino -p atmega16 -P net:192.168.0.100:3000 -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

- Your command will be similar to mine but the path to avrdude, avrdude.conf, the IP address, port, and path to the .hex file will be different. Enter your merged AVRDUDE command at the command line.
- The upload should now proceed successfully.

### Comments
The above is quite a complex process. Although it will be significantly easier with subsequent uploads, it will likely still not be as easy as an upload via the Arduino IDE. I would not recommend regularly using the ESP8266 as an AVR ISP simply because it's what you have on hand. Instead I would strongly recommend you to just buy a cheap (~$3 USD with free shipping from China) 6 pin USBasp from eBay.

The primary benefit of using the ESP8266 for this application is that it can be done over the WiFi network rather than the traditional USB connection but it's questionable how often that will truly be useful.


body:
I'm currently working on a robot using an Arduino and I'd like to control robot's head like this:

Imagine that it is on your desk and it can turn it's head through a range of 150 degrees like a human can do. So if I tap the desk in the the middle position, relative to his head rotation (in front of the robot), it should rotate his head by 75 degrees if he was looking at the left or right.

Likewise, I want to locate the desk tap or another sound source and make his head turn to that direction.

So in order to do that I have a solution, but I'm not confident enough to use it because I don't know whether is will give accurate results. This is what I thought:

I'll place two sound modules on the left and right sides of the robot. When a sound comes, I'll measure which microphone detects the higher sound level, and calculate an approximate angle to rotate the robot's head accordingly.

However, since I'm a newbie to Arduino, I've no real sense of whether that will work as I intend. Do people think this is a good method? If not, how can I improve it?

Also if you can, please suggest some good, Arduino compatible sound modules for this project. Thank you.

title: Rotate Robot head according to Sound level

Answers: 1

body:
A couple of years ago, I completed a MOOC on FUN called [Binaural Hearing for Robots][1] (it doesn't seem to have run since, but it may be worth keeping an eye on it to see if they open registration again. At least some of the resources seem to be archived [here][2]). Interestingly, localising sound turns out to be easier with three microphones than with two.

You scan the three inputs in sequence, and when the sound is directed to record the time-difference between the three sensors. The technique you're looking at to localise the source is called [trilateration][3].

Once you have a direction relative to the robot head, you can use a simple servo to turn the robot head to that direction.

I did play around with this a little bit, using three KY-038 microphone modules like this that I picked up cheap on eBay:

![microphone][4]

Connect them to your Arduino something like this:

![sound-localisation][5]

<hr>

I can't find my code (it was pretty untidy anyway since I was just playing around while I was working on the course), but a lot of Arduino sound-localisation projects have been published online with examples easy to find on [Instructables][6], [Hackaday][7], and many [other sites][8].

  [1]: https://www.fun-mooc.fr/courses/inria/41004/session01/about
  [2]: https://www.canal-u.tv/producteurs/inria/cours_en_ligne/binaural_hearing_for_robots
  [3]: https://en.wikipedia.org/wiki/Trilateration
  [4]: https://i.stack.imgur.com/RSM2f.jpg
  [5]: https://i.stack.imgur.com/TRrya.png
  [6]: http://www.instructables.com/id/Sound-Locator/
  [7]: https://hackaday.com/2011/05/23/sound-localization-and-a-treaded-rover/
  [8]: http://ruralhacker.blogspot.co.uk/p/micloc.html


body:
I have a very basic programming knowledge, but the thing I want to achieve is to alternate between switching 2 relays with a button or a RPi input pulse.

So something like this:

1. Press the button
2. Switch relay 1 on and off (1 second delay)
3. Press the button
4. Switch relay 2 on and off
5. Press the button
6. Switch relay 1 on and off (1 second delay)
7. Press the button
8. Switch relay 2 on and off
9. Press the button
10. Switch relay 1 on and off (1 second delay)
11. Press the button
12. Switch relay 2 on and off
13. etc.

Here's my code, I thought if I'd just put the second relay after the first `else` everything would work. But I'm missing some basic knowledge to figure this out.

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

    const int ledPin = 2;
    const int ledPinA = 3;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(ledPinA, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(1);
      if (sensorValue > 500) {
        digitalWrite(ledPin, HIGH);
      } else {
        digitalWrite(ledPin, LOW);
      }
      if (sensorValue > 500) {
        digitalWrite(ledPinA, HIGH);
      } else {
        digitalWrite(ledPinA, LOW);
      }
    }

I'm thinking I should use `while`.

title: Alternate between 2 relays with one button

Answers: 2

body:
The way you have it, both `if` blocks will be evaluated each time you call to `loop()`. Instead, you need to create a variable that remains "alive" in between each call to `loop()` to keep track of which relay you want to activate:

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

    const int ledPin = 2;
    const int ledPinA = 3;
    int active_relay = 2;   // State variable for current relay pin

    void setup() {
        pinMode(ledPin, OUTPUT);
        pinMode(ledPinA, OUTPUT);
        Serial.begin(9600);
    }

    void loop() {
          int sensorValue = analogRead(A0);

          Serial.println(sensorValue);

          delay(1);    // This delays for 1ms, not 1s ??

          if (sensorValue > 500) {   // Pulse received
              digitalWrite(active_relay, HIGH);  // Relay on
              delay(1000);                       // Wait 1 second
              digitalWrite(active_relay, LOW);   // Relay off

              // Update variable for next call to loop
              if (active_relay == ledPin) {
                  active_relay = ledPinA;      // Swap
              }
              else {
                  active_relay = ledPin;       // Swap
              }
          }
          // Remove 2nd if block
    }

body:
> So something like this:

easy:

1. increment a counter based on button presses;

2. run a state machine on that counter to decide on relay actions.

the state machine can be a simple switch / case statement.


body:
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...

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

Answers: 1

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);


body:
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.

title: OLED on Hardware SPI, on DUE

Answers: 1

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


body:
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/

title: BMP 280 exact Altimeter readings

Answers: 1

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.


body:
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

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

Answers: 1

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)


body:
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

title: Power Measurement

Answers: 2

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 -->


body:
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/

title: Unable to connect ESP8266 to WPA2+Enterprise network

Answers: 1

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.


body:
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.

title: How to do with fzz file

Answers: 2

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


body:
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?

title: Time Library Adjust Default on Windows

Answers: 1

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.


body:
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

title: Convert string into char array in Arduino?

Answers: 3

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;
    }


body:
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?

title: Odd Serial behavior with Uno

Answers: 1

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.


body:
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

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

Answers: 2

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);
        }
    }


body:
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

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

Answers: 2

body: How about `pinMode (analogOutPin, OUTPUT);` ?

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


body:
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);
        }
    }

title: Receive an array of characters using SIM900 module

Answers: 2

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


body:
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

title: Protothread Library Stalling on One Thread

Answers: 1

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


body:
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.

title: Programming a servo on an ATtiny85

Answers: 1

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);
    }


body:
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++;
        }
      }
    }

title: Variables displayed incorrectly

Answers: 1

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`.


body:
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?

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

Answers: 1

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 -->


body:
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.

title: ESP8266: Client Server Based Home Automation System

Answers: 2

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

body:
```
#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
String i;
long newvar;
String httpurl;
String TheHiddenAnswerOfClient;
HTTPClient http;
String SendWithAnswer(String IPcache, String monmessagecache)
{
  httpurl = "http://";
  httpurl += IPcache;
  httpurl += monmessagecache;
  http.begin(httpurl);
  http.GET();
  TheHiddenAnswerOfClient = (http.getString());
  http.end();
  return TheHiddenAnswerOfClient;
}

void setup() {
  // put your setup code here, to run once:
  i = "";
  newvar = 0;
  Serial.begin(9600);
  WiFi.disconnect();
  delay(3000);
  Serial.println("START");
  WiFi.begin("electromodule", "electromodule@456");
  while ((!(WiFi.status() == WL_CONNECTED)))
  {
    delay(300);
    Serial.print("..");
  }
  Serial.println("Connected");
}

void loop() {
  // put your main code here, to run repeatedly:
  i = (SendWithAnswer("192.168.0.2", "YES"));
  Serial.println("Before Clear");
  Serial.println(i);
  i.remove(0, 25);
  i.remove(i.length() - 11, 11);
  Serial.println("After clear");
  Serial.println(i);
  newvar = i.toInt();
  Serial.println((2000 + newvar));
}
```