body:
    void writereg() {
      digitalWrite(latchPin, LOW);
      for (int i = 7; i >= 0; i--) {
        digitalWrite(clockPin, LOW);
        Serial.print("wswitch&&&&&&");
        Serial.print(i);
        Serial.print("----------------------");
        digitalWrite(dataPin, switches[i].stat);
        Serial.println(switches[i].stat);
        digitalWrite(clockPin, HIGH);
      }
      digitalWrite(latchPin, HIGH);
      touched = false;
    }

I don't understand what's wrong with what I'm doing here, but this for loop runs into an almost infinite loop and prints crazily. I'm a newbie to electronics and Arduino and I don't understand what's wrong here. Please help.

This is my switch class:

    struct Swtch
    {
      int num;
      bool stat;
      bool touched;
    };

    Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

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

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

title: for loop running infinitely

Answers: 3

body:
Like [jfpoilpret](https://arduino.stackexchange.com/questions/48311/for-loop-running-infinitely#comment96255_48311) said, it looks like `i` is being treated as an `unsigned char` or `uint8_t` causing it to never go below zero. Instead it wraps around to 255, the max value of an 8-bit unsigned integer, as you can see in line 9 of your output. The condition to remain in the loop is `i >= 0` which means the loop will never exit. A solution is to add a case for if `i` is above the starting value:

```for (int i = 7; i >= 0 && i <= 7; i--) {
```

I would recommend finding out why `int` is being treated as `uint8_t` for any future projects

body:
After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.

This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).

Heavy use of `String` variables is a likely explanation for the observed behavior.
Also a lot of string literals are putting more pressure on memory in the OP program.

Here are my suggestions:

1. Replace all `"..."` string literals with flash-stored strings with `F("...")`. That will reduce the initial SRAM size used.
2. Replace all `String` variables with pure C-string (`char*` and char arrays) and use standard C string functions such as `strcpy`, `strcat`, `strlen`, `strcmp`, `strchr`... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
3. Use `const` whenever possible (instead of variables that waste memory)
4. Use the smallest type needed for each variable, e.g. avoid `int` (2 bytes) when you need to store a boolean value, prefer `bool` type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.

body:
I have noticed that you have incorrectly declared the switches array.

Your code:

    struct Swtch
    {
      int num;
      bool stat;
      bool touched;
    };

    Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

It should be:

    struct Swtch
    {
      int num;
      bool stat;
      bool touched;
    };

    struct Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

Alternatively, you could make a typedef struct:

    typedef struct
    {
      int num;
      bool stat;
      bool touched;
    }Swtch;

    Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

References:
https://stackoverflow.com/a/32185804/6075112
https://overiq.com/c-programming/101/array-of-structures-in-c/#initializing-array-of-structures
https://stackoverflow.com/a/3275389/6075112


body:
I ran into a strange problem were the compiler could not find a header file that I knew existed.

The problem was I created a class called ArduinoEvent and put it in ArduinoEvent.hpp,  but when I tried to include it in a client file, the compiler complained that the file did not exist.

    In file included from sketch/NetworkConnection.hpp:4:0,
                     from /home/john/development/arduino/esp_pump_monitor/app.ino:4:
    sketch/MyEvent.h:5:28: fatal error: ArduinoEvent.hpp: No such file or directory
     #include "ArduinoEvent.hpp"
                                ^

After realizing that the compiler copies the files into another directory,  I took a look and found that it had copied the `ArduinoEvent.hpp` file to
`ArduinoEvent.hpp.cpp`.  Since all the other files were copied fine, I simply renamed the file to `BrduinoEvent.hpp` and then everything was fine.

After searching I could not find anything that would imply that I could not name a class / file ArduinoBlah, so I was going to open an issue, but wanted to see if this restriction was documented somewhere and I just could not find it.

Update
------
I originally _assumed_ the problem was due to the file being called ArduinoXxxx, but I hit this again with another file.  I think the issue is related to the files being in the "top" folder.  I noticed the process copies the xxx.ino files to xxx.ino.cpp,  so I think that's what is happening and somehow it thinks various files are .ino files while they are not.  As a workaround I moved all my class files to a `lib` folder and include them from there `#include "./lib/xxx.hpp"` for example.  This seems to be working.

title: Are there documented Arduino class or file name restrictions?

Answers: 0


body:
I am as new to Arduino as it can get. To start off, I am trying to build a DAC using an Arduino Leonardo. I have a digital signal coming from my dual differential comparator. I want to convert this to an analog signal.

First, I will read the digital signal in a digital pin (can someone point me which is good? There are so many of them. I was overwhelmed). Then I send out a PWM signal (confused with the pin again). Then I use a simple RC circuit to filter out the PWM signal to produce a simple sine wave.

Am I going towards the correct direction? If not, please any suggestion would be helpful.

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

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

title: DAC using Arduino Leonardo

Answers: 1

body:
Yes you are going in the right direction.

**Comparators**
You haven't as yet detailed how you plan to connect the 2 comparators to the Arduino, but I imagine it would be something similar to 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/5ELsW.png)

<!-- End schematic -->

In the circuit above, X and Y are either high or low based on the analog voltages of A, B, C & D. I have created a truth table below with some arbitrary voltages to output. The `value` column corresponds to the value needed for the [`analogWrite()`][1] function.

[![truth table][2]][2]

Note: If you need your analog output to be able to source some current you can add an Op-Amp in a [unity gain][3] configuration at the output of the RC filter.

----------

**Examples To Read**
To output the analog value, the 4 best suited inbuilt examples/tutorials to look at are:

[Dimmer][4]: Send serial values to change the brightness of an LED.
[Fading][5]: Use an analog output (PWM pin) to fade an LED.
[Analog In Out Serial][6]: Read an analog input pin, map the result, and then use that data to dim or brighten an LED.
[Read ASCII String][7]: Parse a comma-separated string of integers to fade an LED.

What all of these examples have in common is the [`analogWrite()`][1] function:

    // writes the analog value (range from 0 to 255):
    analogWrite(pin, value);

*Dimmer* is a simple example where a serial value is read and then output on one of the PWM pins.
*Fading* is probably the most basic example of using the [analogWrite()][1] function (PWM output).
I included *Analog In Out Serial* as it uses the [map()][8] command.
I included *Read ASCII String* as it shows how to parse multiple values on the serial string.

----------

**PWM Pins**
You can use pins 3, 5, 6, 9, 10, 11, and 13 on the Arduino Leonardo to output the PWM using the [`analogWrite()`][1] function.

----------

**Control**
I recommend the following tutorials for your control. You could either use the [if][9]-[else][10] command or the [switch-case][11] command.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
  [2]: https://i.stack.imgur.com/DNf0h.png
  [3]: https://en.wikipedia.org/wiki/Buffer_amplifier#Op-amp_implementation
  [4]: https://www.arduino.cc/en/Tutorial/Dimmer
  [5]: https://www.arduino.cc/en/Tutorial/Fading
  [6]: https://www.arduino.cc/en/Tutorial/AnalogInOutSerial
  [7]: https://www.arduino.cc/en/Tutorial/ReadASCIIString
  [8]: https://www.arduino.cc/reference/en/language/functions/math/map/
  [9]: https://www.arduino.cc/reference/en/language/structure/control-structure/if/
  [10]: https://www.arduino.cc/reference/en/language/structure/control-structure/else/
  [11]: https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/


body:
First-time poster here...

I have the following code to randomize note values and store them in an array `loop1[i]`, where `i` is a specific step in the loop:

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

    nextNote = random(-2, 3);
    note = note + nextNote;

    loop1[i] = note;

    while (loop1[i] == loop1[i - 1] ||
           loop1[i] == loop1[i - 2] ||
           note > 6 ||
           note < 0) {
      nextNote = random(-2, 3);
      note = note + nextNote;
      loop1[i] = note;
    }

(I hope this is clear enough).

Now, it usually works to a certain point until the sketch loops forever in order to randomize an allowed number. Therefore, my questions are:

Running an ATmega 2560, is this actually a task too demanding for the processor or should I suspect that it's not working properly?

How can I optimize the code, but retain the conditions above in order to avoid the loop getting stuck?

title: Conditional randomization gets stuck

Answers: 3

body:
Some reasons why it will not work:

- My feeling is that `i` gets too big, i.e. it is higher than the length of the array you are using. That can cause crashes, or at least unpredicted results. You can easily check this by printing the value of `i` (and check against the maximum value).

- I don't see problems with the while loop (although I would use brackets around `note > 6` and around `note < 0`, but I don't think this is really needed.

- If the value gets below 0 or higher than 6, still random values are added, assume the value is +10... then it might take a lot of time (if ever) for that value to reach max 6 again. The same is true for values < 0. Maybe you should never allow values of less than 0 and higher than 6 anyway, or making the random values in such a way they tend to go towards the average (3).

Tip to debug:

