message:
IR receiver starts giving nonsense readings in LED colour change setting

First of all, I'm very new to this so sorry if it's a dumb question.

I have an IR module which I'm using to control an LED strip. I have set buttons 1–3 on the remote to select three basic static colours and up and down to adjust brightness. So far so good.

I have set button 4 to gradually shift through different colours. Once I activate this code, the IR receiver appears to stop working, and Serial.print shows that it's now reporting random values whatever button I press on the remote.

I have tried Vishay TSOP4838 and KY-022 type receivers, and tried varying combinations of resistors and capacitors on the receiver power supply. I've tried powering it from 3.3V and 5V.

The code that I'm using is only changing numerical values to adjust the colour, so short of there being 'noise' somewhere in the hardware I'm at a loss as to why only this code breaks it. The LED is powered by a 12V adaptor. The IR receiver is the only thing powered by the Arduino.

My full code is as follows, I know it's untidy. I am a noob:

Thank you

    #include "IRremote.h"
    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
      #include <avr/power.h>
    #endif

    //To change the LED/IR reciever pins, you just need to change these values
    #define PIN 13 //LED strip
    int receiver = 10; //IR receiver

    unsigned long debouncing = 0;
    unsigned long rotatedelay = 6;
    unsigned long fadegap = 5;
    byte state = 0; //maintains function based on last button press
    byte red = 0;
    byte blue = 0;
    byte green = 0;
    byte brightness = 250;
    byte rotate = 0; //used for cycling through colours in state 4

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, PIN, NEO_GRB + NEO_KHZ800);

    //Declare IR objects
    IRrecv irrecv(receiver);     // create instance of 'irrecv'
    decode_results results;      // create instance of 'decode_results'

    //Setup IR buttons with names
    void translateIR() // takes action based on IR code received

    // Naming remote IR codes and assigning a 'state'

    {

      switch(results.value)

      {
      case 0xFFA25D: state = 10; Serial.println("POWER"); break;
      case 0xFF629D: state = 11; Serial.println("VOL+"); break;
      case 0xFFE21D: state = 12; Serial.println("FUNC/STOP"); break;
      case 0xFF22DD: state = 13; Serial.println("FAST BACK");    break;
      case 0xFF02FD: state = 14; Serial.println("PLAY/PAUSE");    break;
      case 0xFFC23D: state = 15; Serial.println("FAST FORWARD");   break;
      case 0xFFE01F: Serial.println("DOWN");    break;
      case 0xFFA857: state = 17; Serial.println("VOL-");    break;
      case 0xFF906F: Serial.println("UP");    break;
      case 0xFF9867: state = 19; Serial.println("EQ");    break;
      case 0xFFB04F: state = 20; Serial.println("ST/REPT");    break;
      case 0xFF6897: state = 0; Serial.println("0");    break;
      case 0xFF30CF: state = 1; Serial.println("1");    break;
      case 0xFF18E7: state = 2; Serial.println("2");    break;
      case 0xFF7A85: state = 3; Serial.println("3");    break;
      case 0xFF10EF: state = 4; Serial.println("4");    break;
      case 0xFF38C7: state = 5; Serial.println("5");    break;
      case 0xFF5AA5: state = 6; Serial.println("6");    break;
      case 0xFF42BD: state = 7; Serial.println("7");    break;
      case 0xFF4AB5: state = 8; Serial.println("8");    break;
      case 0xFF52AD: state = 9; Serial.println("9");    break;
      case 0xFFFFFFFF: Serial.println("REPEAT");break;

      default:
        Serial.println(" other button   ");

      }// End Case

    } //END translateIR

    void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the IR receiver
      strip.begin();
      colorBlock(strip.Color(0, 0, 0));
      strip.show(); // Initialize all pixels to 'off'

    //Fades LED strip light in at startup
    for(uint8_t b = 0; b <255; b++) {
         for(uint8_t i=0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, 255 * b/255, 255 * b/255, 255 * b/255);
         }

         strip.show();
         delay(5); //speed of fade in (20 x 255 = total time)
      };
    }

    void loop() {

    //IR detection code
    //if (irrecv.decode(&results) && millis() - debouncing > 1000) // have we     received an IR signal? ignores button press if less than a second after previous
    if (irrecv.decode(&results)) // have we received an IR signal?
    {
        translateIR();
        irrecv.resume(); // receive the next value
        Serial.println(results.value, HEX);

    if (state == 1){
      rotate = 0;
      red = 0; blue = 255; green = 0;
    colorBlock(strip.Color(red, blue, green));
    }

    if (state == 2){
      rotate = 0;
      red = 0; blue = 0; green = 255;
    colorBlock(strip.Color(red, blue, green));
    }

    if (state == 3){
      rotate = 0;
      red = 255; blue = 0; green = 255;
    colorBlock(strip.Color(red, blue, green));
    }

    //brightness
    if (results.value == 16769055 && brightness > 0){
      brightness = brightness - 10;
      strip.setBrightness(brightness); strip.show();
      Serial.println(brightness);
    }

    if (results.value == 16748655 && brightness < 241){
      brightness = brightness + 10;
      strip.setBrightness(brightness); colorBlock(strip.Color(red, blue, green));     strip.show();
      Serial.println(brightness);
    }
    }

    //rotating colours
    if (state == 4){
      //Serial.println (state);
      //Serial.println (rotate);
      //Serial.print ("red"); Serial.print (red); Serial.print ("blue"); Serial.print (blue); Serial.print ("green"); Serial.println (green);
      //Serial.println (rotatedelay);
    }

    if (state == 4 && rotate == 0 && red < 255 && millis() - rotatedelay > 1){
      red = red + fadegap;
      if (blue >= 1){
        blue = blue - fadegap;}
      if (green >= 1){
        green = green - fadegap;}
      colorBlock(strip.Color(red, blue, green));
      rotatedelay = millis();
    }

    if (state == 4 && rotate == 0 && green > 0 && millis() - rotatedelay > 1){
      green = green - fadegap;
      colorBlock(strip.Color(red, blue, green));
      rotatedelay = millis();
    }

    if (state == 4 && rotate == 0 && red == 255 && green == 0 && blue == 0 &&         millis() - rotatedelay > 1){
      rotate = 1;
    }

    if (state == 4 && rotate == 1 && blue < 255 && millis() - rotatedelay > 1){
      blue = blue + fadegap;
      if (red >= 1){
        red = red - fadegap;}
      if (green >= 1){
        green = green - fadegap;}
      colorBlock(strip.Color(red, blue, green));
      rotatedelay = millis();
    }

    if (state == 4 && rotate == 1 && red == 0 && green == 0 && blue == 255 &&     millis() - rotatedelay > 1){
      rotate = 2;
    }

    if (state == 4 && rotate == 2 && green < 255 && millis() - rotatedelay > 1){
      green = green + fadegap;
      if (red >= 1){
        red = red - fadegap;}
      if (blue >= 1){
        blue = blue - fadegap;}
      colorBlock(strip.Color(red, blue, green));
      rotatedelay = millis();
    }

    if (state == 4 && rotate == 2 && blue == 0 && red == 0 && green == 255 &&     millis() - rotatedelay > 1){
      rotate = 0;
    }
    }

    //Solid colour
     void colorBlock(uint32_t c) { //This seems to be the way to colour the whole strip
      for(uint16_t i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
        strip.show();
        }
     }