However, the easiest way to debug this is to print all relevant variables (e.g. `nextNote`, `note`, `i`, the last two notes `loop[i-2]`, `loop[i-1]` and the current note `loop[i]`... Also print a line inside the while loop so you know when you skip it or not. This probably will give you enough information to see what is wrong.

body:
I think you have a problem with your math here, not with your code. What
you are simulating is very similar to a [1-dimensional random
walk](http://mathworld.wolfram.com/RandomWalk1-Dimensional.html).
According to the linked MathWorld page, for such a process “the most
probable number of sign changes in a walk is 0”.

If, at some point in your program, the loop starts with `note == 6`, and
then it starts randomly going up, there is a sizable probability for it
to never go back to values below 7.

------------------------------------------------------------------------

**Edit**: One possible solution could be to avoid the random-walk notion
and instead repeat the random choice always from the same starting
point.

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

    int oldNote = note;  // starting point
    do
        note = oldNote + random(-2, 3);
    while (
        note == loop1[i - 1] ||
        note == loop1[i - 2] ||
        note > 6 ||
        note < 0);
    loop1[i] = note;

body:
The line `loop1[i] = note` doesn't belong in the loop (or above it); you're not changing `i` in the loop, so you're just rewriting the same location over and over again.

As for the loop itself, what sort of use case do you have for this, and what sort of distribution do you want? Waiting until it's between 0 and 6 is horribly inefficient. You need to decide what sort of distribution you want and implement it more directly. For instance, you could have a piecewise quadratic distribution by getting a random number between zero and sqrt(3), then squaring the result, and then randomly choosing whether to subtract the result from 6.


body:
I am very new to Arduino Programming.
I am trying to identify the input string from serial monitor and printing the output to the console accordingly

Code is :

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

    void loop() {

       while (Serial.available() > 0 ) {

         String str = Serial.readString();

         if (str.equals("send")) {
            Serial.println("identified");
         } else {
            Serial.println("unknown");
         }

       }

    }

Whenever i put send string it is showing "unknown" as the output, which is wrong, and i should get "identified" as the output.
Can anyone guide me here to achieve the result.

Note : I am getting output as i wanted by using readStringUntil function but the strings has a lot of "." in it, hence not useful.

title: Very Basic Arduino Uno Serial.readString() operation

Answers: 3

body:
There are any number of reasons the *.equals test is false. Consider case difference or extra characters introduced from the source of your communications.  Even non printable characters may pose a problem and cause the test to fail.

Consider using [*.substring()][1] instead.  This method will return true if the substring is found.  For example:

      String stringOne = "12345 send 1234";

      // substring(index) looks for the substring from the index position to the end:
      if (stringOne.substring(0) == "send")
      {
        Serial.println("identified");
      }
      else
      {
        Serial.println("unknown");
      }

...should always return "identified" because the characters 's', 'e', 'n' and 'd' are found in the correct sequence within the string stringOne.

  [1]: https://www.arduino.cc/en/Tutorial/StringSubstring

body:
If you set your Serial Monitor's line ending to "Both NL & CR", then this code will find the word "send". It will NOT find the word "send" in this string, "ssend" or in this string, "sendd".

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

    void loop(){
      while(Serial.available() > 0 ){
        String str = Serial.readString();
        if(str.substring(0) == "send\r\n"){
          Serial.println("identified");}
        else{
          Serial.println("unknown");
        }
      }
    }

If you want to find the string "send" in "1234send" or "send1234" or "1234send5678" then use indexOf();

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

    void loop(){
      while(Serial.available() > 0 ){
        String str = Serial.readString();
        if(str.indexOf("send") > -1){
          Serial.println("identified");}
        else{
          Serial.println("unknown");
        }
      }
    }

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

    void loop() {
       char inChar[5];

       if(Serial.available() > 0 )
       {
         for (int i=0; i<5; i++)
         {
          inChar[i] = Serial.read();
          delay(10);
         }

         if (inChar[0] == 's' && inChar[1] == 'e' \
                              && inChar[2] == 'n' \
                              && inChar[3] == 'd')
             {
              Serial.println("identified");
             }

         else
         {
           Serial.println("unknown");
         }
      }
    }


body:
So, the basic idea is that user presses a key on keypad, and key that is pressed is sent with RF transmitter.
I got individual parts to work(keypad and transmitter), but can't send the actual key. When I try to send it, I get a strange string on the other end. I am convinced its simple issue with my syntax, so if anyone could help me, that would be great. Code is below:

    #include <RH_ASK.h>
    #include <SPI.h> // Not actually used but needed to compile
    RH_ASK driver; //use this driver for transmitter

    #include <Keypad.h>
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };
    byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void setup()
    {
        Serial.begin(9600);   // Debugging only
        if (!driver.init())
             Serial.println("init failed");
    }

    void loop()
    {

        char key = keypad.getKey();

        if (key){
          Serial.println(key);//outputs correct key
          //transmitter part
    //      const char *msg = "Hello World!";
          const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
          driver.send((uint8_t *)msg, strlen(msg));
          driver.waitPacketSent();
          Serial.println(key);//outputs correct key
          Serial.println("packet_sent");
        }
    }

title: Arduino keypad and RF 433MHz transmitter problem

Answers: 1

body:
The problem is you send a character of type char, thus exactly one byte.
However, when you send it you have to give the length and you use strlen. However, msg is an array (at least that is what you want), but that array contains only the character to sent. What you want is to send only 1 character, so use 1 instead of strlen.

Also, you can get rid of the special msg pointer and instead of

      const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
      driver.send((uint8_t *)msg, strlen(msg

use

      driver.send(&key, 1);

Where &key defines the address (pointer to) key, and since there is always exactly 1 byte in key (the key itself), 1 can be used. To be more safe, you can use sizeof(key) thus

      driver.send(&key, sizeof(key));

What you also can do is create a string that ends with \0, so the first is the character to send, and strlen can be used, but the easiest way is to set the length to exactly 1.

Actually, using strlen on a string that does not end with \0 can result in strange behavior, because maybe there is no \0 in memory.


body: Hello I want to get an arduino get status of bluetooth hc 05 if connect with device or not . I'm trying by myself and search on internet website but I can't find useful things.

title: Arduino reads hc-05 device connecting status

Answers: 2

body:
In hc05 there is led that shows you Bluetooth is paired or not. In datasheet it says that connected the PIO9 pin. You can connect this pin to arduino's digitial input pin. After that you can understand is it paired or not.

`AT+BIND? ` gives you which device you currently paired.

body:
Different Bluetooth adapters (using the HC-05 module) provide different signals, besides its Rx and Tx. Most bring out a "key" input that puts the module into command mode where serial communication is between the external pins and the module itself - 'AT' commands & queries to the module's firmware. When the module is not in command mode, the firmware just passes serial data through the Bluetooth radio, ignoring the content. Some provide an LED- or State signal that you can read (or observe on an LED) to know whether the devices is paired (communicating) or unpaired (in command mode).

On some, this is a simple logic signal; on others it is a square wave of 1/2 to 1 Hz which means your code has to track the signal to know whether it is static (typically High when paired) or toggling (for unpaired/waiting to pair).

You need to read your module's datasheet to find out the behavior of this signal on your particular module. If you connect an LED to this signal, or your module has one on the board, you can often make a good enough guess by observing it with a stopwatch. Either way, you then need an Arduino function that samples the LED periodically, remembering what state it saw and for how long, to decide whether the LED is blinking or is steady.


body:
I am making a security system, and the alarm starts when the button gets pressed. If i turn the alarm off by the serial communication, and want to turn it on again using the button, it will only let the alarm go on for about 0.5 seconds. Does someone see the mistake i'm making, and can help me? Thanks in advance!

    const int ledrood = 11;
    const int ledgroen = 12;
    const int buttonPin = 2;
    int buttonState = LOW;

    int statePin = LOW;
    const int trigPin = 9;
    const int echoPin = 10;
    long duration;
    int distance;
    bool alarm = false;
    int speakerPin = 8;
    String Message = "";
    String NMessage = "";
    String Command = "";
    int index = 0;
    bool Bericht = true;

    void PlaySong()
    {
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
    }
    void alarmaan()
    {
     alarm = true;

      digitalWrite(ledrood, HIGH);
      digitalWrite(ledgroen, LOW);
      digitalWrite(trigPin, LOW);

     }

    void AlarmUit() {
      Serial.println("alarm uit");
      alarm = false;
      digitalWrite(ledgroen, HIGH);
      digitalWrite(ledrood, LOW);
      digitalWrite(trigPin, LOW);

     }
    void setup() {
      pinMode(ledrood, OUTPUT);
      pinMode(ledgroen, OUTPUT);
      pinMode(buttonPin, INPUT);
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600);
     }
    String Doorsturen() //Methode om te communiceren via de serial monitor
    {
     if (Serial.available() > 0)
      {
       char readChar = (char) Serial.read();
       NMessage = NMessage + readChar;
      }
      if (NMessage.startsWith("#") && NMessage.endsWith("%"))
      {
       index = NMessage.indexOf("%");
       NMessage = NMessage.substring(1, index);
       Serial.println(NMessage);
       Command = NMessage;
       NMessage = "";
       Bericht = true;
      }
      else if (NMessage.endsWith("%"))
     {
       NMessage = "";
     }
     return Command;
    }
    void loop() {
     Message = Doorsturen();
     int buttonState = digitalRead(buttonPin);
     digitalWrite(trigPin, HIGH);
     digitalWrite(trigPin, LOW);
     duration = pulseIn(echoPin, HIGH);
     distance = duration * 0.034 / 2;
     Serial.print("Distance: ");
     Serial.println(distance);

     if (alarm == false) {
       digitalWrite(ledgroen, HIGH);
     }

     if (Message == "alarm_off")
     {
       AlarmUit();
       Message = "";
     }
      if (Message == "1234")
      {
       AlarmUit();
       Message = "";
      }
      if (Message == "aan") {
       alarmaan();
       Message = "";
       }

      if (alarm == false) {
       if (buttonState == HIGH) {
        delay(50);
        while (digitalRead(buttonPin) == HIGH) {}
        alarmaan();
        Serial.println("fout");
       }
      }

      if (distance < 10 && alarm == true) {
       PlaySong();
      }

     if (alarm == true) {
       if (buttonState == HIGH) {
        delay(50);
        while (digitalRead(buttonPin) == HIGH) {}
        alarmaan();
        Serial.println("Test");
       }

     }
    }

title: How to make a button work a second time in my code?

Answers: 1

body:
The problem is that `Message = "";` doesn't actually do anything, because the next time `doorsturen` is called, it will just load the previous command from the `command` variable. I'd suggest having the `doorsturen` function only return the command once, and not on consecutive calls.

    String Doorsturen() //Methode om te communiceren via de serial monitor
    {
      Command = "";
      if (Serial.available() > 0)
      {
        char readChar = (char) Serial.read();
        NMessage = NMessage + readChar;

        if (NMessage.startsWith("#") && NMessage.endsWith("%"))
        {
          index = NMessage.indexOf("%");
          NMessage = NMessage.substring(1, index);
          Serial.println(NMessage);
          Command = NMessage;
          NMessage = "";
          Bericht = true;
        }
        else if (NMessage.endsWith("%"))
        {
          NMessage = "";
        }
      }
      return Command;
    }

<strike>
see comment in the code

    if (alarm == false) {
      if (buttonState == HIGH) {
        //here you set alarm to true
      }
    }

    ...

    if (alarm == true) { //now this if statement is true
      if (buttonState == HIGH) {//also buttonState is still high, because it's never updated after you set alarm to true

      }

to fix do this

    if (alarm == false) {
       if (buttonState == HIGH) {
        delay(50);
        while (digitalRead(buttonPin) == HIGH) {}
        delay(50);// this is to negate switch bounce, on release, from interfering
        buttonState = false;// add this line
        alarmaan();
        Serial.println("fout");
       }
      }

</strike>


body:
I'm new to using the serial monitor. I have a code set up so that LEDs turn on when I type an input on the keyboard. I know how to turn them off using a keyboard but I and can't figure out why the leds won't turn off when I press a push button.

        #define led1 10 //10th,
        #define led2 11 //11th
        #define led3 12 //12th
        #define led4 13 //13th
        #define ButtonA 9

        int ButtonState;
        int ButtonState2;
        int state;
        int StateNow;
        int PreviousState = HIGH;

        void setup(){
          pinMode(led1,OUTPUT);
          pinMode(led2,OUTPUT);
          pinMode(led3,OUTPUT);
          pinMode(led4,OUTPUT);
          pinMode(ButtonA,INPUT_PULLUP);
          Serial.begin(9600);
          Serial.println("Enter ch a, b, c, or d:");
        }

        void loop() {
        if (Serial.available())
        {
          ButtonState = digitalRead(ButtonA);
          delay(10);
          ButtonState2 = digitalRead(ButtonA);  //debounce
          if (ButtonState != ButtonState2)
          {
            StateNow = ButtonState2;
          }
          else
          {
            StateNow = ButtonState;
          }
          if(StateNow == LOW && PreviousState == HIGH)
      {
        digitalWrite(led1,LOW);
        digitalWrite(led2,LOW);
        digitalWrite(led3,LOW);
        digitalWrite(led4,LOW);
        Serial.println("Turned off all LEDs");
        PreviousState = LOW;
      }
      else if(StateNow == HIGH && PreviousState == LOW)
      {
        PreviousState = HIGH;
      }
      state = Serial.read();
      if (state == 'a' || state == 'A')
      {
        digitalWrite(led1,HIGH);
        Serial.println("Turned on led 1");
      }
      else if (state == 'b' || state == 'B')
      {
        digitalWrite(led2,HIGH);
        Serial.println("Turned on led 2");
      }
      else if (state == 'c' || state == 'C')
      {
        digitalWrite(led3,HIGH);
        Serial.println("Turned on led 3");
      }
      else if (state == 'd' || state == 'D')
      {
        digitalWrite(led4,HIGH);
        Serial.println("Turned on led 4");
      }
    }

    }

The LEDs turn on properly and I know the circuit is wired correctly so it's definitely something I'm missing in the software

title: Basic Arduino Question. Trying to turn off leds turned on through the serial monitor by using a push button

Answers: 1

body:
To turn off all leds when button is pressed, you must detect a rising or falling in the button signal.

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

In your code you detect the change only if serial is available, but you should do it in the loop.

The simple way to detect the change is doing this in every loop:

    if (StateNow != PreviousState) {
      if (StateNow == LOW && PreviousState == HIGH) //button pushed
      {
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        digitalWrite(led3, LOW);
        digitalWrite(led4, LOW);
        Serial.println("Turned off all LEDs");
      }
      PreviousState = StateNow;
    }

I simplify your code and add some comments:

    #define led1 10 //10th,
    #define led2 11 //11th
    #define led3 12 //12th
    #define led4 13 //13th
    #define ButtonA 9

    int state;
    int StateNow;
    int PreviousState;

    void setup() {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(ButtonA, INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("Enter ch a, b, c, or d:");
      PreviousState = digitalRead(ButtonA);
    }

    void loop() {
      //detect changes in button signal to turn off leds
      StateNow = digitalRead(ButtonA);
      if (StateNow != PreviousState) {
        if (StateNow == LOW && PreviousState == HIGH) //button pushed
        {
          digitalWrite(led1, LOW);
          digitalWrite(led2, LOW);
          digitalWrite(led3, LOW);
          digitalWrite(led4, LOW);
          Serial.println("Turned off all LEDs");
        }
        PreviousState = StateNow;
      }

      //check serial biffer to turn on leds
      if (Serial.available())
      {
        state = Serial.read();
        if (state == 'a' || state == 'A')
        {
          digitalWrite(led1, HIGH);
          Serial.println("Turned on led 1");
        }
        else if (state == 'b' || state == 'B')
        {
          digitalWrite(led2, HIGH);
          Serial.println("Turned on led 2");
        }
        else if (state == 'c' || state == 'C')
        {
          digitalWrite(led3, HIGH);
          Serial.println("Turned on led 3");
        }
        else if (state == 'd' || state == 'D')
        {
          digitalWrite(led4, HIGH);
          Serial.println("Turned on led 4");
        }
      }
    }

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


body:
I am trying to measure AC power using an Arduino with an Atmega328p.
In summary, I want to use timer1 to make an interrupt every 400us where I measure two ADC channels (A0 and A1) and put them into an array. The problem is that instead of measuring five mains periods (mains frequency = 50Hz so 20ms * 5), I get instead 13 of these periods (260ms). What am I doing wrong?

    volatile int sample_incremental = 0;

    void setup() {
          Serial.begin(115200);
          pinMode(voltagePin, INPUT);
          pinMode(currentPin, INPUT);
          set_sample_interrupt();
          sei();
        }

    void set_sample_interrupt() {
      //Count to 400us
      OCR1A = 99;
      //Mode 4, CTC
      TCCR1B |= (1 << WGM12);
      //Enable interrupt
      TIMSK1 |= (1 << OCIE1A);
      //Prescaler 64
      TCCR1B |= (1 << CS11) | (1 << CS10);
    }

    ISR (TIMER1_COMPA_vect) {
      // action to be done every 400 usec
      current_sample[sample_incremental] = analogRead(currentPin) - 504;
      voltage_sample[sample_incremental] = analogRead(voltagePin) - 512;
      if (sample_incremental < (SAMPLES * PERIODREADS))
        sample_incremental++;
      else {
        //Disable interrupt
        TIMSK1 &= ~(1 << OCIE1A);
        sample_incremental = 0;
        finishedReading = true;
      }
    }

Where after I do one reading, I stop the interrupt, and SAMPLES * PERIODREADS = 250.

title: ATMega328p (Arduino) Timer1 set-up

Answers: 1

body:
The Arduino core library configures the Timer 1 for phase-correct PWM at
about 490 Hz. Then you are setting some configuration bits in the
timer's control registers without clearing the bits that had previously
been set by the Arduino core. If you want to use the timer for your own
purposes, and configure it by yourself, you should completely overwrite
the core's configuration with your own. For that, use the `=` operator
rather than `|=`, as in:

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

    OCR1A  = 99;                         //Count to 400us
    TIMSK1 = (1 << OCIE1A);              //Enable interrupt
    TCCR1A = 0;
    TCCR1B = (1 << WGM12)                //Mode 4, CTC
           | (1 << CS11) | (1 << CS10);  //Prescaler 64


body:
I am not getting any compile time error. After some samples of data `void loop()` stops executing. Please let know what the problem is. Below is my code.

Thanks and regards
Thippeswamy

    #include<SPI.h>
    float amplitude=1.5;
    int freq1=20; int freq2=12;
    int k=20;float A= amplitude*k;
    int Fs=10550; float sine[5000]; float Fs1=3000;
    int i=0;int reg1=1; int reg2=0;
    int sample1=Fs/freq1; float sample2=Fs1/freq2;

    void setup() {
      int SS=10;
      pinMode(SS, OUTPUT);
      SPI.begin();
    }

    void data(int reg, int data) {
      digitalWrite(SS,LOW);
      SPI.transfer(reg);
      SPI.transfer(data);
      digitalWrite(SS,HIGH);
    }

    void loop() {
      for(int j=0;j<sample1||i<sample2||i>=sample2);j++) {
        float s=A*sin((2*3.14*freq1*j)/Fs);
        sine[j]=s+190;
        data(reg1,sine[j]);
        if(i<=sample2) {
          float s=A*sin((2*3.14*freq2*i)/Fs1);
          sine[i]=s+190;
          data(reg2,sine[i]);
          i++;
        } else if(i>sample2) {
          float s=A*sin((2*3.14*freq2*i)/Fs1);
          sine[i]=s+190;
          data(reg2,sine[i]);
          i++;
        }
      }
    }

title: Why does void loop() stop after some samples?

Answers: 1

body:
>     float sine[5000]
>     ...
>     sine[j]=s+190;

A float takes 4 bytes. You are allocating 5000 of them which is 20000 bytes. The Uno has 2048 bytes of RAM. Thus you are running out of RAM and overwriting something you shouldn't be.

---

As pointed out on [the Arduino forum](http://forum.arduino.cc/index.php?topic=520194), your `for` loop which tests for:

    i < sample2 || i >= sample2

will always be true. Of course `i` will be *either* **less than** or **greater than or equal to** `sample2`.


body:
It's my understanding that the following lines are equivalent. They seem to be interchangeable in my sketch:

    DDRB = 1<<DDB0;

and

    pinMode(0, OUTPUT);

Is the first form (`DDRB...`) setting a micro-controller address directly? Is that assembler?

And is the second form (`pinMode`) using an included library? Maybe the `avr/io.h` library?

*On a Digispark ATTiny85*.

title: What's the difference between DDRB and pinMode?

Answers: 2

body:
> DDRB

is a register. Exactly: Port B Data Direction Register. See [datasheet][1] for ATtiny, chapter 10.4. Register Description and 10.2.1 Configuring the Pin. This part will explain why

> DDB0

 value was used.
Using this way of setting direction of a pin is much faster than  `pinMode(0, OUTPUT); `
The possible problem is when you want to use same code to program different Arduino. In this case you have to remember to check all direct registers operations.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

body:
Yes, on a simple microcontroller like the ATTiny the two lines of code are equivalent.  The function `pinMode(...)` just looks up what pins relate to what ports in a table and set the right registers.

Using `DDRB` instead of `pinMode(...)` is fine as long as you are never going to run your code on anything else (or give it to anyone else to run), since you have now hard coded into your sketch what pins are to be used. It is more efficient to use `DDRB` though. You sacrifice portability for efficiency.

However, for more complex microcontrollers that have many many functions on a single pin, just manipulating `DDRB` (or the equivalent on the target microcontroller) may not be enough. You may need to switch the pin into GPIO mode, disable analog inputs on the pin, or other operations as well. All that will be wrapped up in the `pinMode(...)` function for you by the Arduino API so you don't need to worry about it.

So, in short, if you don't care about portability, and you do care about efficiency and code size (which may well be the case on an ATTiny) then yes use `DDRB` and its friends.


body:
What I know from my search on the internet, for both **SPI** and **I2C** protocols, communication between multiple devices needs a master, which initiates the communication, and slaves, which respond to the master's request. Basically slaves can't initiate a transfer.

Is there any way to make different devices communicate on their will? I'm not sure about **UART**, but I think the story is the same here. But I know that it is possible to use a USB hub to connect multiple USB devices to one port on the computer. How can that be done? Can I use the same principle with Arduino?

To clarify what I want to do, consider that I have different modules (might be Arduinos) with different characteristics. I want to connect them on a bus line to a master Arduino. The module connections should be indifferent so that the user doesn't have to worry about which port should be used to connect the module. For this reason, using an Arduino Mega with more serial interfaces doesn't solve the problem, because we don't know which device is connected to which port.

title: Serial communication between multiple devices (or Arduinos)

Answers: 3

body:
I2C protocol has Multi-master Arbitration Support, i.e. any I2C device can be master and slave. I2C is a multimaster bus
Master start communication, but master device can change. If one device wants to communicate, acts as a master. The problem is that before sending data you must be sure the bus is not busy with other master.

More information: https://www.i2c-bus.org/multimaster/

With UART is not possible to build a bus, only point to point communication.

body:
Almost any serial communication system can be "bent" to make a multi-master system - some easier than others.  The biggest problem you have is that of detecting and handling collisions.

However, if you can get away with a master->slave(s) system whereby one node on your bus makes requests to the slave nodes to get them to do something and respond with information then the whole system is far far simpler.

That is the normal way that I2C and SPI work, although I2C does have multi-master in its specification (though the Arduino API doesn't handle it AFAIK).

The industry standard way of making a UART able to communicate with multiple devices is through converting it to a standard bus system, such as EIA-422 or EIA-485 (AKA RS-422/RS-485). A half-duplex multi-drop EIA-485 is probably the simplest to arrange, and there are breakout boards for the Arduino that will convert UART to EIA-485.

It is possible (if you are clever) to make UARTs directly work as a multi-drop bus, but it requires a deeper understanding of UART control registers and electrical characteristics to emulate either an open-collector or tri-state TX pin on the slaves.

Of course, for all devices to operate on the same bus they must all conform to the specified operation of the bus. For instance, for EIA-485 all the slaves must have the ability to switch the transceiver into TX mode when needed, and react only to requests from the master and never send anything unsolicited. Just hooking random devices up to a bus with a transceiver is never going to work.

As far as USB goes - that is a single master (the PC) and multiple slaves (your keyboard, mouse, printer, scanner, webcam, Arduino, etc). Hubs are just a way of wiring them all together and routing the signals to the different peripherals at the right speeds.

body:
Another option thats possible if you can control the firmware on each node, as in your case with multiple arduino's, is to create a ring bus using UART ports with multiple peers on it where each node would be responsible for forwarding packets to the next node.

The UART rx tz lines for nodes would have to be connected in a ring like this:

 - NodeA Tx => NodeB Rx
 - NodeB Tx => NodeC Rx
 - NodeC Tx => NodeA Rx

This would require design of a somewhat complicated protocol and controlling firmware on each node, and you would need to think through issues like:
1. how many devices can be supported on the ring
2. message size
3. how much memory is available to buffer messages on each node
3. how many message is each node allowed to send
etc.


body:
I'm planning on making a Force Feed Back racing wheel with arduino.Saw a lot of tutorials but it uses brushed DC motors ,couldn't find how to connect dual brushless motor for force feed back.

This the motor I want to use :
http://www.dx.com/p/chrgm25bl2418-dc-brushless-motor-with-built-in-drive-24v-12v-470930#.WkurLcvhVAg

![motor specs](https://i.stack.imgur.com/HET7j.png)
![enter image description here](https://i.stack.imgur.com/9DhdD.png).                       ![enter image description here](https://i.stack.imgur.com/evklR.png).                         ![enter image description here](https://i.stack.imgur.com/x4AfR.png)

title: How to connect dual brushless motors to arduino

Answers: 1

body:
It looks like you provide the correct voltage to the VCC and GND pins to power it, and connect the CW/CCW and PWM (and GND of course) to your Arduino - the first to control the direction, and the second to a PWM pin to control the speed.

You can use the FG pin to monitor the speed from the internal hall effect sensor if you want.


body:
I have the following code:

          uint8_t buf[1];
          uint8_t buflen = 1;
          if (driver.recv(buf, &buflen)) // Non-blocking
             {
                int i;
                // Message with a good checksum received, dump it.
                Serial.print("Message: ");
                Serial.println((char*)buf);//this prints out okay
                highPins[(char*)buf] = 1;
             }
   The problem is in highPins[(char*)buf]. highPins is array, and in (char*)buf I get index number. When I display it with Serial.println, it shows the number, but here it does not. I am guessing its because (char*)buf is not a number. I have tried to convert it to int with few functions I have found online, but it was unsuccessful. Any help is appreciated :)

title: Converting (char*)variable to int

Answers: 2

body:
The function you want is `atoi`.

    int pinno = atoi((char *)buf);

I would suggest checking that the result is in the right range before using it.

body:
I would suggest improving your code slightly as follows:

      uint8_t buf;
      uint8_t buflen = 1;
      if (driver.recv(&buf, &buflen)) // Non-blocking
         {
            int i;
            // Message with a good checksum received, dump it.
            Serial.print("Message: ");
            Serial.println(buf);//this prints out okay
            highPins[buf] = 1;
         }

The important point is that you do not need to declare `buf` as an array of just one element, but just declare the element itself (as `uint8_t`) and pass its address (`&buf`) to `driver.recv(...)`.

As @Majenko suggested, you should alos check `buf` before using it as an index to `highPins` array, in order to avoid using an index bigger than teh array size.


body:
I want to transmit I2C data, using a Digispark ATTiny85 board:

 - http://digistump.com/products/1
 - http://digistump.com/wiki/digispark/tutorials/connecting

I've found the following I2C libraries. Which one is more lightweight, stable, bug-free, efficient, powerful, and easy to use?

 - Adafruit's [TinyWireM][1] has not been updated in 2 years.

 - felias-fogg's [SoftI2CMaster][2] has been updated within days of this post.

 - lucullusTheOnly's [TinyWire][3] represents some years of improvements, "based on the TinyWireM and TinyWireS libraries". This version is recommended by BroHogan, co-creator of TinyWireM:
https://playground.arduino.cc/Code/USIi2c

Wire seems under-featured:

> "the default Arduino Wire() library does not support changes in bus
> speed or feature proper clock stretching support. This makes the
> default library only marginally functional"
> https://www.maxbotix.com/articles/095.htm

What other I2C libs are available for ATTiny? In the IDE i see Digispark SoftSerial, OneWire, and VirtualWire.

How do they all compare?

---------

Note, these other answers do **not** seem relevant to my question:

 - https://arduino.stackexchange.com/questions/34126/whats-the-difference-between-all-the-software-serial-libraries-which-one-is-ar

 - https://arduino.stackexchange.com/questions/11689/alternatives-to-wire-library-for-i2c

  [1]: https://github.com/adafruit/TinyWireM
  [2]: https://github.com/felias-fogg/SoftI2CMaster
  [3]: https://github.com/lucullusTheOnly/TinyWire

title: I2C libraries for ATTiny85?

Answers: 2

body:
>  I want to transmit I2C data...

A little vague.

Transmit to what device? How fast is your data rate (100kHz, 400kHz)? Your only transmitting and not reading anything back? What is the idling voltage of your I2C bus (to then ask if you have chosen correct pull-up resistor values for your intended bus speed)?

You mention that the Wire library doesn't support core clock speed changes without some hacking, but don't talk about the speed you intend to run the microcontroller or how fast you intend to use the I2C. I can guess 400kHz, since you brought up speed, but that's not a great way to answer a question.

I have using the Wire library on an Arduino UNO at I2C bus rate of 100kHz and it's worked fine for my needs. I got bytes in and out.

At this point, the best suggestion I'd have is that if one of the above libraries you listed does not support a feature you'd like, fork it, and add support for your feature yourself. If you're only transmitting to one slave device, then you shouldn't need to worry about bus arbitration, like the [TinyWire][1] does. Adafruit is okay for the most part, but they seem (to me) slow to fix bugs and maintain code. But don't let the code's age get to you. I2C was [created back in 1982][2], and you're still using it... :-P

Here's how I would approach choosing a library:

- Define features you need
- Look for a library which has most of those features
- Add any new features you need
- Possibly share your added features with the community with a [Pull Request][3]

  [1]: https://github.com/lucullusTheOnly/TinyWire
  [2]: https://en.wikipedia.org/wiki/I²C#Revisions
  [3]: https://help.github.com/en/articles/github-glossary#pull-request

body:
[bHogan][1] seems to be the original developer of TinyWireM and TinyWireS.
[Andreas Spiess][2] ("The guy with the Swiss accent") used [rambo's implementation of the TinyWire library][3] for his I2C sensor, and rambo on GitHub and bHogan on arduino.cc seem to be the same person...

I've also used rambo's TinyWire library, and managed to make it work. Adafruits version of TinyWire seems to be a fork of rambo's code.

  [1]: https://playground.arduino.cc/Code/USIi2c/
  [2]: https://www.youtube.com/watch?v=vj0SUYo8f_A
  [3]: https://github.com/rambo/TinyWire


body:
Hello I found an Arduino project that works with serial port parsing and it had very interesting parsing code. I am trying to use it in my project but I still don't understand some lines and what is going there. (I marked them with ???).

    char inData[82]; //create 82 char array
    byte index = 0; //index byte (0 - 255)
    String string_convert; //String
    int PCdata[20]; //int array

    void setup() {
      Serial.begin(9600); //init port
    }

    void loop() {
      parsing(); //loop the function
    }

    void parsing() {
      while (Serial.available() > 0) {
        //while there is data in serial buffer (128 bytes)
        char aChar = Serial.read(); //aChar - current symbol in buffer
        if (aChar != 'E') {
          //if aChar isnt the 'E' (End) symbol do:
          inData[index] = aChar;
          //(inData - array, index - loop № counter) write all Buffer to the array
          index++; //index + 1 - loop count
          inData[index] = '\0';
          //set the next position to '\0' or null symbol
        } else {
          //if aChar or current buffer symbol is 'E' (End) do:
          char *p = inData; //create inData address pointer
          char *str; //create pointer
          index = 0; //set counter to 0
          String value = ""; //create string
          while ((str = strtok_r(p, ";", &p)) != NULL) { //???
            string_convert = str; //???
            PCdata[index] = string_convert.toInt(); //???
            index++; //counter + 1 - loop count
          }
          index = 0; //counter to 0
        }
      }
    }

Thank you for help!

title: Parsing serial port data

Answers: 1

body:
It's parsing a bunch of semi-colon separated data, like "12;34;45;". In each iteration, it converts one value from character representation to its integer value.

`strtok_r` is the reentrant version of `strtok`. On Arduino you simply use `strtok`. Every time you have to parse a string having a list of values separated by some char, you use `strtok`.

# Name

strtok, strtok_r - extract tokens from strings

# Synopsis

    #include <string.h>

    char *strtok(char *str, const char *delim);

    char *strtok_r(char *str, const char *delim, char **saveptr);

The strtok() function parses a string into a sequence of tokens (sub-strings). On the first call to strtok() the string to be parsed should be specified in `str`. In each subsequent call that should parse the same string, `str` should be NULL.

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This token does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.


body:
Arduino `millis()` does not make use of one millisecond interrupt. Instead they make use of 1,024 µsec interrupts and manipulate. Any specific reason why this was implemented this way?

In one case, we can go for timer0 without prescaler and use 1 µsec interrupts. In such case, we have to use CTC mode with `OCR0A=15`. Inside ISR, we could update the microsecond counter and if it reaches 1,000, we could update the msec timer count. Otherwise we could go for directly 1 msec interrupt (maybe using timer0).

I wrote this code to get `micros()` and `millis()`. But there is some issue and I'm not able to get it working correctly.

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

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

    #ifndef F_CPU
    #define F_CPU 16000000UL
    #endif

    volatile uint32_t oneMilliCounter;
    volatile uint32_t oneMicroCounter;
    extern void initializeTimer0CTC_Mode (void);

    extern uint32_t millis(void);
    extern uint32_t micros(void);

    volatile uint32_t oneMilliCounter = 0;
    volatile uint32_t oneMicroCounter = 0;

    uint32_t millis(void) {
      uint32_t value;
      uint8_t sregCopy = SREG;
      cli();
      value = oneMilliCounter;
      SREG = sregCopy;
      sei();
      return (value);
    }

    uint32_t micros (void) {
      uint32_t value;
      uint8_t sregCopy = SREG;
      cli();
      value = oneMicroCounter;
      SREG = sregCopy;
      sei();
      return (value);
    }

    void initializeTimer0CTC_Mode (void) {
      OCR0A = 15; // Set for 1 usec.
      TCCR0A |= 1 << WGM01;  // CTC Mode
      TIMSK0 |= 1 << OCIE0A;
      TCCR0B |= (1 << CS00); // prescaler=1
    }

    ISR(TIMER0_COMPA_vect) {
      static uint32_t prevMicro;
      oneMicroCounter++;
      if (oneMicroCounter - prevMicro >= 1000)   {
        prevMicro = oneMicroCounter;
        oneMilliCounter++;
      }
    }

    int main(void) {
      DDRD |= 1 << PD3;
      initializeTimer0CTC_Mode();
      sei();
      uint32_t prevTime = micros();
      while (1) {
        uint32_t currentTime = micros();
        if (currentTime - prevTime >= 1000) {
          PORTD ^= (1 << PD3);
          prevTime = currentTime;
        }
      }
      return (0);
    }

title: Why doesn't millis() use 1 µsec or 1 msec interrupt?

Answers: 3

body:
One microsecond is only 16 CPU cycles.

The CPU needs 4 cycles to prepare itself for servicing the interrupt
(save the program counter, load the interrupt vector and clear the I bit
in SREG). The interrupt vector itself is a `jmp` instruction that takes
2 cycles. When the ISR is done, it executes the `reti` instruction
(return from interrupt) that takes 4 cycles. This means you have only 6
CPU cycles left for:

* saving the context, i.e. pushing to the stack any register your ISR
  may modify (2 cycles per `push`)
* doing the actual ISR work
* restoring the context (2 cycles per `pop`)
* doing also some useful work in the main program.

There is no way you can do half of this in only 6 cycles.

------------------------------------------------------------------------

**Edit**: I did a couple of experiments to gain more insight on the cost
of running an interrupt too often.

In the first experiment, I used your `initializeTimer0CTC_Mode()`
function to interrupt every microsecond the following program:

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

    // This ISR consists of a sigle `reti' instruction.
    EMPTY_INTERRUPT(TIMER0_COMPA_vect);

    #include <util/delay.h>

    int main(void)
    {
        initializeTimer0CTC_Mode();
        DDRD |= _BV(PD2);       // PD2 = digital 2 as output
        sei();
        for (;;) {
            PIND |= _BV(PD2);   // toggle PD2
            _delay_us(499.75);  // 0.5 ms - 4 cycles
        }
    }

The program is meant to generate a 1 kHz signal on pin 2, and
that's exactly what it does if the `sei();` statement is commented out.
With the `sei();` statement, the frequency drops to 375 Hz. This
shows that processing an empty interrupt (an ISR consisting solely of
the `reti` instruction) costs 62.5% of the CPU power, leaving 37.5% to
the main program. 62.5% is exactly 10 out of every 16 CPU cycles,
which confirms the cycle count of the first part of this answer.

The second experiment was to compile and disassemble your ISR. Here is
what I got:

<!-- language: lang-clj -->

    __vector_14:
        push r1
        push r0
        in   r0, 0x3f  ; 1 cycle
        push r0
        eor  r1, r1    ; 1 cycle
        push r18
        push r20
        push r21
        push r22
        push r23
        push r24
        push r25
        push r26
        push r27
    ; static uint32_t prevMicro;
    ; oneMicroCounter++;
        lds  r24, 0x0104
        lds  r25, 0x0105
        lds  r26, 0x0106
        lds  r27, 0x0107
        adiw r24, 0x01
        adc  r26, r1    ; 1 cycle
        adc  r27, r1    ; 1 cycle
        sts  0x0104, r24
        sts  0x0105, r25
        sts  0x0106, r26
        sts  0x0107, r27
    ; if (oneMicroCounter - prevMicro >= 1000)   {
        lds  r24, 0x0104
        lds  r25, 0x0105
        lds  r26, 0x0106
        lds  r27, 0x0107
        lds  r20, 0x0100
        lds  r21, 0x0101
        lds  r22, 0x0102
        lds  r23, 0x0103
        sub  r24, r20   ; 1 cycle
        sbc  r25, r21   ; 1 cycle
        sbc  r26, r22   ; 1 cycle
        sbc  r27, r23   ; 1 cycle
        cpi  r24, 0xE8  ; 1 cycle
        sbci r25, 0x03  ; 1 cycle
        cpc  r26, r1    ; 1 cycle
        cpc  r27, r1    ; 1 cycle
        brcs 0f  ; 1 cycle if the if() condition is true, 2 otherwise
    ;   prevMicro = oneMicroCounter;
        lds  r24, 0x0104
        lds  r25, 0x0105
        lds  r26, 0x0106
        lds  r27, 0x0107
        sts  0x0100, r24
        sts  0x0101, r25
        sts  0x0102, r26
        sts  0x0103, r27
    ;   oneMilliCounter++;
        lds  r24, 0x0108
        lds  r25, 0x0109
        lds  r26, 0x010A
        lds  r27, 0x010B
        adiw r24, 0x01
        adc  r26, r1    ; 1 cycle
        adc  r27, r1    ; 1 cycle
        sts  0x0108, r24
        sts  0x0109, r25
        sts  0x010A, r26
        sts  0x010B, r27
    ; } }
    0:
        pop  r27
        pop  r26
        pop  r25
        pop  r24
        pop  r23
        pop  r22
        pop  r21
        pop  r20
        pop  r18
        pop  r0
        out  0x3f, r0  ; 1 cycle
        pop  r0
        pop  r1
        reti           ; 4 cycles

Unless otherwise noted in comments, every instruction of this listing
takes 2 cycles to execute. Note the large number of CPU registers saved
(`push`) and restored (`pop`), and the large number of SRAM accesses
(`lds` and `sts`): three 4-byte variables read and written back.
Counting the total number of cycles taken by this ISR is left as an
“exercise to the reader”.

body:
Using CTC mode would mean you can't use pin 9 as a PWM pin anymore.

Also, setting `OCR0A` to 15, would mean PWM on pin 10 could only have 15 different PWM values.

So, in essence, pins 9 and 10 can't be used for PWM.

body:
Even if you could do what you are proposing, which you can't (see Edgar Bonet's excellent answer), imagine the performance hit running an interrupt *every single microsecond* would have on your code.

Every interrupt takes time away from your code.

Let's crunch some more numbers. If you wanted the millis/micros interrupt to take no more than 1% of the processing time, so it has no noticeable impact on your running code it would have to execute for only 10ns.  That's 1% of 1000ns, or 0.000001 x 0.01.

Now assume it takes 50 clock cycles for a highly optimised version of your function to operate. That's a conservative estimate. That includes the time taken to prepare for, call and return from the interrupt.

For both those to hold true you would have to be able to execute 100 x 50 instructions in a microsecond. (To fill your 1uS you should be able to run your 1% interrupt 100 times, yes?) That's 5,000 x (1/0.000001) instructions per second, or 5,000,000,000 instructions per second.

Assuming a single clock cycle for each instruction, that means your chip would have to be running at 5GHz...!

Can you see the problem?

So we scale it back to something more realistic. Maybe a 10% performance hit instead of 1%. How would that be? Well, it's simple enough to say that it would require a chip running at 10% of the speed. 500 x (1/0.000001). So 500MHz.

Still a long long way away from the 16MHz that the Arduino's ATMega runs at.

So you can see the issue.

So we choose close to 1mS instead. That gives a much lower overhead and it's something that the 16MHz Arduino can cope with.

Why 1024 and not 1000? That's simple: 1000 is base 10. We, as humans, with two hands (usually) of (normally) 5 digits on each, love base 10. We thrive in base 10.  However, computers with their 1s and 0s hate base 10. They much prefer working in base 2. It makes arithmetic really easy for them. And in interrupts we want the arithmetic to be easy.

Let's take a quick look at the maths involved and expand out the macros in the code.

Every tick the millis value is increased by `MILLIS_INC`, and any extra is added to a "fractional" count.  What's `MILLIS_INC`? It's:

    #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)

So let's expand that out - what's `MICROSECONDS_PER_TIMER0_OVERFLOW`?

    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

And what's `clockCyclesToMicroseconds`?

    #define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )

What's `clockCyclesPerMicrosecond()`?

    #define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

And, of course, `F_CPU` is (typically) 16,000,000.

So now we can put it all together.

    #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
    becomes:

    #define MILLIS_INC ((clockCyclesToMicroseconds(64 * 256)) / 1000)
    which becomes:

    #define MILLIS_INC (((64 * 256)/clocksPerMicrosecond()) / 1000)

    Which in turn becomes:
    #define MILLIS_INC (((64 * 256)/(F_CPU/1000000L)) / 1000)

    Which finally turns into:
    #define MILLIS_INC (((64 * 256)/(16000000/1000000L)) / 1000)

    So reduce those down a little:
    #define MILLIS_INC ((16384 / 16) / 1000)

    And finally:
    #define MILLIS_INC (1.024)

And since we're talking integers here that is automatically truncated (by the compiler, not at runtime, so it's essentially "free") to 1.

But what about the 0.024ms...? That's simple. The "Fractional" amount is added to another counter - but not as 0.024 - instead as a `FRACT_INC` amount, which is calculated as `((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)`. That's 1024 % 100, or just 24, but then that's right shifted 3 times.  That becomes 3. And when that count hits another limit it loops round and adds one to the millis count.  That limit is `FRACT_MAX`, which is `1000 >> 3` or 125.

All nice and simple and straight forward. Variables, like the fractional count, are kept to just 8 bits (which is what you want on an 8 bit CPU...) and the majority of calculations are done by the compiler, not at runtime by the CPU.  Everything else is simple addition / subtraction and comparisons. Very light. And it runs often enough to be good enough for the majority of uses. And given that, because it's just a timer interrupt and is subject to collision with other interrupts, and can't run when interrupts are disabled, it's only a rough figure anyway. Even the act of reading `millis()` can slow down the counting of milliseconds, since it disables interrupts while the value of the count is retreived (a so called "critical section").

And yes, it could be tweaked to run at precisely 1000uS intervals and do away with the fractional component - but why bother when it's never going to be that accurate anyway? Also the added complexity of calculating what 1000uS is for a timer configuration when you consider the vast array of speeds that Arduinos could potentially run at (16MHz for an Uno, 8MHz for the 3.3V boards, 1MHz for the default internal oscillator...) it's far simpler to say "This is what it ticks at, and this is the number of milliseconds per tick, with this bit left over" which is calculated at compile time, instead of having to work out prescalers and overflow counts, etc.


body:
    // MPU-6050 Short Example Sketch
    // By Arduino User JohnChi
    // August 17, 2014
    // Public Domain
    #include<Wire.h>
    const int MPU_addr=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

    void setup() {
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0); // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
      Serial.begin(9600);
    }

    void loop() {
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
      Serial.print("AcX = "); Serial.print(AcX);
      Serial.print(" | AcY = "); Serial.print(AcY);
      Serial.print(" | AcZ = "); Serial.print(AcZ);
      Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
      Serial.print(" | GyX = "); Serial.print(GyX);
      Serial.print(" | GyY = "); Serial.print(GyY);
      Serial.print(" | GyZ = "); Serial.println(GyZ);
      delay(333);
    }

Serial Monitor output:

    AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
    AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
    […]

title: MPU6050 accelerometer giving output as -1 -1. Can anyone tell the issue in the code?

Answers: 1

body:
I found that there was a communication problem between MPU and Arduino which I found using code given in this link http://playground.arduino.cc/Main/I2cScanner .
Then I found thought problem Must be in MPU or arduino and problem was in Arduino MCU.
So after changing the Arduino MCU it worked


body:
I am trying to learn more about arduino programming, and recently i've written functions for randomizing and then modifying a single array. Now i'd like to do the same for four individual arrays. This is where i'm getting stuck. My questions:

Am i right to assume that it's not possible calling a function for multiple individual arrays?

Perhaps a separate question, but if a class or struct would be more suitable for multiple instances, what are the major differences worth considering to choose the right approach?

title: Function, struct or class?

Answers: 2

body:
> Am i right to assume that it's not possible calling a function for multiple individual arrays?

What would give you that impression?  An array is just a pointer to a block of memory - as such it's just a variable. You can pass as many as you like to a function.

Just remember that a function can't know how big the array is that you pass it, since it only gets the pointer to the start of the array, so you need to pass the size of the array with it. You can't rely on the `sizeof` operator, since that is a compile-time directive that gives the size of a variable, which inside the function will be the size of a pointer (2 bytes on an 8 bit system). It can only give the size of an array (and then only the memory size in bytes, not the count of elements) if its run in the same (or a subordinate) scope as the declaration of the array.

> Perhaps a separate question, but if a class or struct would be more suitable for multiple instances, what are the major differences worth considering to choose the right approach?

A struct is just a way of grouping variables into compound types. Think of them as database records. Great for if you want to keep related, but different, information together in one block.  Classes are the same thing but add functions as well.*

----

* That's a very simplistic description. In actuality you can have functions in structs and not have functions in classes. The real difference between them is how access controls (private/protected/public) are implemented (there is none in structs, and they are all there in classes) and how inheritance / polymorphism works.

body:
Are you trying to use the same function for different arrays at different times, or are you trying to use a function that handles four different arrays at the same time?

If the former, you'd write something like

    void myfunc( T *arr, size_t size ) // where T is the type of the array
    {
      for ( size_t i = 0; i < size; i++ )
        arr[i] = some_new_value();
    }

then call it for each array:

    T arr1[N];  // where T is int, float, double, whatever
    T arr2[M];
    T arr3[O];
    T arr4[P];

    myFunc( arr1, N );
    myFunc( arr2, M );
    myFunc( arr3, O );
    myFunc( arr4, P );

This assumes all the arrays have the same base type (e.g., they're all arrays of `int`).

If you want a function to work on four arrays simultaneously, you'd write it as

    void myFunc( T *a1, size_t a1_size,
                 T *a2, size_t a2_size,
                 T *a3, size_t a3_size,
                 T *a4, size_t a4_size )
    {
      // code for handling each array
    }

While I wrote it such that all the arrays have the same type, it doesn't have to be this way.  Each array can be a different type (`a1` can be `int`, `a2` can be `double`, etc.).


body:
I want to easily send a number from a phone to my esp8266.
I have an app that sends the number in the format IP/number.
How can I modify the code to give my the number behind the IP address as an integer?

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

    MDNSResponder mdns;

    // Replace with your network credentials
    const char* ssid = "YOUR_SSID";
    const char* password = "YOUR_PASSWORD";

    ESP8266WebServer server(80);

    String webPage = "";

    void setup(void){

      delay(1000);
      Serial.begin(115200);
      WiFi.begin(ssid, password);
      Serial.println("");

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

      if (mdns.begin("esp8266", WiFi.localIP())) {
        Serial.println("MDNS responder started");
      }

      server.on("/", [](){
        Serial.println("device connected");
      });
      server.begin();
      Serial.println("HTTP server started");
    }

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

So it would do something like this for and should be looking through every i between 0 and 200. :

    server.on("/"+String(i), [](){
        Serial.println("i");
      });

title: ESP8266 send number in IP address

Answers: 2

body:
First you need to extract the string that contains the number (after the /). Since it is already stored in consecutive memory you can pass the pointer to the character after the / symbol to the C function `atoi` to convert it to an integer.

I assume the pointer is already `\0` terminated.

You can use the C function `strchr` to search for the / symbol.

Tip: use a C compiler on a desktop/PC to check how these functions work. Once you know how to use them, copy them in your Arduino code. This is much faster than uploading/debugging sketches probably.

body:
First of all use the event function server.on with a path that corresponds to your function and use a url like this:

    192.0.2.2/recordnumber?num=100

With a url parmeter for your number. Your code might look like this:

At the top:

    int nums_size = 0;
    const int nums_max = 128;
    int nums[nums_max];

In setup:

    server.on("/recordnumber", [](){
        int num;
        if(server.hasArg("num")) {
          String num_str = server.arg("num");
          if(num_str.charAt(0) == '0') {
            num = 0;
          } else {
            num = num_str.toInt();
            if(num == 0) {
              server.send(400, "text/plain", "not a number");
              return;
            }
          }
          if(nums_size < nums_max) {
            nums[nums_size++] = num;
            server.send(200, "text/plain", "saved");
          } else {
            server.send(500, "text/plain", "full");
          }
        } else {
          server.send(400, "text/plain", "bad params");
        }
    });


body:
First of all I am very novice in electronics so bare with me.

I am trying to make a self watering system using arduino nano, first I tried the fly fish hygrometer module with the 5V power of the Arduino, and that worked.

Then I wanted to add the 12V solenoid, so I changed to a 12V external power through the Vin.

My goal is to use only one power source.

This is what I have done so far:

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

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

My question is:

**Can I power the hygrometer module using for the positive the 5V outlet of the Arduino nano and the ground from the 12V power source as shown in the figures?**

Or will this burn the module or screw the readings?

  [1]: https://i.stack.imgur.com/ZxoR1.png
  [2]: https://i.stack.imgur.com/9xrRX.png

title: Using a 12V DC adapter to power Arduino nano, 12v Solenoid and an Hygrometer

Answers: 0


body:
I usually use [Platformio][1] as IDE for my Arduino projects. I like it as an editor, but I don't like its serial monitor feature. So I often open the Arduino IDE in background to use its serial monitor, but this has some drawbacks (including a significant increase in my computer's CPU usage and battery consumption).

Is there an Arduino-compatible serial monitor application that just works as a serial monitor (and not also as an IDE)? I'm most interested in a MacOS application, but if you know a Windows one please tell me as well.

  [1]: http://platformio.org

title: "Stand-alone" serial monitor

Answers: 4

body:
I use [CoolTerm][1], which is available for Mac, Windows and Linux. It is a great serial app, and you can have several windows open at the same, for each serial pipe you may be using (Bluetooth, Arduino Serial, etc).

  [1]: http://freeware.the-meiers.org/

body:
There's a list of serial port sniffers here, if you want to view raw data

[ softwarerecs.stackexchange serial-port-logging][1]

And a list here of programs which plot graphs from serial data:

[softwarerecs.stackexchange serial-data-plotting-programs ][2]

  [1]: https://softwarerecs.stackexchange.com/questions/7636/serial-port-logging/7639#7639

  [2]: https://arduino.stackexchange.com/questions/1180/serial-data-plotting-programs

body:
Consider building your own monitor in Python. This gives you flexibility since Python is cross platform and you can tailor the monitor to your needs.

 1. Install [Python][1].
 2. Install [pySerial][2] (`pip install pyserial`).
 3. Write a Python script to read and/or write to the Arduino across the serial port. There are some great examples out there such as [this example][3] and other [Stack Overflow answers.][4]

  [1]: https://www.python.org
  [2]: https://pythonhosted.org/pyserial/
  [3]: https://www.thepoorengineer.com/en/arduino-python-plot/
  [4]: https://stackoverflow.com/questions/24074914/python-to-arduino-serial-read-write

body:
On macOS, you can use the built-in `screen` command, e.g.:

    screen /dev/cu.usbmodem14201 9600

To exit, control-A followed by control-\\


body:
I am trying to read data from an [AD7314 Temperature Sensor][1] that is connected to an Arduino Uno and output that value onto 6 LEDs also connected to the Arduino Uno board. From the image below, the sensor is showing only an output of `0011111111111111` during the streams of 16 clock cycles even after the chip enable goes from low to high before conversion to initiate a new one (it seems that the conversion is stuck). The datasheet says:

>A leading zero and 10 bits of data are transferred during a read operation. Read operations occur during streams of 16 clock pulses. Output data is updated on the rising edge of SCLK. The serial data is accessed in a number of bytes if 10 bits of data are being read. At the end of the read operation, the SDO line remains in the state of the last bit of data clocked out of the AD7314 until CE returns low

I am not sure where exactly I am going wrong during the read operation:

Note: for the Waveform image (Top to bottom):

- waveform 1: Chip Enable

- waveform 2: Serial Clock

- waveform 3: MISO Line

- waveform 4: MOSI Line

My code is below:

    #include <SPI.h>

    const int MOSI_PIN = 11;
    const int MISO_PIN = 12;
    const int SCK_PIN = 13;
    const int Slave_PIN = A0;

    // module data
    uint16_t myValFromTempSensor = 0;

    void setup () {
      SPI.begin ();
      SPI.beginTransaction(SPISettings(125000, MSBFIRST, SPI_MODE0));
      pinMode(5, OUTPUT); //LED 3
      pinMode(6, OUTPUT); //LED 4
      pinMode(7, OUTPUT); //LED 5
      pinMode(8, OUTPUT); //LED 6
      pinMode(9, OUTPUT); //LED 7
      pinMode(10, OUTPUT);//LED 8
      pinMode(MOSI_PIN, OUTPUT); // MOSI to SDI
      pinMode(MISO_PIN, INPUT); //MISO to SDO
      pinMode(SCK_PIN, OUTPUT); //CLOCK PIN to SCK
      pinMode(Slave_PIN,OUTPUT); //Slave pin

      digitalWrite(Slave_PIN, LOW);//Set slave low before communication
      for (int i = 5; i < 11; i++) {
        digitalWrite(i, LOW);
      }
      delay(100);
    } // end of setup

    void loop () {
      digitalWrite(Slave_PIN, HIGH);  //Set slave high to read data
      myValFromTempSensor = SPI.transfer(0x00); // Read Data from the device
      myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;// Bitshift to read next 8 bits
      digitalWrite(Slave_PIN, LOW);
      if(( myValFromTempSensor>=0) && ( myValFromTempSensor<=196)) {
        //Range 0C to 60C is  0 to 196
        digitalWrite(5, bitRead(myValFromTempSensor,0));
        digitalWrite(6, bitRead(myValFromTempSensor,1));
        digitalWrite(7, bitRead(myValFromTempSensor,2));
        digitalWrite(8, bitRead( myValFromTempSensor,3));
        digitalWrite(9, bitRead( myValFromTempSensor,4));
        digitalWrite(10, bitRead( myValFromTempSensor,5));
      } else {
        digitalWrite(5, 0);
        digitalWrite(6, 0);
        digitalWrite(7, 0);
        digitalWrite(8, 0);
        digitalWrite(9, 0);
        digitalWrite(10, 0);
      }
    }

[![SPI Waveform][2]][2]

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/AD7314.pdf
  [2]: https://i.stack.imgur.com/x4WHf.png

title: Unable to read data with 16 serial clock cycles

Answers: 3

body:
This is not an answer to your question but I cannot add it as a remark since it involves code.

You can greatly reduce your code by using for loops, e.g.:

       pinMode(5, OUTPUT); //LED 3
       pinMode(6, OUTPUT); //LED 4
       pinMode(7, OUTPUT); //LED 5
       pinMode(8, OUTPUT); //LED 6
       pinMode(9, OUTPUT); //LED 7
       pinMode(10, OUTPUT);//LED 8

to

       int n;
       for (n = 5; n < 11; n++)
       {
          pinMode(n, OUTPUT);
       }

And

    digitalWrite(5,bitRead( myValFromTempSensor,0));
    digitalWrite(6,bitRead( myValFromTempSensor,1));
    digitalWrite(7,bitRead( myValFromTempSensor,2));
    digitalWrite(8,bitRead( myValFromTempSensor,3));
    digitalWrite(9,bitRead( myValFromTempSensor,4));
    digitalWrite(10,bitRead( myValFromTempSensor,5));

to

    int n = 0;
    for (n = 0; n < 6; n++)
    {
        digitalWrite(n + 5,bitRead( myValFromTempSensor, n));
    }

And

      digitalWrite(5,0);
      digitalWrite(6,0);
      digitalWrite(7,0);
      digitalWrite(8,0);
      digitalWrite(9,0);
      digitalWrite(10,0);

to

    int n;
    for (n = 5; n < 11; n++)
    {
        digitalWrite(n, 0);
    }

Instead of hardcoded values 5 and 11 you can use defines, e.g.

    #define LED_MIN 5
    #define LED_MAX 11

and change

    for (n = 5; n < 11; n++)

to

    for (n = LED_MIN; n < LED_MAX; n++)

body:
I see several issues here.

## Sensor output

According to the waveforms shown by your logical analyzer, the sensor is
outputting 0b0011111111111111. We have to discard the first (a padding
zero) and the last five bits (copies of DB0). We then end up with the
actual data bits being 0111111111. This has to be interpreted as a
signed fixed-point number in s.7.2 format, which gives 127.75 °C:
the maximum possible value the sensor can output, and well above its
maximum operating temperature.

I cannot tell what is going wrong here. It looks like the sensor is
either burning alive, or trying to tell you it's extremely unhappy.

## SPI mode

You wrote:

> `SPISettings(125000, MSBFIRST, SPI_MODE0)`

SPI mode 0 seems to be pretty common. In this mode, the data lines are
updated on the falling edge of the clock, and they are read on the
rising edge. However, according to your sensor's datasheet, it appears
this sensor works the other way around: it uses [SPI mode 1][]. Your
setting should reflect this.

## Decoding the data

You wrote:

> `myValFromTempSensor = SPI.transfer(0x00);`
> `myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;`

Here you are assuming the least significant byte is transmitted first.
This is not the case: you get a stream of 16 bits with the most
significant first. Thus, in terms of bytes, it's also MSB first.

Then, 6 of these 16 bits have to be discarded in order to get the actual
10 data bits. Since the Arduino has no 10-bit data type, and the
number is signed, it has to be sign-extended to 16-bits. All this can be
done in C/C++ by:

* left-shifting one bit to the left (discarding the zero padding bit)
* casting to a _signed_ 16-bit integer
* right-shifting (which [gcc implements using sign
  extension][signed shift]) six bits to the right

Or, in code:

    digitalWrite(Slave_PIN, HIGH);
    uint16_t raw_data = SPI.transfer16(0);
    digitalWrite(Slave_PIN, LOW);
    int temperature_reading = (int16_t)(raw_data << 1) >> 6;

[SPI mode 1]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase
[signed shift]: https://gcc.gnu.org/onlinedocs/gcc-5.5.0/gcc/Integers-implementation.html#Integers-implementation

------------------------------------------------------------------------

**Edit**: Here are more details about the data representation, and about
the conversion to 16-bits done by the expression
`(int16_t)(raw_data << 1) >> 6`.

According to the datasheet, the sensor gives the temperature as a 10-bit
_signed_ number in two's complement notation. If you fail to acknowledge
the fact that the result is signed, and you interpret the 10 bits
as an unsigned number, then a temperature of −1 °C will be
interpreted as +255 °C, which is obviously _very_ wrong.

Since it's a signed number, increasing the bit width of the temperature
to 16 bits has to be done using [sign extension][], i.e. the
missing bit positions have to be filled with copies of the leftmost bit
(the “sign bit”).

The datasheet also shows that the sensor sends a stream of 16-bits as
follows:

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

    0 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0

where the first bit is a padding zero, then come the ten data bits
db9 – db0, and then five extra copies of the last data bit.
These extra copies can  be seen in figure 3 (serial interface
digram), and can also be inferred from the sentence “the SDO line
remains in the state of the last bit of data clocked out of the AD7314”.

The line

    uint16_t raw_data = SPI.transfer16(0);

puts this bit pattern into the variable `raw_data`, which is a 16-bit
unsigned integer. Then, the operation `raw_data << 1` shifts this
pattern one bit position to the left, discarding the leftmost zero and
padding with another zero on the right, which gives:

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

    db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0 0

This is then cast to a signed number, which doesn't change the bit
pattern, but only the interpretation of the leftmost bit, which is now a
sign bit. Then, the number is shifted by 6 bit positions to the
right. Since this is an [arithmetic shift][], which does sign extension,
the leftmost bit (the “sign bit”) is replicated during the shift, which
yields:

    db9 db9 db9 db9 db9 db9 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0

And this is the expected result: the _same numeric value_ that was
originally stored in the “temperature value register” of the sensor,
only represented as a 16-bit number.

[sign extension]: https://en.wikipedia.org/wiki/Sign_extension
[arithmetic shift]: https://en.wikipedia.org/wiki/Arithmetic_shift

body:
If anyone stumbled on this thread later like I did, it may be helpful to understand that the binary response is a decimal number, specifically with 0.25c resolution. Meaning that the integer value that Edgar Bonet's (excellent) response will give you needs to be multiplied by 0.25 to get the actual temperature in Celsius.

I suggest multiplying by 0.25 because it will give the same result as dividing by 4 but without the risk of a divide by zero error. Also division is extremely slow on Arduino since the underlying instruction set does not have a divide instruction.

I  hope this helpful to someone at some point; if not sorry for the annoyance.


body:
I am able to connect to thingspeak but now able to upload the data. here are my set of commands:

    AT+CIPMUX=0
    OK

    AT+CIPSTART="TCP","184.106.153.149", 80
    OK
    Linked

    AT+CIPSTATUS
    STATUS:3
    +CIPSTATUS:0,"TCP","184.106.153.149",80,0
    OK

    AT+CIPSEND=45
    > GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60

    busy s...

    SEND OK

    OK

and after some time unlink

I am giving these commands using arudino serial monitor.
Please help, I have searched a many blogs, youtube videos.

title: Unable to upload the data on thingspeak using uno and esp8266

Answers: 2

body:
You have a malformed HTTP request. You only have half of the first line.

A valid HTTP request would look more like this:

    GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60 HTTP/1.1
    Host: api.thingspeak.com
    Content-length: 0
    Connection: close
    <blank line>

Just sending "GET <path>: ain't gonna work. For a start, the server won't know what protocol you're speaking (HTTP/1.1), nor what website it's supposed to direct the request to (Host: api.thingspeak.com). Also, the final extra blank line is *required* to finish the request.

body:
   I got it working. Yo!

    #include <SoftwareSerial.h>
    #include <stdlib.h>

    // LED
    int ledPin = 13;
    // LM35 analog input
    int lm35Pin = 0;
    float my_value = 22;
    // replace with your channel's thingspeak API key
    String apiKey = "9PJEF1EP8ZMVY5JA";

    // connect 10 to TX of Serial USB
    // connect 11 to RX of serial USB
    SoftwareSerial ser(10, 11); // RX, TX

    // this runs once
    void setup() {
      // initialize the digital pin as an output.
      pinMode(ledPin, OUTPUT);

      // enable debug serial
      Serial.begin(9600);
      // enable software serial
      ser.begin(9600);

      // reset ESP8266
      ser.println("AT+RST");
    }

    // the loop
    void loop() {

      // blink LED on board
      digitalWrite(ledPin, HIGH);
      delay(200);
      digitalWrite(ledPin, LOW);

      // read the value from LM35.
      // read 10 values for averaging.

      // convert to temp:
      // temp value is in 0-1023 range
      // LM35 outputs 10mV/degree C. ie, 1 Volt => 100 degrees C
      // So Temp = (avg_val/1023)*5 Volts * 100 degrees/Volt
      my_value++;
      float temp = my_value;

      // convert to string
      char buf[16];
      String strTemp = dtostrf(temp, 4, 1, buf);

      Serial.println(strTemp);

      // TCP connection
      String cmd = "AT+CIPSTART=\"TCP\",\"";
      cmd += "184.106.153.149"; // api.thingspeak.com
      cmd += "\",80";
      ser.println(cmd);

      if(ser.find("Error")){
        Serial.println("AT+CIPSTART error");
        return;
      }

      // prepare GET string
      String getStr = "GET /update?api_key=";
      getStr += apiKey;
      getStr +="&field1=";
      getStr += String(strTemp);
      getStr +="&field2=";
      getStr += String(strTemp);
      getStr += "\r\n\r\n";

      // send data length
      cmd = "AT+CIPSEND=";
      cmd += String(getStr.length());
      ser.println(cmd);
      Serial.println(cmd);

      if(ser.find(">")){
        ser.print(getStr);
        Serial.println(getStr);
      }
      else{
        ser.println("AT+CIPCLOSE");
        // alert user
        Serial.println("AT+CIPCLOSE");
      }

      // thingspeak needs 15 sec delay between updates
      ser.println("AT+RST");
      delay(30000);
    }


body:
I'm having a weird issue with my Uno trying to power on a PWM fan using a MOSFET.

I'm setting a simple power on/off code using commands sent over the Serial Monitor, and although this code worked before, after I tried to add some code to control the speed of the PWM fan, my if statements do not work anymore, even with the simple power on/off code:

        String command;           //Define the string variable "command"

    void setup() {
      // put your setup code here, to run once:

      pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
      pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
      digitalWrite(5, LOW);   //Start with MOSFET off
      digitalWrite(13, LOW);  //Star with status LED off
      Serial.begin(9600);     //Start Serial comm for sending commands

    }

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

      Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

      while (Serial.available()==0) {        //Wait for user input stopping the code
        digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
        delay(100);
        digitalWrite(13, LOW);
        delay(100);
      }

      command=Serial.readString();          //Save the Serial Monitor String command to the "command" variable as a String
      Serial.println("data read");          //Confirm Serial Monitor input
      Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

      if (command=="On") {                  //Turn the MOSFET on
        digitalWrite(5, HIGH);
      } else if (command=="Off") {                  //Turn the MOSFET off
        digitalWrite(5, LOW);
      }
      else {                                 //Provide feedback for a wrong command
        Serial.println("Wrong command!");
      }
    }

This is my Serial Monitor output after sending "On":

    What's your command?
    data read
    On

    Wrong command!
    What's your command?

To check if the pin works, I tested a simple code that worked fine:

    void setup() {
      // put your setup code here, to run once:

      pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
      digitalWrite(5, LOW);   //Start with MOSFET off
      Serial.begin(9600);     //Start Serial comm for sending commands

    }

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

        digitalWrite(5, HIGH);
     delay(2000);
        digitalWrite(5, LOW);
     delay(2000);

    }

Does anyone have any idea why the if statements are not working anymore?

Thank you in advance!

AC

EDIT: After trying to use the "else" statement as recommended by per1234, the issue continues to happen, but changing the variable type to an integer works, although the Serial output is rather messy:

    int command;           //Define the int variable "command"

    void setup() {
      // put your setup code here, to run once:

      pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
      pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
      digitalWrite(5, LOW);   //Start with MOSFET off
      digitalWrite(13, LOW);  //Star with status LED off
      Serial.begin(9600);     //Start Serial comm for sending commands

    }

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

      Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

      while (Serial.available()==0) {        //Wait for user input stopping the code
        digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
        delay(100);
        digitalWrite(13, LOW);
        delay(100);
      }

      command=Serial.parseInt();          //Save the Serial Monitor imput command to the "command" variable as an int

      Serial.println("data read");          //Confirm Serial Monitor input
      Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

      if (command==1) {                  //Turn the MOSFET on
        digitalWrite(5, HIGH);
      }
      if (command==2) {                  //Turn the MOSFET off
        digitalWrite(5, LOW);
      }
      else {                                 //Provide feedback for a wrong command
        Serial.println("Wrong command!");
      }
    }

And the Serial Monitor output:

    What's your command?
    data read
    1
    What's your command?
    data read
    0
    Wrong command!
    What's your command?
    data read
    2
    What's your command?
    data read
    0
    Wrong command!
    What's your command?

Does anyone experience this issue? I even tried rolling back my IDE to 1.8.3, which I used to write the code the first time, then after a library update, and also getting version 1.8.5, it stopped working.

Also, anyone knows how to avoid the multiple Serial Monitor outputs?

I tested this with "String" variables to be able to get this fixed.

Also, a side question regarding the post size, should I remove the original code when editing, or should I move it to another answer?

Thank you.

title: Arduino Uno "if" statement is ignored in code and halts execution when using Serial.ReadString()

Answers: 3

body:
Let's look at what this code does when you send "On":

      if (command=="On") {                  //Turn the MOSFET on
        digitalWrite(5, HIGH);
      }

This will evaluate true so pin 5 is set to HIGH.

      if (command=="Off") {                  //Turn the MOSFET off
        digitalWrite(5, LOW);
      }

This will evaluate false so the else clause is executed:

      else {                                 //Provide feedback for a wrong command
        Serial.println("Wrong command!");
      }

So the output you are seeing is correct for your code. The problem is that your code doesn't match your intent. For that you need to change this line:

      if (command=="Off") {                  //Turn the MOSFET off

to:

      else if (command=="Off") {                  //Turn the MOSFET off

Then the else clause will only run if the command doesn't match "On" or "Off".

For more information see:
https://www.arduino.cc/reference/en/language/structure/control-structure/else/

body:
The problem with the *original* code is evidenced in the following:

    What's your command?
    data read
    On

    Wrong command!

See that blank line?  Nowhere in your sketch do you specifically print a blank line, rather it is being printed because the `command` string contains a carriage return and/or newline character captured with the input, which is causing a comparison of exact equality to fail.

To fix this, you could either trim these non-printing characters off the end, or use a different comparison, for example `command.startsWith("On")`.  But if you do use a start-of-string comparison, beware if you have any command verbs that extend other shorter ones.

You also have a bug in your block if-else statements, in that instead of

    if ...
    if ...
    else ...

you should have

    if ...
    else if ...
    else ....

So that the "none of the above" clause only runs when none of the conditions are satisfied, rather than running whenever the penultimate condition is not satisfied.

In terms of the numeric version producing an un-entered value of 0, this is the documented return value of the `parseInt()` methods if they time out without finding a valid integer.

It would be more traditional to use an end-of-line condition rather than a timeout to detect the end of user input.  Many traditional "until end of line" read mechanisms trim the line ending characters off the resulting string for you, eliminate the comparison problem, too.

body:
Thank you for your help.

I have been able to find the root cause of my original problem.

After reading this post on https://forum.arduino.cc/index.php?topic=73372.0, more specifically an answer regarding filtering for \n and \r characters and the Arduino IDE Serial Monitor line ending option.

My problem was caused by having the "Newline" option selected in the Serial Monitor. After selecting "No line ending", my original code runs as expected, and I know now how to use String variable and Serial.readString() in a more efficient way, and the if-else statements.

Also, the blank line mentioned by Chris Stratton is gone, and my search to fix that led me to the solution of the main problem, and the code also works 100% with the formatting help provided by per1234.

Thank you both again for the help.