body:
Before the lines

    //rotating colours
    if (state == 4){

You have an extra closing brace.  IF that is in you real code, I'm not sure how it is compiling.

Assuming it isn't that then you might want to change you code to make it more readable.  This is just part of you code from the same place mentioned before:

    if (state == 4)
    {
        if (millis() - rotatedelay > 1)
        {
            if (rotate == 0)
            {
                checkFadeGap (red, blue, green);

                if (green > 0)
                {
                    green -= fadegap;
                    colorBlock(strip.Color(red, blue, green));
                    rotatedelay = millis();
                }//if (green > 0)
                if (red == 255  && green == 0 && blue == 0)
                {
                    rotate = 1;
                }//if (red == 255)
            }
            if (rotate == 1)
            {
                checkFadeGap (blue, red, green);
                if (red == 0 && green == 0 && blue == 255)
                {
                    rotate = 2;
                }//if (blue == 255)
            }
            if (rotate == 2)
            {
                checkFadeGap (green, reb, blue);
                if (red == 0  && green == 255 && blue == 0)
                {
                    rotate = 0;
                }//if (green == 255)
            }
        }//if (millis() - rotatedelay > 1)
    }    // end of if (state == 4)

This function removes some of the complexity in the code above.

    void checkFadeGap (byte& inc, byte& dec1, byte& dec2)
    {
        if (inc < 255)
        {
            inc += fadegap;
            if (dec1 > 0)
                dec1 -= fadegap;
            if  (dec2 > 0);
                dec2 -= fadegap;
            colorBlock(strip.Color(red, blue, green));
            rotatedelay = millis();
        }
    }


sender: user

message:
How to use tone in two pins?

I have a buzzer and an IR led emitter so I have to use the tone function to sound the buzzer and to modulate the output of the LED.
I have connected the led pin 5 of the arduino, the buzzer pin A0.

    int tones[] = {261, 277, 294, 280, 230};
    const int pinBuzzer = A0;
    const int cr_pin = 5;

    void setup(){
      Serial.begin(1200);
      tone(cr_pin, 38000);  /* For modulation at 38kHz */
      pinMode(pinBuzzer, OUTPUT);
    }

    void soundBuzzer() {
      for (int i = 0; i < sizeof tones; i ++) {
        tone(pinBuzzer, tones[i]);
      }
        noTone(pinBuzzer);
    }

    void irLED() {
      Serial.println("Hello");
    }

This is my code but I can not make the led and the buzzer work at the same time, apparently the buzzer is affected by the tone line `(cr_pin, 38000); / * For modulation at 38kHz * /.`

I tried to remove `(cr_pin, 38000); / * For modulation at 38kHz * /.` of the setup and leave code in the following way.

    int tones[] = {261, 277, 294, 280, 230};
    const int pinBuzzer = A0;
    const int cr_pin = 5;

    void setup(){
      Serial.begin(1200);
      pinMode(pinBuzzer, OUTPUT);
    }

    void soundBuzzer() {
      for (int i = 0; i < sizeof tones; i ++) {
        tone(pinBuzzer, tones[i]);
      }
        noTone(pinBuzzer);
    }

    void irLED() {
    tone(cr_pin, 38000);  /* For modulation at 38kHz */
          Serial.println("Hello");
    noTone(cr_pin);
        }

In the first code the LED works but not the buzzer and in the second code the buzzer now works but not the LED.

sender: assistant

body:
Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to `tone()` will have no effect. If the tone is playing on the same pin, the call will set its frequency. Source: [arduino.cc - tone()][1].

`noTone()` Stops the generation of a square wave triggered by `tone()`. Has no effect if no tone is being generated. Source: [arduino.cc - noTone()][2]

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/
  [2]: https://www.arduino.cc/reference/en/language/functions/advanced-io/notone/


message:
post data from node mcu to my sql database

#include <ESP8266WiFi.h>

    const char* ssid = "xxxx";
    const char* password = "xxxxxxxxxx";

    const char* host = "192.168.43.18";
    const int ldr = A0;
    int val = 0;

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

      Serial.printf("Connecting to %s ", ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
      Serial.println(" connected");
    }

    void loop()
    {
      val = analogRead(ldr);
      WiFiClient client;

      Serial.printf("\n[Connecting to %s ... ", host);
      if (client.connect(host, 80))
      {
        Serial.println("connected]");
        client.println("POST /past.php HTTP/1.1");
        client.println("Host: 192.168.43.10");
        client.print(val);
        Serial.println(val);
        Serial.println("\n[Disconnected]");
      }
      else
      {
        Serial.println("connection failed!]");
        client.stop();
      }
      delay(5000);
    }

I have uploaded this code to node mcu but it get's working but the uploaded data in my database is not shown please any one help me out

body:
You are using the WIFIClient to send data to a HTTP server.  I don't think the WiFiClient knows how to format HTTP requests properly so you need to do that.  I think there is a HTTPClient which may do more for you.

There is a blank line between the header and body of the message and a blank line at the end of the body. you need to have a line that say `client.println();

Does the "SQL server" accept a message that just contains a number?  How does it know what the number relates to?  If you have some PHP site on the front if the DBS that handles all that then please ignore that question.

You might want to see if you can run Wireshark (or similar) on your PC and see what the MCU is sending, you might also want to look at the Chrome add ins, I believe there are some where you can create raw packets and send those to you server to ensure it responds as expected.

As a final resort you could probably knock up a very quick and dirty C# program using Visual Studio Community Edition (Free) and get that to send a packet to the server.  Using this in combination with wireshark might be easier than using the MCU until you know what you should be doing.


body:
You are not actually posting any data.
After client.println("POST /past.php HTTP/1.1");
Add another line(s) like ...
client.println("?myvar=65dcsagh&anothervar=ghsadjkj78");

Also the page on the server (past.php) needs to be able to get and process the sent data.
If using PHP will be soemthing like..
$data = $_GET[myvar];
And then the PHP code need to connect to your SQL database and insert it using mySQL


body:
My corrected code working code:

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

    #include <ESP8266WiFi.h>

    const char* ssid = "vathsal";
    const char* password = "1234567890";

    const char* host = "wwwkprstaffcom.000webhostapp.com";
    const int ldr = A0;
    int val = 0;
    String data;
    void setup()
    {
      Serial.begin(9600);
      Serial.println();

      Serial.printf("Connecting to %s ", ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
      Serial.println(" connected");
    }

    void loop()
    {
      val = analogRead(ldr);
      data = "ldr=";

      data.concat(val);
      WiFiClient client;

      Serial.printf("\n[Connecting to %s ... ", host);
      if (client.connect(host, 80))
      {
        Serial.println("connected]");
        client.println("POST /add.php HTTP/1.1");
        client.println("Host: wwwkprstaffcom.000webhostapp.com");
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.print("Content-Length: ");
        client.println(data.length());
        client.println();
        client.print(data);
        Serial.println(val);
        Serial.println("\n[Disconnected]");
      }
      else
      {
        Serial.println("connection failed!]");
        client.stop();
      }
      delay(5000);
    }


message:
Minimizing Digital input code

I am making a device which can multiply the analog input signal with respect to the selected gain from the digital inputs. Here I have used two digital inputs(from which I can have four selections) but I am planing to add two inputs more(then I can have 16 selections). I made the code with if else statements is there any shorter way to do that? or else the code is getting huge.

here is the code:

    #define sensor A0
    #define resetPin 3
    #define measurePin 2
    #define k1 3
    #define k2 4

    float A = 0;
    float J = 0;
    int resetstatus = 0;
    int measurestatus = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(sensor,INPUT);
      pinMode(resetPin,INPUT_PULLUP);
      pinMode(measurePin,INPUT_PULLUP);
      pinMode(k1,INPUT_PULLUP);
      pinMode(k2,INPUT_PULLUP);
      Serial.println("INITIALAIZING");
      delay(3000);
      Serial.println("Ready to begin");
      delay(200);
      }

    void loop()
    {
      resetstatus = digitalRead(resetPin);
      measurestatus = digitalRead(measurePin);
      if(resetstatus == LOW)
      {
        reset();
        delay(200);
      }
      if(measurestatus == LOW)
      {
        if(digitalRead(k1 == LOW) && digitalRead(k2 == LOW))
        {
        J = 1.0;
        measure();
        delay(50);
        }
        else if(digitalRead(k1 == LOW) && digitalRead(k2 == HIGH))
        {
        J = 2.0;
        measure();
        delay(50);
        }
        else if(digitalRead(k1 == HIGH) && digitalRead(k2 == LOW))
        {
        J = 3.0;
        measure();
        delay(50);
        }
        if(digitalRead(k1 == HIGH) && digitalRead(k2 == HIGH))
        {
        J = 4.0;
        measure();
        delay(50);
        }
      }
    }
    void measure()
    {
      A = analogRead(sensor);
      float sumA = A * J;
      Serial.println(sumA);
    }
    void reset()
    {
      Serial.println("reset");
    }

I am having a problem with the output from this code
(I am using a potentiometer to feed the arduino an analog value)

[![output][1]][1]

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

I dont know why the output is showing 993 and 3972 at each cycle. can someone explain?

body:
This is wrong:

    if(digitalRead(k1 == LOW)

You mean:

    if(digitalRead(k1) == LOW

Ditto for a lot of other places in your code.


body:
>  I made the code with if else statements is there any shorter way to do that?

    j = 1 + (digitalRead(k1) | (digitalRead(k2) << 1) | (digitalRead(k3) << 2) | (digitalRead(k3) << 3));
or

    j = 1 + digitalRead(k1) + 2*digitalRead(k2) + 4*digitalRead(k3) + 8*digitalRead(k4)

>  dont know why the output is showing 993 and 3972 at each cycle. can someone explain?

the printed values are off because of the error addressed in Nick's answer


body:
>I made the code with if else statements is there any shorter way to do that?
>or else the code is getting huge.

Yes, there is a way of simplification. As @Juraj already noted, it can in this special case even be expressed as a binary representation:

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

    if(digitalRead(k1) == LOW && digitalRead(k2) == LOW)
    {
    J = 1.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1) == LOW && digitalRead(k2) == HIGH)
    {
    J = 2.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1) == HIGH && digitalRead(k2) == LOW)
    {
    J = 3.0;
    measure();
    delay(50);
    }
    if(digitalRead(k1) == HIGH && digitalRead(k2) == HIGH)
    {
    J = 4.0;
    measure();
    delay(50);
    }

What you are doing here is the following pattern:

* read the state of the buttons
* depending on which combinations of buttons is pressed, assign a different value to `J`

We can generalize this concept of "get the J value for a certain button combination" by doing the following:

* aggregate the entire "button states" into a single, unique number
* search for the associated `J` value

If we name the input button states "k1" and "k2", we see that you have the following logic:

    | k1 | k2 | J   |
    | 0  | 0  | 1.0 |
    | 0  | 1  | 2.0 |
    | 1  | 0  | 3.0 |
    | 1  | 1  | 4.0 |

We simply concatenate the button inputs to a signle bitstring "k1|k2" and we see

    | (k1,k2) | J   |
    | 00      | 1.0 |
    | 01      | 2.0 |
    | 10      | 3.0 |
    | 11      | 4.0 |

If we re-write the binary indices to decimal numbers:

    | (k1,k2) | J   |
    | 0       | 1.0 |
    | 1       | 2.0 |
    | 2       | 3.0 |
    | 3       | 4.0 |

So we see that we can use this (k1,k2) number as an index from 0 to 3 to get us a J value as such:

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

    //Aggregate all button inputs to single number
    //using bitshifts
    int index = (digitalRead(k2) << 1) | digitalRead(k1);

    //All used J values in the right order
    const float J_values[] = {
      1.0f, 2.0f, 3.0f, 4.0f
    };

    //get the right J value
    J = J_values[index];

    //measure and delay
    measure();
    delay(50);

This replaces all your 4 `if-else` statements and does exactly the same.

Now if you were to add more inputs, you can simply expand the way you construct the index number and your `J_values` array. Write down the "function table" for your wanted `J` values as above, construct the bit strings, order the indices in ascending order and write down the array values accordingly.

Referenecs:

* https://www.cprogramming.com/tutorial/bitwise_operators.html
* https://www.arduino.cc/reference/en/language/structure/bitwise-operators/bitshiftleft/


body:
Put all 4 pins on one port then do a port read.
Say you used D2,3,4,5
Then
switches = (PIND && 0b00111100) >> 2;

then switches = 0 to 15 and you can do a branch on that.


message:
Reduce speed on DC motor

The Arduino starter kit came with a DC motor. I want to have it rotate at a slow speed so it can be on a reel and automatically dispense and wind wire, however, I don't know how I can slow it down.

Giving it an analog value of 1 is still way too fast.

Is there any way to control or reduce the speed. Like a 360 degree turn in a second rather than milliseconds?

Thanks

body:
Remember if you are using a UNO or similar there is no Analog Output, the output is PWM (Look that up).
If its DC motor then it needs to work from a DC (constant voltage) and will spin at a fixed speed.
Motors usually have a RPM (speed) specification.
Speed can be reduced with gears and rotation detected with rotary encoders and or sensors like Infra Red Switches or Reed Switches.
You can also get Motor Controllers like...
https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
AC Motors can be speed controlled by changing drive frequency, this is usually called an inverter.
NOTE reducing DC voltage will result in less torque and higher current.
Hope this helps.


message:
FTDI and atmega328p-au

I want to connect an Arduino Pro Mini with ATmega328P so as to drive a [SI4463][1]. But I don't know BLK, CTS, DTR should be connected to what pins of ATmega328P.

How do I connect this?

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

  [1]: https://www.silabs.com/documents/public/data-sheets/Si4464-63-61-60.pdf
  [2]: https://i.stack.imgur.com/6ZI5q.jpg

body:
BLK is ground.

CTS is generally not used. I leave it unconnected on my boards.

DTR goes to the auto-reset circuit.

Update:

> Can I let DTR directly connect with RESET ?

Auto-reset circuits use a .1uf capacitor between the DTR (or RTS, depends on which one your cable supplies) and the reset pin. (The exact value probably isn't too important). Without it, the reset circuit is likely pick up noise and randomly reset the Arduino.

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

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


message:
Serial.print query

is it even possible to print a variable output with 4 digits before and one digit after decimal in serial monitor?

my pot reading is shown in the above output

    value   -   1.2
    value   -   51.5
    value   -   61.8
    value   -   546.6
    value   -   255.0
    value   -   1235.9

to this

    value   -   0001.2
    value   -   0051.5
    value   -   0061.8
    value   -   0546.6
    value   -   0255.0
    value   -   1235.9

body:
You basiscally want a format string which includes `%f`. However on Arduino, that only returns a `?` (not included to to space reasons). Refer to https://stackoverflow.com/q/27651012/5296568.

However the alternative is `dtostrf` ([double-to-string-formatted][1]). The function takes the `double` / `float` value, the total wanted width of the string and the decimal places you want to have.

However it fills the string with spaces to the left until the total width is met. You need an additional pass to replace it with `0`.

    #include <Arduino.h>

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

     const float vals[] = {
       1.2, 51.5, 61.8,
       546.6, 255.0,
       1235.9
     };

     //allocate 8 byte buffer
     //biggest string is "-9999.9\0" (with NUL)
     char buf[8];

     int numVals = (int) (sizeof(vals) / sizeof(*vals));

     for(int i=0; i < numVals; i++) {
      //format correctly
      dtostrf(vals[i], 4+1+1, 1, buf);

      //convert left-appended spaces to zeroes
      for(size_t j=0; j < sizeof(buf); j++){
       if(buf[j] == ' ')
        buf[j] = '0';
      }

      //print buffer
      Serial.println(buf);
     }
    }

    void loop() {
    }

Prints

    0001.2
    0051.5
    0061.8
    0546.6
    0255.0
    1235.9

Edit: You can also offload it into a function and then feed it with the ADC values.

Example:

    #include <Arduino.h>

    void printValueFormatted(float value, int numDecimalPlaces, int totalWidth) {
     //format correctly
     char buf[16];
        //prevent buffer overflow
        if(totalWidth >= (int) sizeof(buf))
             return;
     dtostrf(value, totalWidth, numDecimalPlaces, buf);

     //convert left-appended spaces to zeroes
     for(size_t j=0; j < sizeof(buf); j++){
      if(buf[j] == ' ')
       buf[j] = '0';
     }

     //print buffer without newline
     Serial.print(buf);
    }

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

    void loop() {
     float val = analogRead(0);
     Serial.print("ADC Count: ");
     Serial.print(val);
     Serial.print("  -- Voltage: ");
     val = val * 5.0f / 1023.0f;
     printValueFormatted(val, 1, 4+1+1);
     //print newline
     Serial.println();
     delay(100);
    }

Prints

    ADC Count: 719.00  -- Voltage: 0003.5
    ADC Count: 718.00  -- Voltage: 0003.5

  [1]: https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html


body:
    if(val < 1000){Serial.print('0');}
    if(val < 100){Serial.print('0');}
    if(val < 10){Serial.print('0');}
    Serial.println(val, 1);


message:
Float magnet switch interrupts atmega328p and RN2483 sends data

It was so easy to my mind but it is really not. I have a float switch which goes high when water is floating. So I connect the switch to INT0 pin of MCU. So when water is not floating everything is OK. When the water is floating I send data. I declare the interrupt as follows:

    attachInterrupt (digitalPinToInterrupt (switch), float, RISING);

Where float is

    void float()
    {
    detachInterrupt(0);
    digitalWrite (LED, HIGH);
    txReturn = myRN.txCnf("1");
    }

And my main loop is

    attachInterrupt (digitalPinToInterrupt (BUTTON), switchPressed, RISING);
    digitalWrite (LED, LOW);
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

I can't understand why my led is not going LOW and why I interrupt is useless after the first successful time. I am aware that I must keep interrupts routines short and by `txReturn.txCnf("1");` I don't but I can not understand where my logic is wrong.

body:
`float` is already defined for floating point number, so you cannot use it for your function that detects when the sensor is floating on water.  Try calling it something else.

Also, instead of detaching and reattaching the interrupt, use a state machine.  When the interrupt is triggered, you will be able to run different code in the main loop.

    unsigned int state;
    void setup(){
      state=1;
      attachInterrupt(0,changestate,RISING);
    }
    void loop(){

    switch (state) {
    case 1: // do something
    // add code here
    break;

    case 2: // do something else
    // add code here
    break;
    }
    }

    void changestate(){
    if(state==1){state=2;} // interrupt changes state
    }


message:
"Does not name a type" error with Serial.print

I am getting an error that I have never seen before and don't know how to fix. Basically I am trying to print a string (stored in `thermistor`) to the serial monitor. When I run the code I get an error message that says: exit status 1
'Serial' does not name a type.

What can I do fix this error?

    void setup() {
    Serial.begin(9600);
    pinMode(4, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(8, OUTPUT);

    }

    void loop() {

    } <==== ERROR: loop() ENDS TOO EARLY
    String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
    String lilyPad = codeWrite(6, HIGH, LOW, LOW);
    String thermistor = codeWrite(8, HIGH, HIGH, LOW);
    Serial.println(thermistor);
    delay(1000);

    String codeWrite(int pin, char output1, char output2, char output3)
    {
      digitalWrite(pin, output1);
      int A = digitalRead(pin);
      delay(1);
      digitalWrite(pin, output2);
      int B = digitalRead(pin);
      delay(1);
      digitalWrite(pin, output3);
      int C = digitalRead(pin);
      delay(11);
      String code = String(A) + String(B) + String(C);
      <==== ERROR: MISSING RETURN STATEMENT
    }

body:
If you move this code into loop(), the sketch will compile.

    String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
    String lilyPad = codeWrite(6, HIGH, LOW, LOW);
    String thermistor = codeWrite(8, HIGH, HIGH, LOW);
    Serial.println(thermistor);
    delay(1000);

EDIT:

The sketch should look like this:

    void setup() {
      Serial.begin(9600);
      pinMode(4, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(8, OUTPUT);
    }

    void loop() {
      String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
      String lilyPad = codeWrite(6, HIGH, LOW, LOW);
      String thermistor = codeWrite(8, HIGH, HIGH, LOW);
      Serial.println(thermistor);
      delay(1000);
    }

    String codeWrite(int pin, char output1, char output2, char output3)
    {
      digitalWrite(pin, output1);
      int A = digitalRead(pin);
      delay(1);
      digitalWrite(pin, output2);
      int B = digitalRead(pin);
      delay(1);
      digitalWrite(pin, output3);
      int C = digitalRead(pin);
      delay(11);
      String code = String(A) + String(B) + String(C);
    }

The issue is the code can not be outside of a function.


message:
4WD Arduino sketch problem

Here is the code:

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

    /**  * @file         Arduino UNO Autonomous Robot  * @author       Calin Dragos for intorobotics.com  * @version      V1.0  * @date
          13.10.2016  * @description  This is an Arduino sketch for an autonomous robot able to detect and avoid obstacles  */
    #include <AFMotor.h>
    #include <Servo.h>
    #include <NewPing.h>
    Servo myservo;
    int ENABLE_A = 6;
    int PIN_A1 = 3;
    int PIN_A2 = 2;
    int ENABLE_B = 11;
    int PIN_B1 = 5;
    int PIN_B2 = 4;
    int SENSOR_DISTANCE;
    int LEFT_SENSOR_DISTANCE;
    int RIGHT_SENSOR_DISTANCE;
    int SNZ_DISTANCE_L;
    int SNZ_DISTANCE_R;
    int LFT_SNZ_DIS;
    int RGT_SNZ_DIS;
    #define TRIG_PIN 7
    #define ECHO_PIN 8
    #define MIN_DISTANCE 40
    #define MAX_DISTANCE 200
    #define INTERVAL 200
    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    void setup() {
      Serial.begin(9600);
      //pin mode for the DC motors
      pinMode (ENABLE_A, OUTPUT);
      pinMode (PIN_A1, OUTPUT);
      pinMode (PIN_A2, OUTPUT);
      pinMode  (ENABLE_B, OUTPUT);
      pinMode (PIN_B1, OUTPUT);
      pinMode (PIN_B2, OUTPUT);
      //pin mode for the ultrasonic sensor
      pinMode(TRIG_PIN, OUTPUT);
      pinMode(ECHO_PIN, INPUT);
      //for servo motor
      myservo.attach(9);
      //set the ultrasonic sensor to center
      sensorCenter();
      //stop the motors
      stopMotors();
    }

    void loop() {
      SENSOR_DISTANCE = sensorDistance();
      Serial.print("Front sensor distance is: ");
      Serial.println(SENSOR_DISTANCE);
      if (SENSOR_DISTANCE >= MIN_DISTANCE || SENSOR_DISTANCE == 0) {
        goForward();
        Serial.println("Go forward");
      }
      else {
        //stop the motors
        stopMotors();
        LFT_SNZ_DIS = toTheLeft();
        RGT_SNZ_DIS = toTheRight();
        if (LFT_SNZ_DIS >= MIN_DISTANCE && LFT_SNZ_DIS >= RGT_SNZ_DIS)
        {
          int NEW_SNZ_DIS_LFT;
          //try three times to escape
          for (int i = 1; i <= 3; i++) {
            goLeft();
            Serial.println("Go left");
            delay(300);
            //stop the motors
            stopMotors();
            NEW_SNZ_DIS_LFT = sensorDistance();
            if (NEW_SNZ_DIS_LFT >= MIN_DISTANCE)
            {
              break;
            }
          }
          sensorCenter();
        }
        else if (RGT_SNZ_DIS >= MIN_DISTANCE && RGT_SNZ_DIS >= LFT_SNZ_DIS)
        {
          int NEW_SNZ_DIS_RGT;
          //try three times to escape
          for (int j = 1; j <= 3; j++) {
            goRight();
            Serial.println("Go right");
            delay(300);
            //stop the motors
            stopMotors();
            NEW_SNZ_DIS_RGT = sensorDistance();
            if (NEW_SNZ_DIS_RGT >= MIN_DISTANCE)
            {
              break;
            }

          }
          sensorCenter();
        }
        else
        {
          goBackward();
          Serial.println("Go backward");
          delay(500);
          //stop the motors
          stopMotors();
          sensorCenter();
        }
      }
    }

    void stopMotors() {
      analogWrite (ENABLE_A, 0);
      analogWrite (ENABLE_B, 0);
      digitalWrite (PIN_A1, LOW);
      digitalWrite (PIN_A2, LOW);
      digitalWrite (PIN_B1, LOW);
      digitalWrite (PIN_B2, LOW);
    }

    int sensorDistance() {
      int distance;
      int uS = sonar.ping();
      distance = uS / US_ROUNDTRIP_CM;
      if (distance != 0) {
        return distance;
        delay(300);
      }
    }

    void goForward() {
      analogWrite (ENABLE_A, 255);
      digitalWrite (PIN_A1, HIGH);
      digitalWrite (PIN_A2, LOW);
      analogWrite (ENABLE_B, 255);
      digitalWrite (PIN_B1, HIGH);
      digitalWrite (PIN_B2, LOW);
    }

    void goBackward() {
      analogWrite  (ENABLE_A, 180);
      digitalWrite (PIN_A1, LOW);
      digitalWrite (PIN_A2, HIGH);
      analogWrite (ENABLE_B, 180);
      digitalWrite (PIN_B1, LOW);
      digitalWrite (PIN_B2, HIGH);
    }

    void goLeft() {
      analogWrite  (ENABLE_A, 180);
      digitalWrite (PIN_A1, HIGH);
      digitalWrite  (PIN_A2, LOW);
      analogWrite (ENABLE_B, 180);
      digitalWrite (PIN_B1,  LOW);
      digitalWrite (PIN_B2, HIGH);
    }

    void goRight() {
      analogWrite  (ENABLE_A, 180);
      digitalWrite (PIN_A1, LOW);
      digitalWrite (PIN_A2, HIGH);
      analogWrite (ENABLE_B, 180);
      digitalWrite (PIN_B1, HIGH);
      digitalWrite (PIN_B2, LOW);
    }

    void sensorCenter() {
      myservo.write(90);
      delay(500);
    }

    void turnSensorLeft() {
      myservo.write(120);
      delay(500);
    }

    void turnSensorRight() {
      myservo.write(60);
      delay(500);
    }

    int leftSensorDistance() {
      int LEFT_SENSOR_DISTANCE;
      LEFT_SENSOR_DISTANCE = sensorDistance();
      return LEFT_SENSOR_DISTANCE;
    }

    int rightSensorDistance() {
      int RIGHT_SENSOR_DISTANCE;
      RIGHT_SENSOR_DISTANCE = sensorDistance();
      return RIGHT_SENSOR_DISTANCE;
    }

    int toTheLeft() {
      int LEFT_SENSOR_DISTANCE;
      turnSensorLeft();
      LEFT_SENSOR_DISTANCE = leftSensorDistance();
      Serial.print("Left sensor distance is: ");
      Serial.println(LEFT_SENSOR_DISTANCE);
      return LEFT_SENSOR_DISTANCE;
    }

    int toTheRight() {
      int RIGHT_SENSOR_DISTANCE;
      turnSensorRight();
      RIGHT_SENSOR_DISTANCE = rightSensorDistance();
      Serial.print("Right sensor distance is: ");
      Serial.println(RIGHT_SENSOR_DISTANCE);
      return RIGHT_SENSOR_DISTANCE;
    }

Here is the error that I am getting:

<!-- language: lang-none -->

    Arduino: 1.8.6 Hourly Build 2018/05/28 09:33 (Windows 8.1), Board: "Arduino/Genuino Uno"
    In file included from C:\arduino-nightly\hardware\arduino\avr\cores\arduino/Arduino.h:257:0,
                     from sketch\intorobotics.ino.cpp:1: C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
    error: expected unqualified-id before numeric constant
    #define PIN_A1 (15)
                       ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
    note: in expansion of macro 'PIN_A1'
    int PIN_A1 = 3;
         ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
    error: expected ')' before numeric constant
    #define PIN_A1   (15)
                       ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
    note: in expansion of macro 'PIN_A1'
    int PIN_A1 = 3;
         ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
    error: expected unqualified-id before numeric constant
    #define PIN_A2 (16)
                       ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
    note: in expansion of macro 'PIN_A2'
    int PIN_A2 = 2;
         ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
    error: expected ')' before numeric constant
    #define PIN_A2   (16)
                       ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
    note: in expansion of macro 'PIN_A2'
    int PIN_A2 = 2;
         ^ exit status 1
    Error compiling for board Arduino/Genuino Uno.
    This report would have more information with "Show verbose output
    during compilation" option enabled in File -> Preferences.

body: It looks like you've chosen names for your variables that are being used by the core.  Pick different names for those variables.


message:
Why can't my bluetooth receive serial data from my android phone, but can send serial data from my bluetooth to my android phone?

I can receive serial data from my phone but I can't send serial data to the arduino using bluetooth. I can see my input from serial monitor to my Android but not the other way. I'm using [ARF7044A bluetooth module][1] if that matters. Any help would be appreciated please.

Arduino to Android: Working
Android to Arduino: Not working.

Here is the wiring: [![enter image description here][2]][2]

Here is the code:

    char state;
    void setup()
    {
    pinMode(8, OUTPUT);
    Serial.begin(9600);
    }

    void loop()
    {

      if(Serial.available())
      {
        state = Serial.read();
        Serial.println(state);
      }
      if (state == 'a')
      {
        digitalWrite(8, HIGH);
      }
      else if(state == 'b')
      {
        digitalWrite(8,LOW);
      }
    }

  [1]: http://www.farnell.com/datasheets/462686.pdf
  [2]: https://i.stack.imgur.com/mwQEs.jpg

body:
Your erroneous level shifting attempt from Bluetooth TX to Arduino RX is the root of your problem.

Pins 0 and 1 are also connected to the on-board USB interface chip via a pair of 1kΩ resistors. These resistors serve two purposes:

1. To "weaken" the drive of the USB chip's UART interface (actually only needed on the USB chip's TX -> Arduino RX connection), and
2. To protect both the USB chip and the main MCU from damage should two connected pins be set to opposing levels, which would cause high currents to flow through both output drivers.

The TX pin of the USB chip is actively driven HIGH all the time when idle (stupid design by Arduino, it should be Hi-Z when the port is not open), and the RX pin is pulled up by the internal pullup resistor in the USB chip.  Further, when the Arduino's `Serial` is in use the TX pin of the Arduino is actively driven HIGH when idle (or LOW when transmitting a "1" bit).

The actual circuit you have looks more like this:

<!-- 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/Pw1yT.png)

<!-- End schematic -->

Transmitting from the Arduino to the BT module is straight forward enough - the "high" point of the circuit is the Arduno's TX pin at 5V when idle.  Current flows through R2 to the USB RX pin, and through R5 to the BT RX pin, with a portion split off to ground, which is what you want for your level shifting.

Communication in the other direction, however, is different, because you have two balanced "high" points in your circuit - one at the USB TX and one at the Bluetooth TX - and the fact you have 1kΩ resistors in both branches means that neither transmitter is "stronger" than the other. This means that when the BT TX is LOW (0V) you have around 2.5V at the Arduino RX pin (5V over two 1kΩ resistors = 2.5V in the center tap - see [here](https://en.wikipedia.org/wiki/Voltage_divider)).

Since 2.5V is neither within the Arduino's HIGH nor LOW voltage ranges (which are more than 3.5V for HIGH and less than 1.5V for LOW when running from 5V) the input is completely ignored.

The 3.3V transmitted by the Bluetooth module is a little under the *official* threshold for a HIGH signal on an Arduino, but in practice, it usually is detected fine. So remove the resistor network from the Bluetooth's TX pin and connect it directly to the Arduino. Since the input threshold voltage is a function of the supply voltage (0.7 * Vcc) it depends very much on your power supply as to whether it will work reliably or not. If you find it doesn't, you should use some *upward* level shifting.  There are simple MOSFET based bi-directional level shifters available cheaply that are a better solution than resistors, and will allow proper operation in both directions, shifting a high voltage to a low one and a low voltage to a high one. These are good for lower frequency communications such as UART. If you should need higher frequency, or you find a simple MOSFET based shifter isn't working for you then a 74HCT08 or similar chip (be sure to use the HCT range not the HC range) or a dedicated level shifting chip may be in order.


message:
Assigning Pointers to arrays - incorrect results?

I'm trying to build a transmission frame for a workshop library for the Arduino Uno. I have the byte frame inside an array, give it to another function that builds a bit frame and then want to transmit that bit frame.

When I try to print out the arrays using the serial monitor, I get the correct results for the entire byte array and correct results for the bit array up to a certain point. However, since my output (that I'm checking using a logic analyzer) had also more incorrect values when trying to print the values, I suspect it might have to do with timing issues from my transmission and `Serial.print`.

I thus tried to make another pointer (in the code below `frameCheck`) to print that out _after_ I'm done transmitting my frame, which still leaves me with results that are different from what my logic analyzer tells me from a certain point onwards.

My byte array is as follows:

    10100101  // Preamble
    10000000  // First line of my image
    00100000
    00010000
    01000000
    00000000
    00000000
    00000000
    00000000  // Last (8th) line of my image
    11110000  // Checksum

These values are also represented in the bit array (before assignment to what in my code be called `_frame` as well as after that). However, when I read the values from the logic analyzer, the checksum is transmitted as `11111111` instead of `11110000`.

Here is my code in the .cpp file:

    Transmitter::Transmitter()
    {
      [...]
      _frame = new uint8_t[90];
      frameCheck = _frame;
      [...]
    }

    [...]

    int Transmitter::prepFrame(LEDBitmap image) {
      if(_busy) return -1; //no Data can be sent right now since the transmitter is already busy
      if(!_pin) return -2;
      /** construct the frame that is to be transmitted
        *
        * frame structure is
        * 1 byte preamble (0xA5) | 8 byte payload | checksum
        *
        * the image will be transmitted in rows
        * with one row being one byte
        *  1  2  3  4  5  6  7  8   <-- 1st byte
        *  9 10 11 12 13 14 15 16   <-- 2nd byte
        * 17 18 19 20 21 22 23 24   <-- 3rd byte
        * ...                           ...
        */
      uint8_t size = 10;
      uint8_t frame[size];
      uint8_t checksum = 0x00;

        for(uint8_t h = 0; h < image.getHeight(); h++) {
          uint8_t value = image.getBitmap()[h];
          checksum = (checksum + value) % 255;
          frame[h+1] = value;
        }

        for(uint8_t h = image.getHeight(); h < 8; h++) {
          frame[h+1] = 0x00;
        }

      // building the frame
      frame[0] = PREAMBLE;
      frame[size-1] = checksum;

    //The byte frame "frame" is correct at this point

      _frame = buildBitFrame(frame, size);

    //The frame built by this function (see below) as well as the bit frame "_frame" have the correct checksum

      frameCheck = _frame;  // <-- This is the checkFrame which I print in my .ino which gives me false results.

      // set the transmitter into busy mode so the idle pattern will no longer
      // be transmitted but instead the frame will be sent out.
      _busy = true;
      _pos = 0;

      return 1; //preperation was successful
    }

    uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
      _frameSize = size*8;
      uint8_t bitFrame[_frameSize];
      int pos = 0;
        for (size_t byte = 0; byte < size; byte++) {
          for (size_t bit = 0; bit < 8; bit++) {
            bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
            pos++;
          }
        }

      return bitFrame; // <-- This frame is correct as well.
    }

    void Transmitter::transmitBit() {
      if(_active) {
        // Preperation
        // only change the state when the manchester bit is completely transmitted.
        if(!_manHalf) {
          if(_busy) {
            // if there is currently a transmission running
            // read the next bit from the frame
            _state = _frame[_pos];
            if(_pos >= _frameSize) {
              _busy = false;
              _state = 0;
              _pos = 0;
            }
            _pos++;
          } else { // else transmit the idle pattern
            _state = 0;
          }
        }
        // Transmission
        if (!_manHalf) {
          digitalWrite(_pin, !_state);
        } else {
          digitalWrite(_pin, _state);
        }
        _manHalf = !_manHalf;
      } else {
        digitalWrite(_pin, HIGH);
      }
    }

    [...]

The corresponding, relevant lines in the header file are as follows:

    [...]

    class Transmitter
    {
      public:
        Transmitter();

      public: //methods
        int sendData(LEDBitmap image);
        void transmitBit();
        [...]
        uint8_t* frameCheck;

      private: //members
        uint8_t _state;
        uint8_t* _frame;
        [...]

        int prepFrame(LEDBitmap image);
        uint8_t* buildBitFrame(uint8_t* frame, uint16_t size);
        [...]

    };

    [...]

The function `transmitBit()` is called every 1ms via a ISR.

Last but not least, here is my arduino sketch:

    [...]

    Transmitter transmitter;

    [...]

    int smallData[] = {1, 0, 0, 0,
                       0, 0, 1, 0,
                       0, 0, 0, 1,
                       0, 1, 0, 0};

    LEDBitmap small(4, 4, smallData);

    void setup() {
      Serial.begin(2000000);
      transmitter.setPin(4);
      transmitter.start();
      delay(200);
      pinMode(5, OUTPUT);
      digitalWrite(5, HIGH);
      transmitter.sendData(small);
      delay(1000);
      for(int a = 0; a < 88; a++) {
        Serial.println(transmitter.frameCheck[a]);
      }
    }

The loop is currently empty.

Now onto the weird results I'm getting from printing checkFrame (which I have also already gotten when trying to print the full arrays inside my cpp). This is what it printed (already grouped in bytes):

    1 0 1 0 0 1 0 1
    1 0 0 0 0 0 0 0
    0 0 1 0 0 0 0 0
    0 0 0 1 0 0 0 0
    0 1 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0        // Up to here everything is fine.
    0 0 0 0 0 2 149 0      // On the logic analyzer this line reads 0x00 as it should
    221 5 15 0 2 149 0 1   // On the logic analyzer this line reads 0xff instead
    1 222 0 98 2 149 8 218 // This line is irrelevant as it is only a buffer I added to see if the problem lies within my array not having enough space

Now onto my questions!

Do you have an idea what could cause this? Did I do the array assignment wrong? Could this just be an issue with the timing of the `Serial.print`s and my transmitter going off every 1ms? But why does my logic analyzer say that the last line is `0xff` then? Do you have any idea how to fix this?

I'd be super glad if you responded as quickly as possible.
Thanks in advance!

**EDIT:** After increasing the initial value of `a` in my sketch to 64, I found out that the 8th byte is still `00000000` as it says on the logic analyzer. However, the checksum still was a mess. This did also not improve a lot after increasing it to 72. It then was `1 1 2 149 8 218 5 15`. These last few values did also not change when I increased `a` again to 74.

body:
    uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
      _frameSize = size*8;
      uint8_t bitFrame[_frameSize];
      int pos = 0;
        for (size_t byte = 0; byte < size; byte++) {
          for (size_t bit = 0; bit < 8; bit++) {
            bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
            pos++;
          }
        }

      return bitFrame; // <-- This frame is correct as well.
    }

You are returning a pointer to a function-local array which was allocated on the stack. After the function exists the stack for that function gets de-allocated and the array becomes invalid.

It may be valid for a short time after the function exists, but as soon as new functions are called and variables are allocated on the stack, this gets overwritten.

See https://www.fayewilliams.com/2015/06/30/a-challenge-discussion-returning-pointers-to-local-variables/

In cases like these (especially with a constant maximum frame length), you should re-write your memory management to use statically allocated buffers within your class.

For example:

    uint8_t* _frame;

to

    #define SOME_MAX_SIZE 128
    uint8_t _frame[SOME_MAX_SIZE];

And then re-write functions to write into these buffers instead of allocating new memory every time.

Dynamic memory allocation in general should be avoided at all costs on a microcontroller due to heap fragmentation.

If you really want to keep doing it you could also allocate a `new` frame of the required length **and** make sure to **delete** it after usage!

    uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
      _frameSize = size*8;
      uint8_t* bitFrame = new uint8_t[_frameSize];
      int pos = 0;
        for (size_t byte = 0; byte < size; byte++) {
          for (size_t bit = 0; bit < 8; bit++) {
            bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
            pos++;
          }
        }

      return bitFrame; //return pointer to malloced array, okay now.
    }


message:
Arduino does not see data from nodemcu

I’m trying to send data from a NodeMCU to an Arduino nano.

If I try to send data with one second delay - all working fine.

But if I try to send without delay or with a delay less than one second, then arduino sees data but nothing not does.

Arduino nano sketch:

    #include <Servo.h>

    Servo servo1;

    int servo = 6;
    int engine = 5;

    void setup() {
    Serial.begin(9600);
    analogWrite(servo, 67);
    servo1.attach(8);
    }

    void loop() {
    if (Serial.available()) {
    String model = Serial.readStringUntil(':');
    i

    f (model.equals("engine")){
    String value = Serial.readStringUntil('c');
    int power = value.toInt();
    analogWrite(engine, power);
    }
    if (model.equals("servo")){
    String value_servo = Serial.readStringUntil('c');
    int power_servo = value_servo.toInt();
    servo1.write(power_servo);
    }
    }
    }

NodeMCU sketch:

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

    const char* ssid = "my_wifi_ssid";
    const char* password = "my_wifi_password";

    ESP8266WebServer server(80);

    void get_vars(){
    if (server.argName(0) == "engine"){
    server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
    Serial.println("engine:"+server.arg(0)+"c");
    }
    if (server.argName(0) == "servo"){
    server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
    Serial.println("servo:"+server.arg(0)+"c");
    }
    }

    void setup(void){
    main_stuff();
    }

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

    void main_stuff(){
    Serial.begin(9600);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

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

    server.onNotFound(get_vars);

    server.begin();
    Serial.println("HTTP server started");

    }

body:
the newline characters from println (\r\n) stay in the serial input buffer and you read them with `Serial.readStringUntil(':');`. then the string is not "servo" but "\r\nservo"

if you wait one second with sending, the the \r\n are discarded because the readStringUntil times out one second after reading them


message:
Arduino Zero Compiling Issues for "Test-AnalogReadFast-SAM"

#include <Streaming.h>
    #include "StopWatch.h"
    #include <Albert.h>
    #include "avdweb_AnalogReadFast.h"

    const byte adcPin = A1;

    void setup(void)
    { Serial.begin(9600);
      while(!Serial);
      Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
      for(int i=0; i<10; i++) testAnalogRead();
    }

    void testAnalogRead()
    { static Stopwatch Stopwatch(micros);
      //delay(1000);

      stopwatch.start();
      int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
      stopwatch.stop(); int t1 = stopwatch.interval;

      analogReadResolution(12);
      stopwatch.start();
      int adc2 = analogRead(adcPin); // 425us on SAMD21
      stopwatch.stop(); int t2 = stopwatch.interval;

      analogReadResolution(10);
      stopwatch.start();
      int adc3 = analogReadFast(adcPin); // 23us on SAMD21
      stopwatch.stop(); int t3 = stopwatch.interval;

      analogReadResolution(12);
      stopwatch.start();
      int adc4 = analogReadFast(adcPin); // 24us on SAMD21
      stopwatch.stop(); int t4 = stopwatch.interval;

      Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
      analogReadResolution(10); // restore default
    }

    void loop(void)
    {
    }

Hi I have to run this code in the Arduino Zero. When I try to compile this code it throws the following error:

Error:

    In file included from /Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino:2:0:
    /Users/RAJU/Documents/Arduino/libraries/Streaming/Streaming.h:102:15: warning: unused parameter 'arg' [-Wunused-parameter]
     inline Print &operator <<(Print &obj, _EndLineCode arg)

                   ^
    /Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino: In function 'void testAnalogRead()':
    Test_AnalogReadFast_SAM:17: error: 'Stopwatch' does not name a type
     { static Stopwatch Stopwatch(micros);
              ^
    Test_AnalogReadFast_SAM:20: error: 'stopwatch' was not declared in this scope
       stopwatch.start();
       ^
    exit status 1
    'Stopwatch' does not name a type

Any helps are greatly appreciated

body:
The compiler doesn't know the type `Stopwatch`. You have a typo there. A short look into the header file (`StopWatch.h`) shows you, that it is `StopWatch` and not `Stopwatch`. You need a big W there.

Next time first try to investigate yourself. Obviously you didn't do anything before asking here. Next time try it and then, if you  cannot find the problem, then write in your question what you have tried.

---
I was able to compile the following program in my Arduino IDE for Arduino/Genuino Zero:

    #include "StopWatch.h"

    void setup() {
      static StopWatch Stopwatch(StopWatch::MICROS);
    }

    void loop() {
    }

The `StopWatch` library comes from [this Github page][1]. It is the same, that you linked within your other language with the same code, so I assume, that you use it.

For future questions: It is better to directly provide links to all used libraries, that are not part of the Arduino IDE.

  [1]: https://github.com/RobTillaart/Arduino/tree/master/libraries/StopWatch


message:
Understanding how to power objects with a relay (featherwing, feather huzzah)

I am trying to learn how to control a relay to power various household objects. I bought a [power relay][1] shield for an [adafruit feather huzzah][2], and I have just set up the arduino blink sketch to provide conditional high / low to a control pin on the relay:

    const int ledPin = 13;

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

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

If I connect a jumper from the `signal` pin hole on the board to the appropriate `ledPin` (13), I can hear the relay switching on and off. If I use a multimeter in continuity mode, it will register continuity at the appropriate times in the blink sketch (HIGH or LOW).

I might be confused on how the relay should be wired, but shouldn't attaching wires from two of the terminal blocks deliver power to something? If I use a multimeter on wires coming out of the blocks, I don't detect any current. I've tried powering a simple led, but I can't get it to light up. Here's my setup. Can anyone explain what I might be doing wrong? Does the LED need a separate power source apart from what's coming from the feather itself? (the feather is powered by a USB cable from my computer).

Thanks for any clarification anyone can provide.

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

BTW, here is a reference photo from Adafruit of how they have it wired.

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

  [1]: https://learn.adafruit.com/adafruit-power-relay-featherwing/pinouts
  [2]: https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/pinouts
  [3]: https://i.stack.imgur.com/6SJnR.jpg
  [4]: https://i.stack.imgur.com/NpJ4Z.jpg

body:
A relay is just a switch, that is controlled via a magnet force from coil. The power line to the relay breakout board is just used to drive enough current through this coil, since often the 20mA of a normal digital output pin aren't enough for that.

Relays are for switching big loads, that should not have contact with the microcontrollers circuit. You don't want the 230V (or 110V, depending on where you live) to find their way to the microcontroller. Also most boards can only provide a very limited amount of current. Big loads mostly need a lot of current and you don't want this big current flowing through the tiny copper traces on the board. You have to use an extra power supply for these.

So have to connect the relay like a normal switch, in series with the load you want to control with it. Also keep in mind the difference between the normally open and normally closed output of the relay. Here is a schematic, to explain further, what circuit you need:

<!-- 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/UcCtI.png)

<!-- End schematic -->

You provide power for the coil of the relay from the two power lines of the ESP (3.3V and GND). The digital pin, that you use for switching is just a signal. It only has to provide a very minimal amount of current. The board itself has a driver circuit to activate the coil. Here I used a simple MOSFET, but I actually don't know, what driver circuit is really used on that board.

If enough current is flowing through the coil, the switch inside the relay changes from NC (normally closed/connected) pin to NO (normally open) pin, closing the electrical circuit, that provide the big load (here a light bulb) with current from an external power supply (like a wall outlet). The two circuits are NOT electrically connected, so you won't have to deal with potential high voltage and current on the ESP side.

---

And in your sketch you don't ever turn the LED off. I assume this is just an error from copy/paste.


body: I don't see a current limit resistor in the LED circuit, 270 to 470 Ohms, must have. Also, there is no power supply for the LED, the relay is just a short circuit across the LED.


message:
Error using SD card module: no matching function for call to

This code is just a test code to write a file to an SD card using an SD card module. When I run the code, I get this error message and I'm not sure what to do to fix the code: `no matching function for call to'SDLib::SDClass::exists(SDLib::File&)'`.

    #include <SD.h>
    #include <SPI.h>

    int cs = 10;

    File myTest;

    void setup()
    {
      //
      char myTestName[] = "MyTest.txt";

      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {

      }
      Serial.println("Initializing SD card...");
      Serial.println();

      pinMode(cs, OUTPUT);
      pinMode(SS, OUTPUT);
      if (!SD.begin(cs)) {
        Serial.println("SD did not initiliaze");
        while (1) ;
      }
      Serial.println("SD initialized.");

      if (! SD.exists(myTest)){
         myTest = SD.open(myTestName, FILE_WRITE);

         myTest.println("My 1st Line of Data");
         myTest.flush();
      }
      else{
        myTest = SD.open(myTestName, FILE_WRITE);
        myTest.println("Another Line of Data");
        myTest.flush();

      }

      Serial.println("Done Writing");

    }

    void loop()
    {

    }

body:
The function is defined as

    // Methods to determine if the requested file path exists.
    boolean exists(char *filepath);

Source: https://github.com/adafruit/SD/blob/master/SD.h#L90

You call it with a `File` object, not the filename. You probably mixed up the variable names:

    File myTest;

    void setup()
    {
      //
      char myTestName[] = "MyTest.txt";

      //[...]
      if (! SD.exists(myTest)){
         myTest = SD.open(myTestName, FILE_WRITE);
         myTest.println("My 1st Line of Data");
         myTest.flush();
      }
    //..

Just exchange `myTest` for `myTestName` in the `SD.exists()` call.


message:
Where can I find the code for Arduino's "attachInterrupt"?

Where can I find the code for [Arduino's `attachInterrupt`][0] function?

A search on the [Arduino's Github repo][1] yielded nothing.

I suspect it might be a wrapper for some avr-libc function but nothing in [the avr-libc docs][2] stands out to me...

[0]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
[1]: https://github.com/arduino/Arduino
[2]: https://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html

body:
It's in the core in WInterrupts.c

On my install it's at:

arduino-1.8.5/hardware/arduino/avr/cores/arduino/WInterrupts.c


message:
I have downloaded the library but not sure what went wrong

C:\Users\Dray98\AppData\Local\Temp\arduino_modified_sketch_819854\sketch_jun09a.ino:2:29: fatal error: Adafruit_Sensor.h: No such file or directory

     #include <Adafruit_Sensor.h>

                                 ^

    compilation terminated.

    Multiple libraries were found for "DHT.h"
     Used: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
     Not used: C:\Users\Dray98\Documents\Arduino\libraries\DHT-sensor-library-master
    Using library DHT_sensor_library at version 1.3.0 in folder: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

body: Have you installed the Adafruit_Sensor library correctly? If not, at top of IDE, click <Sketch -> Include Library > and see if it's in the list and click it, if not, go to top of list and click Manage Libraries..., search for and click on it.


body:
When you encounter a `No such file or directory` error it usually means you need to install the library that contains the missing file (in this case Adafruit_Sensor.h).

Ideally the documentation for the code you are trying to compile will have instructions for installing dependencies.

Sometimes the author did not make the effort to write this documentation and you'll need to go searching for the missing library.

Many Arduino libraries are in the Library Manager index, which makes them quite easy to install:

### Library Manager installation

1. (In the Arduino IDE) Sketch > Include Library > Manage Libraries.
1. Wait for the download to finish.
1. In the "Filter your search..." box, type your search query, in this case "adafruit unified sensor abstraction layer" would get you the one correct result but with a little searching through the results of a more general search like "adafruit sensor" will get you there also.
1. Scroll through the search results to find something that looks correct (in this case "Adafruit Unified Sensor by Adafruit"), then click on it.
1. Click "Install".
1. Wait for installation to finish.
1. Click "Close".

If you don't find the library you need in Library Manager you'll need to spend some time with your favorite search engine. Once you find the library and download it you'll need to install it.

### .ZIP Installation

1. (In the Arduino IDE) Sketch > Include Library > Add .ZIP Library
1. Select the downloaded file (must be a .zip).
1. Click "Open".

The above installation instructions require the .zip file to have a specific folder structure. In some cases the library author has not been kind enough to provide the correct folder structure. If you get a "Zip doesn't contain a library" error message then you will need to do a manual installation of the library.

### Manual Installation

1. Unzip the downloaded file
1. Browse through the unzipped folder until you find the library folder. This will either have a library.properties file and/or a .h file.
1. Copy the library folder to `{Sketchbook folder}/libraries`. You can find the sketchbook folder in the Arduino IDE at **File > Properties > Sketchbook location**.
You will need to restart the Arduino IDE before the examples sketches for manually installed libraries will appear under the **File > Examples** menu.


body:
Your problem is, that you haven't installed the `Adafruit_Sensor.h`, which is a dependency of Adafruits DHT library. The README on Github for the DHT library also states this:

> You must have the following Arduino libraries installed to use this
> class:
>
>     Adafruit Unified Sensor Library

You can find the `Adafruit_Sensor.h` [here at Github][1]. Install it in your libraries folder. You can refer to the answer from per1234 for instructions on installing libraries.

--

The second part in your error output is not really an error. As others stated before, the IDE only tells you, which version of the DHT library it uses. If you want to have multiple version in your libraries folder, you will have to make sure, that you always use the correct one. If they are identical, you can delete one of them, if you want to. The outcome would not be any different, except for that the IDE doesn't have to tell you, which library it uses.

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


message:
Why this code for ESP8266 goes into STA+AP mode?

I'm using Arduino IDE 1.6 nightly with Generic ESP8266 Board.

Why this code runs in mesh mode instead of simply connecting to my wifi?
My goal is to test out MDNS, but so far I found this:

- board connects to my wifi
- but board also opens an `ESP-` access point
- when connected to my wifi on my computer I cannot resolve http://esp8266-webupdate.local/update
- when connected to the open `ESP-` wifi I can resolve http://esp8266-webupdate.local/update

To my understanding such code should just connect to my wifi and I would then be able to navigate to http://esp8266-webupdate.local/update, am I missing something?

**output (note STA+AP)**

    Booting Sketch...
    ......
    Connected, IP address: 192.168.1.20
    Mode: STA+AP
    PHY mode: N
    Channel: 10
    AP id: 0
    Status: 5
    Auto connect: 1

**code**

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

    const char* host = "esp8266-webupdate";
    const char* ssid = "myhomeap";
    const char* password = "blabla";

    ESP8266WebServer httpServer(80);
    ESP8266HTTPUpdateServer httpUpdater;

    void setup(void){

      Serial.begin(115200);
      Serial.println();
      Serial.println("Booting Sketch...");
      WiFi.mode(WIFI_AP_STA);
      WiFi.begin(ssid, password);

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

      Serial.print("Connected, IP address: ");
      Serial.println(WiFi.localIP());
      WiFi.printDiag(Serial);
      MDNS.begin(host);

      httpUpdater.setup(&httpServer);
      httpServer.begin();

      MDNS.addService("http", "tcp", 80);
      Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
    }

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

body:
It goes into STA+AP mode because your code is telling it to do that.

If you want it to just go into STA mode then your line:

```
WiFi.mode(WIFI_AP_STA);
```

should be

```
WiFi.mode(WIFI_STA);
```


message:
Timer frequency calculation for UNO/Atmega328

I must be overwrought or something... I just can't get the calculation of the timer frequency right. I have a 16 MHz crystal on the Atmega328. I want 1 kHz timer interrupt rate. So I chose prescaler = 64 and counter top = 249, that is

fTimer = fCPU/prescaler/(top+1) = 16 MHz/64/250 = 1 kHz

But my oscilloscope shows 2 kHz... !? Why?

I have read https://arduino.stackexchange.com/questions/53298/timer2-compare-interrupt-not-working-as-expected but the accepted answer doesn't make it better. There the frequency is half as high whereas mine is twice as high as expected.

Code:

    const int signalLED = 1; //14;

    void setup()
    {
      pinMode(signalLED, OUTPUT);
      digitalWrite(signalLED, LOW);

      TCCR2A = 0; // set TCCR2A register to 0
      TCCR2B = 0; // set TCCR2B register to 0
      TCNT2  = 0; // reset counter
      OCR2A = 249; // top value in CTC mode
      TCCR2A |= (1 << WGM21); // enable timer2 CTC mode
      TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2
      TIMSK2 |= (1 << OCIE2A); // enable timer2 compare interrupt
      sei(); // allow interrupts
    }

    ISR(TIMER2_COMPA_vect)
    {
      // generate peak
      digitalWrite(signalLED, HIGH);
      digitalWrite(signalLED, LOW);
    }

    void loop()
    {
    }

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

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

body:
Your comment:

    TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2

doesn't match the actual setting (= 1/32)

Also there are some issues with setting Timer2 CTC mode, it's better to set mode, then OCR2A + TCNT2 + interrupts and then Prescaler to start the timer. It behaves as there is OCR2A=0, so the frequency is much higher than expected.


message:
What is corrrect the way to find roll, pitch, yaw?

I have an MPU9250. I have calculated accelerometer, gyroscope, magnetometer. But I want to know how to caclulate roll yaw pitch. I have searched on Google. I found many answer

    roll  =  (atan2(-Accel_Y, Accel_Z)*180.0)/M_PI;
    pitch =  (atan2(Accel_X sqrt(Accel_Y*Accel_Y + Accel_Y*Accel_Y))*180.0)/M_PI;

source: https://theccontinuum.com/2012/09/24/arduino-imu-pitch-roll-from-accelerometer/

       accelerationX = (signed int)(((signed int)rawData_X) * 3.9);
       accelerationY = (signed int)(((signed int)rawData_Y) * 3.9);
       accelerationZ = (signed int)(((signed int)rawData_Z) * 3.9);
       pitch = 180 * atan (accelerationX/sqrt(accelerationY*accelerationY + accelerationZ*accelerationZ))/M_PI;
       roll = 180 * atan (accelerationY/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;
       yaw = 180 * atan (accelerationZ/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;

source:  https://engineering.stackexchange.com/questions/3348/calculating-pitch-yaw-and-roll-from-mag-acc-and-gyro-data

      Accroll = atan2( accy / (accy^2 + accz^2) )
      Accpitch = atan2( accx / (accx^2 + accz^2) )

source: http://franciscoraulortega.com/pubs/Algo3DFusionsMems.pdf

     Accroll = atan2(accy, accz)
     Accpitch = atan2( -accx, sqrt(accy^2 + accz^2) )

source:https://www.nxp.com/docs/en/application-note/AN3461.pdf

What is the correct way to find roll yaw pitch?

body:
For a stationary accelerometer sensing the acceleration of gravity, I see "dead zones" when the Pitch, Yaw or Roll axes are parallel or close to parallel to the gravity vector.

Likely this is why accelerometers are used in conjunction with gyroscopes.

Refer to [this NXP (aka Motorola, Freescale & Qualcomm) document][1] for an in depth discussion regarding the necessary math.  Note the section regarding "Regions of Instability".

Also, refer to [this class][2] and [this class][3] from rutgers.edu which work students through a project using an Arduino and an accelerometer in the 1st class then adds a gyroscope in the 2nd class to improve the response.

(Added Later)

The rutgers.edu links don't appear to work anymore and [this link][4] has been suggested as an alternative.

  [1]: http://cache.freescale.com/files/sensors/doc/app_note/AN3461.pdf
  [2]: http://physics.rutgers.edu/~aatish/teach/srr/workshop3.pdf
  [3]: http://physics.rutgers.edu/~aatish/teach/srr/workshop4.pdf
  [4]: http://aatishb.com/materials/srr/materials.html


message:
Long freezes at the beginning of sd card transfer

I am creating an accelerometer data logger that writes data to sd card. After some sort of "warm-up" everything works perfectly for at least ~15 minutes (which is what I have tested so far).

However, during the first few seconds there are some pretty long freezes of the File.write() function (180 ms instead of 50us for normal writes!) which I can identify on an oscilloscope (see picture below, signal low after starting high indicates File.write() phases) and which I can also see in the data if I include in them a milis() timestamp.

Since RAM on the Atmega328 is limited, there is also tight limits to the amount of sensor data I can buffer (I am using an interrupt for transfer from the sensor, where I can store the data to a buffer and thus bridge the shorter sd card delays).

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

I stripped down my code to the absolute bare bones, just writing nonsense data instead of those from the accelerometer. What could be the reason for these freezes? The data rate is the same during the whole run. Isn't the sd card electrically or logically initialized after SD.begin()? It doesn't seem to be a problem with erasing flash memory blocks because it only occurs in the beginning. Even if I restart the application a second time (after staying electrically on all the time) it already shows no freezes anymore. Whereas if I unplug/plug power, the freezes in the beginning reappear.

**And most importantly: how can I solve it?**

Of course I could write the dummy data before receiving the start button. But how many? Does it depend on sd card type? Does it depend on cpu or spi clock frequency? I want a robust solution that doesn't break when I use another type of sd.

Code:

    #include <SPI.h>
    #include <SD.h>

    const int chipSelect = 10; // chip select of the sd card
    const int pushButton = 9; // this is where the start button is (on a pulldown resistor)
    const int debugPin = 1; // a line used for displaying a debug bit on the oscilloscope

    const int bufferSize = 14;
    byte buffer[bufferSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; // for the test just dummy values

    String fileName = "accellog.raw";

    void setup()
    {
      pinMode(pushButton, INPUT);
      pinMode(debugPin, OUTPUT);

      if (!SD.begin(chipSelect))
      {
        // on error stop execution
        for(;;);
      }
    }

    void loop()
    {
      // wait for the start button to be pressed
      while (digitalRead(pushButton) == HIGH);
      delay(100); // debounce delay
      while (digitalRead(pushButton) == LOW);

      // remove old file on sd card
      if (SD.exists(fileName)) SD.remove(fileName);

      File dataFile = SD.open(fileName, FILE_WRITE);

      if (dataFile)
      {
        // Debugging: indicate start of whole data transfer on an oscilloscope
        digitalWrite(debugPin, HIGH);

        int lastMillis = millis();

        for (long i=0; i<10000; i++)
        {
          // wait until millis changes in order to get SD writes at
          // whole millisecond boundaries (some cycles may get lost,
          // however, during lengthy SD writes)
          int tempMillis = millis();
          while (tempMillis == lastMillis)
          {
            tempMillis = millis();
          }
          lastMillis = tempMillis;

          // Debugging: indicate file access times by sending 0 to the DSO
          digitalWrite(debugPin, LOW);

          dataFile.write(buffer,bufferSize);

          // Debugging: indicate end of file access on DSO
          digitalWrite(debugPin, HIGH);
        }

        // Debugging: indicate end of whole data transfer
        digitalWrite(debugPin, LOW);

        dataFile.close();
      }
      else
      {
        // on error stop execution
        for (;;);
      }
    }

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

body:
As a temporary workaround I have come to the following procedure:

I inserted a function that writes a certain amount of bytes into a dummy file, closes it and finally deletes it, all during setup().

This does indeed seem to cure the freezes if (in my scenario) I write at least 6 blocks (512 bytes each, i.e. total 3072 Bytes). Remarkably there were always exactly 6 freezes visible in my oscilloscope plots. I don't even remotely know what the meaning of this magic number 6 could be...

Just to have some additional safety in case I choose a different type of sd card (and this workaround becomes permanently temporary...), I have decided to write 16 kB into the dummy file. This is ~5 times as much as the empirical minimum value (3 kB) and is still pretty fast so that I don't notice any significant startup delay after power-up.

This empiric approach is still unsatisfactory though, and certainly a piece of mediocre engineering. So I won't mark my answer as accepted, to leave the chance for someone else to give a more well-founded answer.

    void writeAndEraseDummyFileToEliminateFreeze()
    {
      if (SD.exists("dummy")) SD.remove("dummy");
      File dummyFile = SD.open("dummy", FILE_WRITE);
      int n = 16384/recordSize+1; // write 16kB in chunks of recordSize (just because we have that buffer already
      for (int i=0; i<n; i++)
      {
        // buffer values are uninitialized, but who cares, we'll dispose of them anyway
        dummyFile.write(buffer,recordSize);
      }
      dummyFile.close();
      SD.remove("dummy");
    }

    void setup()
    {
      // ...other things I have been already doing...

      writeAndEraseDummyFileToEliminateFreeze();
    }


message:
DT-06 WIFI. How to program with Arduino Uno

I have a DT-06 wireless WiFi. I can connect using my phone but I cannot access 192.168.4.1/status.html or /wifi_set.html like in the tutorial

I put this module in wiring with Arduino Uno on 5v. I notice that the LED is low lighting until I put pin state in GND. Then I get full power red led. I put RX module to TX Arduino and TX module to RX Arduino but i can not access it using Arduino.

How can I program this module or how can I access? Any tutorial links are welcome.

Thanka. Sorry for my English.

L.E.

Module RX - Arduino TX
Module TX - Arduino RX
Module VCC - Arduino 5v
Module GND - Arduino GND
Module STATE - GND

My module has a red led on it. This led is low lighting until i put pin STATE in GND. After that the red led is full lighting.

After i put VCC and GND i can "see" my module using my phone wireless connection

body:
Are you wiring it to Arduino pins 0 & 1? These are hard-wired to the other processor on the Arduino board that handles USB to/from your PC. There may be interference with the DT-06 unless you disconnect from your PC after upload. But then you'll need an alternate source of power to the Arduino.

You can pick another pair of pins and use the SoftwareSerial library (up to 9600 baud) to talk to the DT-06. Make sure Arduino and the DT-06 use the same baud-rate. You may have to experiment to find what baud-rate the device has now, in order to set it to 9600.

Update:

> Do i have to use any resistence?

Two sites I looked at described the DT-06 voltage requirement as:
"Working voltage: 4.5V~6.0V, TTL working voltage: 3.3V (compatible with 5.0V);", so you should be OK without voltage divider resistors.

> And what settings to make in arduino IDE before uploading code?

You won't need to change your IDE to upload code to the Uno.


message:
How much low analog voltage can Arduino uno read?

Today I was playing around with arduino analog voltage ranges, the error in output
 with respect to a digital multimeter started to happen when the reading was around 0.0014volts. How much low an arduino can read?

body: You divide your reference voltage by 1024.  That tells you what the step size is.  The smallest you can measure is an ADC reading of 1.  So for say a 5V reference that works out to 0.00488V


body:
The Arduino Uno uses a processor containing a 10 bit ADC.  This means the ADC can resolve (if we do not consider noise) 2 to the 10th or 1024 voltage levels between zero and the voltage supplied to the Arduino Uno at the AREF pin.  There is a good explanation of the AREF pin in [this stackexchange.com question / answer][1].  It is common practice to supply the AREF with voltages lower than the positive rail the processor is operating at to improve resolution of expected lower voltages.  For example, if you do not expect to measure voltages higher than 3.3 volts on a 5 volt Arduino, use the 3.3 volt supply as a reference.  Relative to using a 5 volt reference, using a 3.3 volt reference decreases your granularity from 0.00489 to 0.00322 volts per step.

Of course there is a lot of noise in most ADC circuits.  Finding the average of many ADC readings helps mitigate this problem.  Consider using [exponential averaging][2].

  [1]: https://arduino.stackexchange.com/questions/132/what-are-the-aref-ioref-and-the-unlabeled-pin-next-to-ioref-on-the-uno-r3?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
  [2]: https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average


message:
Arduino 3rd party cores

I am trying to use Arduino platform.txt to run some extra pre-processing on my Arduino codes.

As far as I can understand the best way to do that is to use prebuild hooks as mentioned below
https://github.com/arduino/arduino/wiki/arduino-ide-1.5-3rd-party-hardware-specification

I am using the hooks as follows

    recipe.hooks.sketch.prebuild.1.pattern=echo {source_file} sketch pret;
    recipe.hooks.sketch.prebuild.2.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

This is the output I get for the hooks

    echo "{source_file}" sketch pret;
    {source_file} sketch pret;
    "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -c -g -Os -w -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto -fno-fat-lto-objects -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   {includes} "{source_file}" -o "{object_file}"
    avr-gcc: error: {includes}: No such file or directory
    avr-gcc: error: {source_file}: No such file or directory
    avr-gcc: fatal error: no input files
    compilation terminated.

The {source_file} variable is used in a compilation reciep as follows

    recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

and the recipe runs as follows

    "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino" "-I/Users/vinayakjoshi/Library/Arduino15/packages/boltiot/hardware/avr/1.0.0/variants/boltduino" "-I/Users/vinayakjoshi/Documents/Arduino/libraries/boltiot-arduino-helper-update-dev/src" "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/src" "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp" -o "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp.o"

As you can see, in a standard recipe, the variable {source_file} and other such definitions are correctly replaced. But in the hooks, this is not happening.

I want to know whether it is possible to get the value of the {source_file} variable to be used with the hooks, so that I can do some extra pre-processing with it. And if it is, how can I do it.

P.S. IDK what tag has to be used. I couldn't find platform.txt or 3rd party cores. I used the Arduino-IDE tag, as this question definitely asks how the IDE works.

body:
It looks like those properties are only expanded in:

- `recipe.cpp.o.pattern`
- `recipe.S.o.pattern`
- `recipe.c.o.pattern`
- `recipe.preproc.includes`
- `recipe.preproc.macros`

They are not expanded in any of the hook recipes.

This actually makes sense for `{source_file}` with the current build system because the hooks are not run before and after the compilation of each file but rather before and after the entire sketch compilation, so even if that property was expanded it could only give you an arbitrary filename, perhaps the first file to be compiled in the prebuild hook and the last in the postbuild hook, but that leaves all the other filenames inaccessible so it really wouldn't do much good. See [related issue report](https://github.com/arduino/Arduino/issues/7160).

If you're actually trying to use `{source_file}` to get the preprocessed sketch file, that's accessible from any recipe as `{build.path}/sketch/{build.project_name}.cpp`.

As for `{includes}`, it seems like an unnecessary restriction for that property to only expand in specific recipes. If you can present a good case for this behavior being changed, it might be worth opening a feature request to see what the Arduino developers will think.


message:
How to expand an Arduino when using a TFT display shield?

I am really new to this Arduino stuff. I can't figure out one of my problems on my own.

I am using this [2.4 TFT display shield][1] on an Arduino Uno. It works fine so far: I have coded a little sketch for it that displays a start button and after tapping that it shows random colors.

Now I would like to connect a circuit with jumper cables that are used as sensors. When I touch one of the jumper cables the light connected will turn on.

The problem I have now is that this specific circuit is using an other Arduino because my first Arduino is already 'full' because the TFT shield is taking up all pins.

How can I resolve my problem? Is it possible to Stack Arduinos? Is it possible to connect those Arduinos somehow? Thanks in advance!

  [1]: https://www.hackster.io/calogerus/arduino-uno-2-4-tft-lcd-display-shield-touch-panel-ili9341-576b1b

body:
Ok, your problem seems to be that you have run out of pins. Currently you are using an Arduino Uno. I would go out and buy an Arduino Mega.

Alternatively you could use the analog inputs as digital inputs.

**[Arduino Uno][1]**
Digital I/O Pins **14** (of which 6 provide PWM output)
Flash Memory 32 KB (ATmega328P) of which 0.5 KB used by bootloader

**[Arduino Mega][2]**
Digital I/O Pins **54** (of which 15 provide PWM output)
Flash Memory 256 KB of which 8 KB used by bootloader

  [1]: https://store.arduino.cc/usa/arduino-uno-rev3
  [2]: https://store.arduino.cc/arduino-mega-2560-rev3


body:
As I can read your link, the shield is using D2-D8 and A0-A3, leaving some pins unused. So some Arduino pins are still free to use, just the shield is in the way to get connected there.

So there are some possible ways:

- brutally solder some wires to the shield unused pins from front side and use that wires to connect where you want (sensors, breadboard, universal PCB, ...)
- brutally solder some wires to arduino bottom on unused pins, then continue as mentioned
- create intermediate shield (there are many, which allow you connect to arduinou on bottom and stack antother shield on top, draw your wires from there (and maybe even put some circuities on the middle shield, if you want
(something like this https://www.aliexpress.com/item/UNO-Prototype-DIY-shield-kit-for-Arduino-UNO-Universal-Extend-Board-UM-UNO/32555004112.html or any "arduino universal shield"

https://www.indiegogo.com/projects/ardushield-most-universal-shield-for-arduino-ever#/ works excelently across arduinos and other shields/breadboards ...

or anything along this lines ... http://shieldlist.org/sunhayato/universal

- use pins D10-D13 as they are connected also to ISP header https://www.arduino.cc/en/Tutorial/ArduinoISP and could be connected from there. As they are part of SPI interface
https://www.arduino.cc/en/Reference/SPI that could be good coise too (if you manage ChipSelect somehow.

---
As for other part of question -
It is possible to connect more arduinos, there are so much different ways, that it is hard to write here all - choose one, that would suit you best. (anyway you would need some access to some pins anyway )


message:
Reed Sensor matrix for chess board query

NOTE:
This is not a question that has been answered previously in similar questions.
I am using an arduino Mega

I have gone through [Bergers Blog(schematic is in this link)][1], but have been breaking my head on the logic of your sensor matrix, I have been breaking my head for the past few days on this one thing.

1. Initially he set all rows to HIGH then reset the 1st row to LOW to scan the reed sensors, let's assume that all the sensors in the 1st and 2nd row are closed.

My question is that since the 1st row is set to LOW won't it get shorted because the second row is initially set to HIGH?

Also, I used the same matrix as berger but instead I enabled the internal Pull up pins of all the 8 input pins, but yet again I faced the same problem of getting a short , since if a row 1 is set to LOW and row 2 is initially set to HIGH then One sensor in row 1 is closed and a reed sensor in row 2 below the sensor mentioned in row 1 is also closed. Then won't we get a short and random values show on the arduino.

  [1]: https://sites.google.com/site/bergersprojects/reedcb/programming

body:
Almost all switch matrix keyboards use normally open / momentary contact switches. Consider this when discussing switch matrix behavior. Your initial (text) description is of a switch matrix only comprising of switches.  For such a matrix, only one switch may be closed at any given moment. This is to prevent aliasing.  A conditions where multiple simultaneous switch closures cause the incorrect key to be detected. And, in some cases, prevents harmful shorts.

Adding a [forward biased diode][1] to every switch in a matrix prevents harmful shorts.  For a design where one row is driven high and all other rows are driven low, closing two switches in a single column can directly connect the row driven high with a row driven low in a switch matrix only comprising of switches.  However, if a normally forward biased diode is placed in series with both of these closed switches, only the diode connected to the row driven high would be forward biased.  The diode connected to the row driven low would be [reversed biased][2] preventing the harmful short.

Using diodes on every switch is costly.  Most computer keyboard do not use this approach.  Instead they use clever circuitry and layouts to prevent shorts and improve their perceived performance.  In reality, almost all computer keyboard have an [n-key-roll-over][3] limit.  A point at which the keyboard fails to detect or distinguish a new pressed key while other keys are already pressed.

For a graphic example of the behavior of a forward and reversed biased diode consider this image from allaboutcircuits.com where the diode on the left is in forward biased and the diode on the right is in reversed bias:

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

  [1]: https://en.wikipedia.org/wiki/P–n_junction#Forward_bias
  [2]: https://en.wikipedia.org/wiki/P–n_junction#Reverse_bias
  [3]: https://en.wikipedia.org/wiki/Rollover_(key)
  [4]: https://i.stack.imgur.com/ElrEA.png


body:
Mega has 70 inputs, 86 if you use a '2560 in a full breakout board.
I offer a couple of form factors to access all pins at http://www.crossroadsfencing.com/BobuinoRev17

Chess board will always have multiple pieces in multiple rows and multiple columsns pressed until near the end of the game. I'd wire up each square individually, make life a lot easier.  Read ports 8 pins at a time, 8 reads to have all 64 squares read.


message:
DT-06 program using arduino uno

I'm working to program DT-06 wireless wifi module.

And right now when i'm trying to program i get the following error message :
espcomm_send_command: can't receive slip payload data

Module RX - Arduino RX

TX - TX

VCC - 5v

GND - GND

Right now i can upload black program to arduino and send serial AT commands to my module and alson getting response.

How can i program ?

Thx

Appendix:

 * Module:  https://www.banggood.com/Geekcreit-DT-06-Wireless-WiFi-Serial-Port-Transparent-Transmission-Module-TTL-To-WiFi-p-1141047.html

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

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

body:
Just program it like you would program a normal ESP8266.

The documentation is here:

* https://github.com/SmartArduino/SZDOITWiKi/wiki/ESP8266---TTLtoWiFi

The datasheet provides the schematic of the module

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

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

So SW2 is the reset button and "SW1" is the "FLASH" button. To enter the bootloader mode in which the ESP8266 can be programmed, you first have to hold down the "FLASH" button then press "RESET" once.

For programming you would ideally get a 5V USB-UART adapter make the connections

* VCC to 5V (it has a regulator to generate the actually needed 3.3V)
* GND to GND
* EN to 5V (e.g. via a pullup)
* TXD to RX of UART adapter
* RXD to TX of UART adapter

After the ESP is in the bootloader mode as described above, you can just program it normally through the Arduino IDE. Follow the instructions at https://github.com/esp8266/Arduino to install the ESP8266-Arduino core in the board manager.

Refer to the similiar procedure:

* https://www.hackster.io/harshmangukiya/program-esp8266-esp-12e-with-arduino-using-ftdi-cable-2310c9

  [1]: https://i.stack.imgur.com/WafXX.png
  [2]: https://i.stack.imgur.com/bR51C.png


message:
Help - Atmega328p, converting a PWM servo code from pin9 to pin6

I found a working code that uses pin9 (PB1) on my Arduino for controlling a Servo, but in my project, an ultrasonic sensor is already using that pin/timer. I want to convert the code to use pin6 (PD6), changed the registers according to the atmega's datasheet, but it doesn't work. Need help :/

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

The code should allow me to turn a servo using a potentiometer.

    #define F_CPU 16000000 //16MHz
    #include <avr/io.h>
    #include <util/delay.h>
    #include <avr/interrupt.h>
    #include <stdlib.h>

    #define PWM_PRESCALLER 64
    #define ICR_MAX (long double)F_CPU/PWM_PRESCALLER/50
    #define OCR_MIN (float)ICR_MAX/37.5 // /8.75
    #define OCR_MAX (float)ICR_MAX/8.7 // 37.5

    volatile unsigned long adc_val=0;
    volatile unsigned long counter=0;
    unsigned long curr_adc=0;

    ISR (ADC_vect)
    {
    adc_val += ADC;
    counter++;
    }

    int main(void)
    {
        DDRD |= (1<<DDD6);
        ICR1 = ICR_MAX;
        OCR0A = OCR_MIN;
        TCCR0A = (1 << COM1A1) | (1<<WGM00) | (1<<WGM01);
        TCCR0B = (1<<WGM02) | (1<<CS01) | (1<<CS00);
        ADMUX = (1 << REFS0);
        ADCSRA = (1 << ADEN)|(1 << ADATE)|(1 << ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);

        sei();
        ADCSRA |= (1<<ADSC);

        while(1)
        {
            if(counter >= 1000)
            {
                cli();
                unsigned long round_val = round(adc_val / counter);
                adc_val=0;
                counter=0;
                if(abs(round_val - curr_adc) > 1)
                {
                    curr_adc = round_val;
                }
                long double ocr = OCR_MIN + ((long double)curr_adc * (OCR_MAX - OCR_MIN)/1024);

                OCR0A = (int)round(ocr);
                sei();
            }
        }
    }

body: PORTB bit 6 is controlled with TIMER0 while PORTB bit 1 is controlled with TIMER1.  Therefore you need to change the timer variables appropriately.  One mistake in your code is that you leave ICR1.  It should be OCRA if you want to use TIMER0.