body:
I have a Raspberry Pi and an Arduino. On my Arduino I wrote a program, if you see the last two functions i.e. `getMove()` and `SendMove()` you will see that I am sending a move serially and the RPi will read the string only after it reads start. It is sending it to the RPi through serial communication using a USB (Note: As you can see the Arduino will send the string only one time and not again and again since once it sends the string the control will go into `getMove()` which waits for "Rstart").

Once I uploaded the code in the Arduino, I opened the serial monitor to check the output that I should be expecting in my RPi. Then I removed the USB from my laptop and connected the Arduino to the RPi and ran the Python code to read the string sent from the Arduino serially and got the string sent. I ran the code again on the RPi and got the string sent.

Now my question is, the first time when I opened the serial monitor on the laptop there was serial communication between the Arduino and my laptop, so I expected the string I sent to have gone to the laptop. So, when I connected the Arduino to the RPi, I didn't expect a string to be received on the RPi since the string was already sent to the laptop. Then again I ran the code on the RPi but still got the string sent.

Can someone explain how Serial communication works? Once I send something from the Arduino serially, will it always be in the serial buffer?

EDIT:
I have understood that unless the DTR pin of the serial connector is disabled the Arduino will keep resetting itself when connected to something new.

Now my question is, why does Arduino reset itself when I run the Python code (to read the serial buffer) again and again?

ARDUINO CODE

    #include "LiquidCrystal.h"

    const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // 4 bit mode
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
    int SensorValStore_Prev[8][8] = { {0,0,0,0,0,0,0,0}, \
                                      {0,0,0,0,0,0,0,0}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {0,0,0,0,0,0,0,0}, \
                                      {0,0,0,0,0,0,0,0} };

    int SensorValStore_Curr[8][8]={ {0,0,0,0,0,0,0,0}, \
                                    {0,0,0,0,0,0,0,0}, \
                                    {1,1,1,1,1,1,1,1}, \
                                    {1,1,1,1,1,1,1,1}, \
                                    {1,1,1,1,1,1,1,1}, \
                                    {1,1,0,1,1,1,1,1}, \
                                    {0,0,0,0,0,0,0,0}, \
                                    {0,1,0,0,0,0,0,0} };
    //int SensorValStore_Curr[8][8];
    int sum1[8],sum2[8],temp[8][8],k,l,i,j,rank,nextRow;
    String file,moveSan,Temp,bestMove;
    char Buffer[20];
    void doAction();
    void ReadSensor();
    void Difference();
    void binToIntCalc();
    void check();
    void getMovePlayed();
    void SendMove();
    void getmove();

    void setup()
    {
      Serial.begin(9600);
      lcd.begin(16,2);
      pinMode(22,INPUT_PULLUP); // Reed switch - Row1
      pinMode(24,INPUT_PULLUP); // Reed switch - Row2
      pinMode(26,INPUT_PULLUP); // Reed switch - Row3
      pinMode(28,INPUT_PULLUP); // Reed switch - Row4
      pinMode(30,INPUT_PULLUP); // Reed switch - Row5
      pinMode(32,INPUT_PULLUP); // Reed switch - Row6
      pinMode(34,INPUT_PULLUP); // Reed switch - Row7
      pinMode(36,INPUT_PULLUP); // Reed switch - Row8
      pinMode(2,INPUT_PULLUP);// Push Button
      pinMode(38,OUTPUT);
      pinMode(40,OUTPUT);
      pinMode(42,OUTPUT);
      pinMode(44,OUTPUT);
      pinMode(46,OUTPUT);
      pinMode(48,OUTPUT);
      pinMode(50,OUTPUT);
      pinMode(52,OUTPUT);
      pinMode(3,OUTPUT);
      digitalWrite(38,HIGH);
      digitalWrite(40,HIGH);
      digitalWrite(42,HIGH);
      digitalWrite(44,HIGH);
      digitalWrite(46,HIGH);
      digitalWrite(48,HIGH);
      digitalWrite(50,HIGH);
      digitalWrite(52,HIGH);
      digitalWrite(3,LOW);
    }

    void loop()
    {
      //if( digitalRead(10) == 0 )
      //{
      Serial.print("--------------------Initial Matrix-----------------------------\n");
      Print(SensorValStore_Prev);
      // doAction();
      delay(40);
      Serial.print("--------------------Final Matrix------------------------------\n");
      Print(SensorValStore_Curr);
      delay(40);
      Difference();
      delay(40);
      binToIntCalc();
      delay(40);
      check();
      delay(40);
      getMovePlayed();
      delay(40);
      getMove();
      delay(40);
      //}
    }

    void Print(int matrix[8][8])
    {
      for(i=0;i<8;i++)
      {
        for(j=0;j<8;j++)
        {
          Serial.print(matrix[i][j]);
          Serial.print(" ");
        }
        Serial.println();
      }
    }

    void doAction()
    {
      nextRow = 0;
      for(i=0;i<8;i++)
      {
        digitalWrite(38 + nextRow,LOW);
        delay(40);
        ReadSensor(i);
        digitalWrite(38 + nextRow,HIGH);
        delay(40);
        nextRow +=2;
      }
    }

    void ReadSensor(int iter)
    {
      delay(10);
      for(j=0;j<8;j++)
        SensorValStore_Curr[iter][j] = digitalRead(j+2);
      Serial.print("----------------------------------------------");
      Serial.println("Value of sensory board after move is played");
    }

    void Difference()
    {
      for(i=0;i<8;i++)
        for(j=0;j<8;j++)
          temp[i][j] = abs(SensorValStore_Curr[i][j] - SensorValStore_Prev[i[j]);
      Serial.print("-----------------------Difference---------------------------\n");
      Print(temp);
    }

    void binToIntCalc()
    {
      for(i=0;i<8;i++)
        for(j=0;j<8;j++)
        {
          sum1[i] += pow(2,j)*SensorValStore_Prev[i][j];
          sum2[i] += pow(2,j)*SensorValStore_Curr[i][j];
        }
      Serial.print("---------------------sum1 and sum --------------------------\n");
      for(i=0;i<8;i++)
      {
        Serial.print(sum1[i]);
        Serial.print(" ");
      }
      Serial.println();

      for(i=0;i<8;i++)
      {
        Serial.print(sum2[i]);
        Serial.print(" ");
      }
      Serial.println();
    }

    void check()
    {
      k=0;
      l=0;
      for(i=0;i<8;i++)
      {
        if(sum2[i]>sum1[i])
          k = i;
        if(sum2[i]<sum1[i])
          l = i;
        delay(40);
      }
    }

    void getMovePlayed()
    {
      for(j=0;j<8;j++)
      {
        if(temp[k][j] == 1)
        {
          rank =k+1;
          file = String(char(97+j));
          delay(40);
          moveSan = file + rank;
          Temp = moveSan;
        }
      }
      for(j=0;j<8;j++)
      {
        if( temp[l][j] == 1)
        {
          rank =l+1;
          file = String(char(97+j));
          delay(40);
          moveSan = file + rank;
          Temp.concat(moveSan);
        }
      }
    }

    void SendMove(String movePlayed)
    {
      Serial.println("start");
      Serial.print(movePlayed);
      Serial.println();
    }

    void getMove()
    {
      while(1)
      {
        if(Serial.available()>0)
        {
          if(Serial.readString() == "Rstart")
          {
            bestMove = Serial.readString();
            lcd.setCursor(0,0);
            lcd.print(bestMove);
            delay(5000);
            lcd.clear();
            Serial.println(bestMove);
            exit(0);
          }
        }
      }
    }

PYTHON CODE

    import serial
    from stockfish import Stockfish
    s1 = serial.Serial('/dev/ttyACM0', 9600)
    stockfish = Stockfish('/usr/games/stockfish')
    while 1 :
        if str(s1.readline(),'UTF-8').strip('\n\r') == 'start' :
                    move_played = str(s1.readline(),'UTF-8').strip('\n\r')
                    print(move_played)
                    // stockfish.set_position(move_played)
                    // print("Rstart")
                    // print(stockfish.get_best_move().encoded())
                    break

title: Query related to Serial communication

Answers: 1

body: It would help to see your code but bear in mind when you connect the serial monitor to your arduino it resets so any code will re-run


body:
I have written the code that should work, but for some reason the numbers do not display correctly. When I choose to display 3 times the same number it works correctly (so pin connections are correct) but when trying to display different numbers on each digit things get messy. Can anyone see what is wrong with the code? I don't seem to find it. thanks!

Working when 3 digits are the same:

![a busy cat](https://preview.ibb.co/h5PrZy/CAM00319.jpg)

Not working with different numbers (should be 3, 2, 1:

![a busy cat](https://preview.ibb.co/dsKfSJ/CAM00318.jpg)

And the code:

    int a = 2;               //Defining segments corresponding to the pins
    int b = 3;
    int c = 4;
    int d = 5;
    int e = 6;
    int f = 7;
    int g = 8;

    void setup(void) {      //Setting Pins as output
      pinMode(A0, OUTPUT);
      pinMode(A1, OUTPUT);
      pinMode(A2, OUTPUT);
      pinMode(a, OUTPUT);
      pinMode(b, OUTPUT);
      pinMode(c, OUTPUT);
      pinMode(d, OUTPUT);
      pinMode(e, OUTPUT);
      pinMode(f, OUTPUT);
      pinMode(g, OUTPUT);
    }

    void WriteNum(int PositionN, int Number) {
      int Position;
      int NumberSegments[10][7] = {{a,b,c,d,e,g},     //Defining segments for forming numbers
                              {b,c},
                              {a,b,d,e,g},
                              {a,b,c,d,g},
                              {b,c,f,d},
                              {a,c,d,f,g},
                              {a,c,d,e,f,g},
                              {a,b,c},
                              {a,b,c,d,e,f,g},
                              {a,b,c,d,f,g}};
      digitalWrite(A0, HIGH);                       //Setting begin conditions (All segments low and no digits turned on)
      digitalWrite(A1, HIGH);
      digitalWrite(A2, HIGH);
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);

      switch (PositionN) {                        //Deciding which digit to turn on
        case 1:
          Position = A0;
          break;
        case 2:
          Position = A1;
          break;
        case 3:
          Position = A2;
          break;
      }
      digitalWrite(Position, LOW);
      for (int i = 0; i < sizeof(NumberSegments[Number]); i++){       //For each segment in number to display
            digitalWrite(NumberSegments[Number][i], HIGH);            //Light that segment
            }
      delay(5);
    }

    void loop(void) {
      WriteNum(1,2);
      WriteNum(2,2);
      WriteNum(3,2);
    }

title: 7-Segment, 3-digit display not displaying correctly

Answers: 1

body:
I have three recommendations for you. @Gerben was correct as to your problem, but doing the following three steps will improve the speed of your code:

 1. Change your definition for `NumberSegments` to be `[10][8]`, and put the number of active segments as the first number of each array:

         ...[10][8] = {{6,a,b,c,d,e,g},     // ...
                       {2,b,c},
                       {5,a,b,d,e,g}, // etcetera
 2. Change your `for` loop as follows:

        for (int i = 1; i <= NumberSegments[Number][0]; i++) { // ...
           digitalWrite(NumberSegments[Number][i], HIGH); // ...
        }

  This will only turn on the minimum number of segments required. Note the loop now starts at `1`, and uses `<=` instead of `<`.
 3. Put the keyword `static` in front of `NumberSegments`:

        static int NumberSegments[10][8] = {{ // ...

This last one is a language nicety. Every time the function `WriteNum` is called, the poor thing has to re-create the (large) `NumberSegments` array - and it’s the same every time! The keyword `static` means “only create this variable once”. Next time into the function, it’ll already be available: no processing required!

You might also consider moving `int position;` below `NumberSegments`, since it’s convention to put `static` variables first in a function.

You can also use the keyword `const` on `NumberSegments`, since its values never change:

    static const int NumberSegments[10][8] = {{ // ...


body:
I am trying to set the Arduino MEGA 2560 R3 into sleep mode and wake it up with an RTC DS3231 via interrupt. I was following this tutorial:
[Tutorial][1]

One of the libraries included is the "LowPower" library, you can find it [here on GitHub][2]. It produces the following error while compiling:

    C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp: In member function 'void LowPowerClass::idle(period_t, adc_t, timer5_t, timer4_t, timer3_t, timer2_t, timer1_t, timer0_t, spi_t, usart3_t, usart2_t, usart1_t, usart0_t, twi_t)':

    C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:562:49: error: 'power_usart3_disable' was not declared in this scope

      if (usart3 == USART3_OFF) power_usart3_disable();

                                                     ^

    C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:597:48: error: 'power_usart3_enable' was not declared in this scope

      if (usart3 == USART3_OFF) power_usart3_enable();

                                                    ^

    exit status 1
    Error while compiling for Arduino/Genuino Mega or Mega 2560.

I dont understand why there should be any functions in the library, which are not declared...This would mean noone could use it?! I am not an expert in C++ so maybe one of you could tell me what the issue could be. I am glad for any help.

  [1]: http://www.instructables.com/id/Arduino-Sleep-and-Wakeup-Test-With-DS3231-RTC/
  [2]: https://github.com/rocketscream/Low-Power/

title: Arduino MEGA2560 wake up using DS3231 RTC

Answers: 1

body:
after further web research, it looks like this is a bug which hasnt been fixed yet.
it was discussed previously [here][1] and [here][2].

My solution was to go into the "LowPower.cpp" scroll down to the lines, where the functions are not declared and I just out-commented them. Compiling works now.

  [1]: https://github.com/rocketscream/Low-Power/issues/30
  [2]: https://github.com/arduino/Arduino/issues/5286


body:
I am working with an Adafruit Feather 32u4 FONA board. I want to connect a GPS module I have worked with before (3.3V required) but am not having much luck. I have studied the pinout of the board and have tried the 3.3V pin but it is far too erratic in nature and cannot sufficiently power the module. There is a pin called USB which supplies 5.0V from the pin if a micro USB cable is connected. I have used an LM317 and a potentiometer to make a voltage regulator circuit to convert the 5.0V from the USB pin to the 3.3V I need for the GPS module. This works, as I have measured 3.3V successfully using a multimeter.

**The problem** is that when I connect the VCC and GND pins of the GPS module to the 3.3V regulated output, the module still doesn't get any power. I measured a significant drop to around 0.89V across GND and VCC after I connect the module. What could be causing this strange behavior?

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

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

The bottom left rail is what I am trying to use to power the GPS module, before I connect it I get **3.3V** as mentioned earlier, which is the required level.

title: 3.3V from 5.0v outlet

Answers: 2

body: According to the datasheet the LM317 has a minimum Vin to Vout of 3v so you'd only be able to get 2v out of it if you put 5v in.  I'd recommend using either an AMS1117 3.3 or one of the cheap modules based on that chip that has an LED and capacitors on board. They definitely deliver 3.3v from 5v in.

body: A while has passed since I asked this question but in a bid to resolve it, I used my Buck regulator as suggested and this solved the problem.


body:
Will the Arduino IDE interpret digitalWrite(13,x), where x>0, as digitalWrite(13,HIGH)?
And will it interpret digitalWrite(13,x), where x<=0, as digitalWrite(13,LOW)?

title: A minor confusion in digitalWrite command

Answers: 1

body:
Every other value than `0` or `LOW` will result in setting the pin to `HIGH`. In the following I explain why:

The function `digitalWrite()` can be seen in the file `hardware/arduino/avr/cores/arduino/wiring_digital.c`. The important lines here are:

    if (val == LOW) {
        *out &= ~bit;
    } else {
        *out |= bit;
    }

As you can see, it checks, if the given value (from the parameter) is equal to `LOW` and if so will set the corresponding pin to `0`. In every other case it will set the pin to `1`. The definition of `LOW` can be found in `arduino/hardware/arduino/avr/cores/arduino/Arduino.h`:

    #define HIGH 0x1
    #define LOW  0x0

So the code checks, if the value is equal to `0` and sets the pin also to `0`. Every other value will result in a `1` (meaning `HIGH`). Also have a look at the definition of `digitalWrite()`:

    void digitalWrite(uint8_t pin, uint8_t val)

The value is an unsigned type, so every signed type will be casted to an unsigned type. A negative number would result in a positive number inside the function.


body:
I'm new to serial communication. I tried to make Arduino talk to MATLAB, but certain values are allowed to be received like 100 and 101. I tried other values but didn't work. The problem is with ASCII code but I tried to subtract what is read by 48 but failed.

This is the Arduino code that I found on Google and edited it for my servo motor problem:

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

    #include <Servo.h>
    const int servoPin = 3;
    int recValue; // received value from MATLAB
    Servo Servo1;

    void setup()
    {
      Serial.begin(9600);
      Servo1.attach(servoPin);
    }

    void loop()
    {
      if (Serial.available() > 0)
      {
        recValue = Serial.read();
        if  (recValue == 100)
        {
          Servo1.write(0);
          delay(1000);
        }
        if (recValue == 101)
        {
          Servo1.write(90);
          delay(1000);
        }
      }
    }

So how can I read the correct angles that I received from the MATLAB via serial communication? Thanks.

title: How can I read servo motor readings via serial communication?

Answers: 2

body:
I'm assuming, that you are sending the angle value as a 1-byte value, so no ASCII encoded numbers. This is how the code in your question works, so it should be right.

You don't have to convert anything here. The `Serial.read()` function already returns an integer value and you are saving it to an integer variable. But in your code you only care for 2 different states (100 and 101), instead of the actual angle value. Now you only have to replace your if-statements and write this value directly to the servo:

    Servo1.write(recValue);

EDIT:

You doesn't seem as you know how serial communication (to be exactly USART) functions. So I will explain further:

The data, that is send over serial is just a stream of bytes. All content, that get transmitted are converted to a stream of bytes. Every byte has a numerical value. For example a byte with the bit-content `00100000` has a numerical value of `32`. But at some point in history it was necessary to send text with a byte stream. So someone invented ASCII, which assigns a character or control command to every numerical value from 0 to 127. So if you send a byte with the numerical value of `32`, you could mean the actual numerical value `32`, or you could mean the ASCII equivalent to `32`, which is the space character. This is just an interpretation of the byte data, that flows through the serial interface.

So you have to investigate, in which kind you are encoding the angle value. If you use `fwrite()` in your Matlab code, you are most likely sending the byte value, which you can simply use as described above. If you use `fprintf()`, you are sending the angle value as an ASCII encoded string. The value `32` from above would then occupy 2 bytes with the characters `3` and `2`, which correspond to the byte values of `51` and `50`. In this case you should add a delimiter character at the end in `fprintf()` (for example the newline character "\n") and use `Serial.parseInt()` to get the angle value from the string.

You can read more of this in many tutorials about Serial communication that you can find in the internet. Also refer to the example, that come with the Arduino IDE.

body:
chrisl is quite right. You need to understand how MATLAB is talking to your Arduino. I suspect it is sending a sequence of characters for each servo angle instead of a single character.  In your code you are waiting for 100 and 101, which are the ASCII 'd' and 'e' characters, and then acting immediately you have read one character. See if the servo will turn if you send 'd' or 'e'. If that works then what you need to do is read a whole line of ASCII characters e.g. '9' (which is 57) and '0' (which is 48) followed by a delimiter e.g. newline (13)
At the beginning of line you can set int angle = 0 and each time you read a character multiply your angle by 10 and add in the new value by subtracting 48 from it.
When you reach the delimiter you can then send the angle to the servo.
Oh - and make sure MATLAB is talking at the right baud rate.


body:
I'm a first year persuing Mechatronic engineering, and I'm having trouble with this code that I am using to control a biped robot for my project.

    #include <servo.h>
    Servo myservoa;
               myservob;
               myservoc;
               myservod;
    int     myservoa=10;
              myservob=55;
              myservoc=25;
              myservod=125;

    void setup() {
        myservoa.attach(2)
        myservob.attach(3)
        myservoc.attach(4)
        myservod.attach(5)
    }

    void loop() {
        for pos=10;pos<=75;pos+=1;
        {
            myservoa.write(pos);
            delay(1000);
        }
        for pos=55;pos<=100;pos+=1;
        {
            myservob.write(pos)
            delay (1800)
        }
        for pos=25;pos<=165;pos+=1;
        {
            myservoc.write(pos)
            delay (1000)
        }
        for pos=125;pos<=170;pos+=1;
        {
            myservod.write(pos)
            delay (1800)
        }
    }

Could there be an error in the code?

title: Coding multiple servos in Arduino

Answers: 1

body:
> Could there be an error in the code?

You could say that, yes.  Let's list all the syntax errors to start with:

    #include <servo.h>
    Servo myservoa;
               myservob; // This has no type. It's just a word by itself.
               myservoc; // This has no type. It's just a word by itself.
               myservod; // This has no type. It's just a word by itself.

    int     myservoa=10; // You already defined myservoa as a Servo type.
              myservob=55; // This has no type. It's just a word by itself.
              myservoc=25; // This has no type. It's just a word by itself.
              myservod=125; // This has no type. It's just a word by itself.

    void setup()
    {
        myservoa.attach(2) // Semicolons must terminate all statements.
        myservob.attach(3) // Semicolons must terminate all statements.
        myservoc.attach(4) // Semicolons must terminate all statements.
        myservod.attach(5) // Semicolons must terminate all statements.
    }

    void loop()
    {
        for pos=10;pos<=75;pos+=1; // Braces are missing, pos is not defined, and extra ;
        {
            myservoa.write(pos);
            delay(1000);
        }
        for pos=55;pos<=100;pos+=1; // Braces are missing, pos is not defined, and extra ;
        {
            myservob.write(pos)  // Semicolons must terminate all statements.
            delay (1800) // Semicolons must terminate all statements.
        }
        for pos=25;pos<=165;pos+=1; // Braces are missing, pos is not defined, and extra ;
        {
            myservoc.write(pos) // Semicolons must terminate all statements.
            delay (1000) // Semicolons must terminate all statements.
        }
        for pos=125;pos<=170;pos+=1; // Braces are missing, pos is not defined, and extra ;
        {
            myservod.write(pos) // Semicolons must terminate all statements.
            delay (1800) // Semicolons must terminate all statements.
        }
    }

You really need to get to grips with the syntax of a language before you start programming in that language. I count just 6 lines (not including { and }) of valid C code there, and two of them are handed to you by the IDE.


body:
#include "LiquidCrystal.h"

    const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7)

    void setup() {
      Serial.begin(9600);
      lcd.begin(16, 2);
      pinMode(22, INPUT_PULLUP); // Reed switch - Row1
      pinMode(24, INPUT_PULLUP); // Reed switch - Row2
      pinMode(26, INPUT_PULLUP); // Reed switch - Row3
      pinMode(28, INPUT_PULLUP); // Reed switch - Row4
      pinMode(32, OUTPUT);
      digitalWrite(32, HIGH);
      lcd.setCursor(0, 0);
      lcd.print("hello");
    }

When I run the above code I get weird characters in my LCD. I removed all the connections to the pins` defined in pinMode and left only the lcd connections but kept the pinMode and digitalWrite statements in the code, but am still getting weird characters. But when I remove the pinMode and digitalWrite statements from my code the lcd works fine. Can anyone help me out.

Edit:
Another weird thing happened, I removed all the pinMode and digitalWrite statements do my setup() had only Serial.begin() and lcd.begin() and I only had the lcd connections. Now I put this code to print into an function called lcdprintMove() and there were other functions too which were performing other tasks when I ran it as such I got weird characters in the LCD but when I removed all of the other functions,the lcd printed fine. From this I was able to conclude that this problem can't be because of the supply but has to be something else. But I still can't figure it out.

Problem Solved

Today I commented all the digitalWrite statements and uploaded the program and it worked! So,  I am going to connect the lcd onto a separate arduino and communicate serially. Someone suggested the solution of putting a cap to ground and buff the power of 5 v pin can you explain this in more detail.

Circuit diagram   Note: Rs is connected to pin 7 and E to 6

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

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

title: LCD prints weird characters when I place the print statement in setup after pinMode statements

Answers: 1

body: The capacitor between 5V and GND effectively acts as a small battery. When a sudden demand in a current relatively large occurs, the system can get that extra small amount from the cap and not experience a voltage drop.


body:
I have been working on several projects recently an made hundreds of uploads to several different boards.  I haven't had any issues to speak of.  Now I cannot upload. I have tried:

 - Disconnect all inputs and output from analog a digital ports - This is a board, nothing connected except USB.
 - Changing cables
 - Changing USB ports on my computer
 - Using a brand new out of the box Arduino Uno
 - Using example sketches, and even BareMinimum
 - Serial Loopback test - FAILED
 - Updating the driver with the one from the arduino folder
 - Using an unsigned driver
 - Manually setting the windows driver speed, parity, etc.
 - Uninstalling and re-installed Arduino IDE
 - Rolling back the board manager for AVR boards to 1.20 and 1.19
 - Change programmer to AVR ISP

Here is the output:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xc7
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xc7
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Here is the verbose output:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Users\kanan\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/bin/avrdude -CC:\Users\kanan\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\kanan\AppData\Local\Temp\arduino_build_835373/BareMinimum.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\kanan\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd5
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd5

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

I am not attempting to install the beta version of the arduino ide, but I am not betting this will work.

I feel like I have tried everything that is reasonable, and more than most people would think to try, what am I missing?

-------------  UPDATES --------------

I have now moved away from the arduino IDE and am working directly with avrdude.  Still no luck.  Running:

    avrdude.exe -p m328p -c arduino -P COM6

fails.

I also tried it on my Fedora 27 box.  Here is dmesg output:

    [349004.632101] usb 2-1.5: new full-speed USB device number 5 using ehci-pci
    [349004.711497] usb 2-1.5: New USB device found, idVendor=1a86, idProduct=7523
    [349004.711503] usb 2-1.5: New USB device strings: Mfr=0, Product=2, SerialNumber=0
    [349004.711507] usb 2-1.5: Product: USB2.0-Serial
    [349004.713405] ch341 2-1.5:1.0: ch341-uart converter detected
    [349004.714652] usb 2-1.5: ch341-uart converter now attached to ttyUSB0

then I ran this:

    $ dmesg | grep tty

And got this:

    [    0.000000] console [tty0] enabled
    [    0.781927] 00:06: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
    [   14.034377] usb 2-1.5: ch341-uart converter now attached to ttyUSB0

I then run this:

    $ avrdude -p m328p -c arduino -P /dev/ttyS0

and get this:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

    avrdude done.  Thank you.

At this point I also tried

    $ avrdude -p m328p -c arduino -P /dev/ttyUSB0

Same result.  At this point it seems to me I have a few fried arduinos.  They were fine yesterday, but today, they're toast.  Three computers, three cables, three arduinos, all the same result.

So, from here.  Has anyone heard of a bad cable frying an arduino?

title: Can't upload to arduino boards anymore

Answers: 2

body:
Since your USB ports likely work for other things (like your keyboard) and you have tried several arduinos, cables etc, now try Knoppix - it has both Arduino IDE (not the most recent version) and avrdude.
https://unetbootin.github.io or
https://www.pendrivelinux.com/install-knoppix-6-to-a-usb-flash-drive-in-windows
and
http://www.knopper.net/knoppix-mirrors/index-en.html

If it does not work, have a look through the boot log, or more quickly `dmesg` after plugging your arduino in and trying an upload.

Worth noting: the 328p target is not correct for mega, use e.g.: `avrdude -vv -p atmega2560 -b115200 -c wiring -P COM3` or `avrdude -vv -p atmega2560 -c wiring -P /dev/ttyUSB0`. Omitting `-b115200` should be no problem with the mega. Try this before torturing yourself further...

If you still get errors, and have not fiddled with clockspeed or anything else, it will be very strange indeed.

body:
I'm an idiot.

I should have looked more carefully.

Because I have used these boards so extensively, I figured that I knew the dip switches by heart.  Everything started to go wrong when I got confused switching from the Uno to the ESP.

Here is the reference from https://robotdyn.com/uno-wifi-r3-atmega328p-esp8266-32mb-flash-usb-ttl-ch340g-micro-usb.html:

[![DIP switch positions][1]][1]

Meaning this DIP switch pattern is for the ESP: [![UNO DIP Switch Settings][2]][2]

And This is for the UNO:

[![UNO DIP Switch Setting][4]][4]

THANK YOU ALL FOR THE TIME AND EFFORT YOU PUT IN TRYING TO HELP ME!!!

tldr: Check your DIP switches.

  [1]: https://i.stack.imgur.com/LM266.jpg
  [2]: https://i.stack.imgur.com/UARvW.jpg
  [4]: https://i.stack.imgur.com/4umNX.jpg


body: I wrote a "Hello world" type of sketch using the Arduino IDE and uploaded it to an esp8266. I used no libraries, or any kind of WiFi commands. However, when I powered up the esp8266, it was visible under "available connections" when I connected to WiFi using a Windows laptop. I was told that the firmware on an esp8266 (which has the AT commands) is being flashed when the Arduino IDE uploads a sketch. Why do I still see the esp8266 when my laptop connects to WiFi?

title: Why is my esp8266 still visible under "available connections" when connecting to WiFi?

Answers: 1

body:
It's because you don't actively program the WiFi - you just give instructions to configure it, and those instructions are stored elsewhere in flash, separate to a sketch.  The WiFi code is always included and always running regardless of what you include or don't include in your sketch.

Uploading a sketch doesn't replace those settings, and so they remain.

To change the settings you will need to write a sketch that specifically changes them - maybe set it to STA mode, for example.

If you want to completely blank the ESP8266, including the WiFi settings, there is an option in the Tools  menu in the IDE to Erase Flash.


body:
I am using an arduino mega. I'm trying to use interrupts in one of my programs.
I have 8 pins that I will need to make separate interrupts for.

The pins are 40 - 47. These pins are attached to limit switches, so when the limit switch is pressed or not it'll indicate that via digitalRead().

    #define switch_1 43     // Pin 43 is connected to Switch 1 (1: X+)
    #define switch_2 42     // Pin 42 is connected to Switch 2 (1: X-)
    #define switch_3 41     // Pin 41 is connected to Switch 3 (1: Y+)
    #define switch_4 40     // Pin 40 is connected to Switch 4 (1: Y-)
    #define switch_5 46     // Pin 46 is connected to Switch 5 (2: FR)
    #define switch_6 47     // Pin 47 is connected to Switch 6 (2: BL)
    #define switch_7 45     // Pin 45 is connected to Switch 7 (2: BR)
    #define switch_8 44     // Pin 44 is connected to Switch 8 (2: FL)
    int interruptVar = 5;

In my set up function I have:

    attachInterrupt(digitalPinToInterrupt(switch_6), tightenStrings1, CHANGE);

Then I have:

    void tightenStrings1()
    {
      interruptVar = 9;

    }

When I change the status of the limit switches, by pressing them or unpressing them, this function never activates. The variable interruptVar is still 5.

What am I doing wrong?

Also, Serial isn't the problem in this case. I understand now not to use it though, but still doesn't solve the problem. Additionally I tried instead of CHANGE using RISING or FALLING and still no changes.

I have a feeling it's because the pins I'm using aren't technically interrupt pins...is there a way to make them usable as interrupt pins? I'm not allowed to change the pins being used, and using an interrupt is the best solution for the coding portion I'm working on.

title: Arduino Mega: Interrupt not working? Use any pin for interrupt?

Answers: 2

body:
You are right when you say "technically they aren't interrupt pins".

The only pins you can use as interrupts are 2, 3, 18, 19, 20 and 21. There is no way of changing that. You can't magic more interrupts out of thin air.

However there is a *different* interrupt system that may help you out - the *pin change* interrupts.  These are harder to work with since they are grouped into sets of pins that share the same interrupt, but there are far more pins with this kind of interrupt available. Note that you still have to be careful which pins you choose.

There are a couple of libraries available to help you configure the PCINT registers should you need it.

body:
Limit switch implies some mechanical thing is closing the switches, which hardly needs an interrupt as that will be pretty slow electronically. Simple polling is probably more than sufficient at the top of loop() or similar.

You can declare all the pins as INPUT_PULLUP, wire the switches to connect the pins to Gnd when pressed, then do digitalRead of each to determine its state, or put all 8 on one port and do a PORTx read

for example, and if the result is other than 0xFF, then one has been closed and you can act on it, or read it directly and act on like here for example:

    switches = PORTL;
    if (switches != 0xff){
    switch(switches){
    case 0b01111111:
    //code for switch 7
    break;
    case 0b10111111:
    // code for switch 6
    break;
    etc for 0b11011111, 11101111, 11110111, 111111011, 11111101, 111111110
    }
    }


body:
I have an ESP8266 NodeMCU which I'm using for an automatic blinds project. The NodeMCU struggles to power the servo on its own, so at the moment I am using a 5 V supply for the servo and a USB cable for the NodeMCU (with a common ground).

The servo is an inexpensive MG996R which is rated up to 7.2 V I've read that NodeMCU can take 5-10 V on the VIN pin.

After I'm done prototyping, I want to only use one power supply. What could I use? Ideally it would be something with just a wall adapter and then I can cut the other and connect that to servo and MCU.

title: How can I power a servo and Arduino from the same power supply?

Answers: 2

body: Wire the +5 and Ground from the supply to both the ESP's Vin & Ground and the servo's Vin & Ground. The only thing you have to avoid is trying to power the servo *through* the ESP.

body: You might be better off using an external supply with a voltage regulator like an LM7805. It would also be wise to add a protection diode to your servo motor if it does not already have one so that the microcontroller does not get damaged by any flyback voltages. The key thing to remember when running a supply from an Arduino is that it's on board supply current capabilities are very limited, especially in the case of a motor or servo. Good luck, I hope this helps, I recently replaced the blinds in my home and was thinking to build something similar myself!


body:
[![circuit][1]][1][![bluetooth app][2]][2]    int L1=12;

    void setup() {

      Serial.begin(9600);

      pinMode(L1,OUTPUT);

    }

    void loop() {

    char receive=Serial.read();

    if(Serial.available()>0){
        receive = Serial.read();
    }

    {

    if(receive =='A') {
      digitalWrite(L1,HIGH);
    }

    if(receive =='a') {
      digitalWrite(L1,LOW);
    }
    }
    }

  [1]: https://i.stack.imgur.com/1n5dv.jpg
  [2]: https://i.stack.imgur.com/6i6WQ.jpg

title: void loop is only run once why?it can recive only off signal?

Answers: 1

body:
    int L1=12;

    void setup() {

      Serial.begin(9600);

      pinMode(L1,OUTPUT);

    }

    void loop() {

    //char receive=Serial.read(); //This is incorrect. because after u perform this serial.read(), the received data in serial's buffer is cleared. So ...

    if(Serial.available()>0){
        receive = Serial.read(); //... at here, your 'receive' receives nothing
    }

    {

    if(receive =='A') {
      digitalWrite(L1,HIGH);
    }

    if(receive =='a') {
      digitalWrite(L1,LOW);
    }
    }
    }

Here's the correct codes.

    int L1=12;

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

    void loop()
    {
      char receive;

      if(Serial.available()>0)
      {
        receive = Serial.read();

        if(receive =='A')
        {
          digitalWrite(L1,HIGH);
        }

        else if(receive =='a')
        {
          digitalWrite(L1,LOW);
        }
      }
    }


body:
1.Reading strings sent from Arduino on RPI

Below you can see that I am communicating between a rpi and arduino serially. I am sending "start", then move_played to the rpi. The readline() reads until a newline so, first start gets read then the move_played string(it's like read the move played only after encountering the string start)

Python code on RPI

    s1 = serial.Serial('/dev/ttyACM1', 9600)
    stockfish = Stockfish('/usr/games/stockfish')
    while 1 :
        if str(s1.readline(),'UTF-8').strip('\n\r') == 'start' :
               move_played = str(s1.readline(),'UTF-8').strip('\n\r')
               print(move_played)

Code on Arduino

    void SendMove();
    String movePlayed ="e2e4";
    void setup()
    {
      Serial.begin(9600);
    }
    void loop()
    {
      SendMove();
      exit(0);
    }
    void SendMove()
    {
      Serial.println("start");
      Serial.println(movePlayed);
    }

2.Reading strings send from RPI on Arduino

The  goal for the arduino is to read the bestMove string after it reads "Rstart". But when I run the code on the rpi(sending the strings). The lcd prints "Rstart" and not the bestMove string. So from what I can see is that once the "Rstart" string is sent , the first readString() in the if condition , reads " Rstart" and the the second readString() in the print statement reads "Rstart".

Why is the string"Rstart" stll in the serial Buffer even after being read once?

Python Code on RPI

    bestMove = "b3c7"
    s1 = serial.Serial('/dev/ttyACM1', 9600)
    s1.write(bytes("Rstart","ascii"))
    s1.write(bytes(bestMove,"ascii"))

Code on Arduino

    #include "LiquidCrystal.h"
    const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // 4 bit mode
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
    void setup()
    {
      lcd.begin(16,2);
      Serial.begin(9600);
    }
    void loop()
    {
      if (Serial.available()>0)
      {
        if(Serial.readString() == "Rstart")
        {
          lcd.setCursor(0,0);
          lcd.print(Serial.readString());
          delay(10000);
          exit(0);
        }
      }
    }

title: Arduino reading string sent from Rpi multiple times

Answers: 0


body:
I'm new to C++ and arduino. I want to build an object Tree, but it did not behave like I expected. Here is the code:

TreeNode.h

    class TreeNode {

      public:
        TreeNode(String inputNodeName);
        TreeNode *children[];
        TreeNode &getChild(int index);
        int getLength();
        String nodeName;
        void addChild(TreeNode &node);
        String getName();

      private:
        int childLength;
    };

TreeNode.cpp

      TreeNode::TreeNode(String inputNodeName) {
        nodeName = inputNodeName;
        childLength = 0;
      }

      TreeNode &TreeNode::getChild(int index) {
        return *children[index];
      }

      int TreeNode::getLength() {
        return childLength;
      }

      String TreeNode::getName(){
        return nodeName.c_str();
      }

      void TreeNode::addChild(TreeNode &node) {
        children[childLength] = &node;
        childLength++;
      }

I'm initialising it in the setup function:

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

        TreeNode mainTree("main");
        TreeNode firstChild("first child");
        TreeNode secondChild("second child");
        TreeNode subChild("subschild");

        Serial.println(mainTree.getName()); //prints "main"
        Serial.println(firstChild.getName()); //prints "first child";
        Serial.println(secondChild.getName()); //prints second child";

        mainTree.addChild(firstChild);
        mainTree.addChild(secondChild);
        Serial.println(mainTree.getName()); // prints an empty string
        Serial.println(secondChild.getName()); //prints second child"

        secondChild.addChild(subChild);
        Serial.println(secondChild.getName()); //prints an empty string
    }

So my problem is, when I'm adding a child to a node, the node name is empty, or strange characters will be displayed.
I think I misunderstood passing an object by reference. Can anybody explain what I did wrong?

title: Problems with passing objects in tree structure

Answers: 1

body:
    TreeNode *children[];

That declares an array of pointers however it also requires that you assign memory to it. I never see you allocate that memory.

If you only expect a small amount of children then you can use that upper bound as a static allocation:

    #define MAX_CHILDREN 10

    //...
    TreeNode *children[MAX_CHILDREN];

Otherwise use a vector instead:

    std::vector<TreeNode *> children;


body:
I am having issues uploading to my Arduino from the IDE on Ubuntu 18.04. The error message I have received is:

> Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Uno"
avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied

I have checked other questions similiar to this one and have tried adding myself to the dialout group running:

    sudo usermod -a -G dialout username

and added permission to write:

    sudo chmod a+rw /dev/ttyUSB0

After, when I run:

    ls -l /dev/ttyUSB0

I get:

    crw-rw-rw- 1 username dialout 188, 0 jūl  2 16:09 /dev/ttyUSB0

However,I still get the same error message from the IDE.

Any help would be greatly appreciated!

title: Arduino IDE Permision Denied For Upload, Ubuntu

Answers: 3

body:
As mentioned on the official [guide for Linux][1], you need to run

 `sudo usermod -a -G dialout <username>`

with the `<username>` replaced with the username of your system.
After running this, log out and log in (or in some cases reboot the computer) and you should be good to go.

  [1]: https://www.arduino.cc/en/Guide/Linux/

body:
When you run

>ls -l /dev/ttyUSB0

you have

    crw-rw-rw- 1 username dialout 188, 0 jūl  2 16:09 /dev/ttyUSB0

**The Problem** is you have `the dev` as `<username>`, try to change to as root

    sudo chown root:dialout -R /dev/

**Note:**

One thing after your plug your USB, check your port with follow

    ll /dev/tty*

if you can see my port as ttyUSB0 or with difference name (i.g ttyUSBx / ttyACMx ).
and then try to compile your sketch with following,

    cd /path/your/arduino/installation/
    $ARDUINO-DIR(pwd)
    cd /path/your/sketch/
    $ARDUINO-INO/arduino --verify sketch.ino --board arduino:avr:uno --port /dev/ttyUSB0 --verbose //compile your sketch.ino with arduino uno board.

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

Hope this helps.

  [1]: https://i.stack.imgur.com/b6bbz.gif

body:
Arduino has added a script to the install to fix this problem.  I found it after much annoyance trying to get it to work with all these suggestions.

In the arduino-1.8.8-linuxarm.tar.xz file that you download is a script called `arduino-linux-setup.sh`

run that from commandline with your user name `./arduino-linux-setup.sh <username>`

It'll ask for the root password, and then ask you to reboot.  After that you won't have any more port trouble.

[![terminal][1]][1]

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


body:
This seems so simple but I can't solve it. (I'm new to Programming) I do not want to use EEPROM. Just store it and do the math. I strip the Azmuth and Elevation values from a satellite tracker program and need to calculate the difference the satellite has moved to turn the rotors. Here's my efforts so far as requested ...Thanks

    /*  Sketch for WXtrack satellite tracking software
     *  VE3COJ Burlington, Ontario, Canada
     *  Requires COM port and Max 232 from PC
     *  to Serial in on Arduino (Rx)
     *
     *  Download URL:  http://www.satsignal.eu/software/wxtrack.htm
     *
     *  Setup in WXtrack: Go to <Tracker menu> <Options> <Select EGIS COM port> <check box XY mode>
     *  Select a Satellite using Manual in Timeframe box.
     *  Highlight Satellite icon, Use seconds box (third box from left side) to increment satellite.
     *  Use the Sketch Monitor to see Elevation and azimuth reading from Serial port.
     *  Alternatly, one can use an array to simulate Elevation and Azimuth increments in degrees.
     */

          #include <Stepper.h>
          #include <avr/pgmspace.h>
          #define STEP 50
          #define motorSteps 600      // Number of steps to turn the motor
          #define motorPin1 8
          #define motorPin2 9
          #define motorPin3 10
          #define motorPin4 11

          // 2 EasyDriver boards will be used in final project //

              String readString, read_az, read_el;

              int el_current_store_0;           // elevation ... global value ??
              int el_current_store_1;
              int el_position;                  // final value in degrees to move rotor

              int az_current_store_1;           // azimuth ..... global value ??

           void setup() {

              Serial.begin(9600);
              Serial.println("  AZ & EL "); // so I can keep track of elevation and Azimuth
              Serial.println (" =========");
              Serial.print("");
          }

          void loop() {

               while (Serial.available()) {
                  delay(3);  //delay to allow buffer to fill
                   if (Serial.available() >0) {
                  char c = Serial.read();  //gets one byte from serial buffer
               readString += c; //makes the string readString
          }
        }

              if (readString.length() >0) {
              //Serial.println(readString); //see what was received from Serial input

              // pull out the number values required... parse the serial output
              // On WXtrack menu, select "Tracker" > "Options" > "EGIS COM" & "XY mode"
              read_az = readString.substring(3, 7);   //get the first 3 to the 6th integers (azmuth)
              read_el = readString.substring(10, 13); //get the next 10 to thee 13th integers (elevation)

             int el_current_store = read_el.toInt();  // Change String el to Integer
             int az_current_store = read_az.toInt();  // Change String Az to integer

            /* This is an attemp to calculate the difference in degrees the satellite moves. */

             int n1 = el_current_store_0;       // first elevation reading ... store it ... how?
             int n2 = el_current_store_1;       // second elevation reading ...
             int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

                                               // if result is negative, rotor changes direction

              /* Can't be done as is because the reading gets put in all variables

               * I cannot figure out how to store the number of degrees in memory (Not EEPROM)
               *  EEPROM will burn out eventually, FLASH cannot change values it appears... in docs.
               *
               * From here:
               * Store first reading from Serial port into memory.
               * Rotor moves to degrees probably 3 degrees ... read second position (if 4 degrees)
               * Subtract 3 degrees from 4 degrees equals 1 and multiply by variable STEP (200 STEP = 1 degree motor rotation)
               * Get next elevation reading and repeat subtraction...
               */

               // Print to serial monitor to see results of all values //

               Serial.print("  Elevation = ");
               Serial.println(read_el);

               Serial.print("  Azimuth = ");
               Serial.println(read_az);

               //Serial.println(el_position);
               Serial.println (" --------next-------");

               Serial.print("");

               readString="";
              }
             }

              /* 1. ========= Send Antenna to 0 degrees / Check for interrup at 0 degrees & Stop =========
                    ========= Wait for Serial input then goto 2. =========

                 2. ========= Get Az and El from Serial Port and Start Tracking ==========

                 3. ========= Store (first, second, etc. ) El and AZ =========

                 4. ========= Get Next El and Az / Subtract from one before El & Az =========

                 5. ========= Move Antenna to Next Position =======

                 6. ======== Goto 3. =========

                 7. ======== If El Equals 0, Goto 1.

                           When El = 90 degrees, (Satellite overhead) Az rotates 180 degrees and

                           El decreases, coming down to the horizon.

                          When Satellite is off to E or W, elevation does not reach 90 degrees!
             */

title: Way(s) to store an integer from the serial output and sutract it from the next Serial output

Answers: 1

body:
You have the following global variables declared:

    int el_current_store_0;           // elevation ... global value ??
    int el_current_store_1;
    int el_position;                  // final value in degrees to move rotor

    int az_current_store_1;           // azimuth ..... global value ??

But you never put anything into these variables.

Here is your relevant code that attempts to work with these values:

    // pull out the number values required... parse the serial output
    // On WXtrack menu, select "Tracker" > "Options" > "EGIS COM" & "XY mode"
    read_az = readString.substring(3, 7);   //get the first 3 to the 6th integers (azmuth)
    read_el = readString.substring(10, 13); //get the next 10 to thee 13th integers (elevation)

    int el_current_store = read_el.toInt();  // Change String el to Integer
    int az_current_store = read_az.toInt();  // Change String Az to integer

Above, you are declaring *new* variables `el_current_store` and `az_current_store` and giving them integer values converted from your input string. When you prefix a variable name with `int` (or any other type) you are declaring a new variable within that scope. In this case, the scope is the `if (readString.length() >0) {}` block. Once that block ends, those variables don't exist anymore, and every time that block runs, new variables are created there, and destroyed at the end of the block.

    /* This is an attemp to calculate the difference in degrees the satellite moves. */

    int n1 = el_current_store_0;       // first elevation reading ... store it ... how?
    int n2 = el_current_store_1;       // second elevation reading ...
    int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

Above, you declare new variables `n1`, `n2`, and `el_position`. However, you give `n1` and `n2` whatever was in `el_current_store_0` and `el_current_store_1`, but you have **never** put any value into those variables, and so they have nothing.

Once that is solved, you also need to take a look at declaring a new variable by the command:

    int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

which, because it's in a nearer scope than the global variable of the same name, is used instead of the global. And when the scope block ends, it is destroyed.

You should instead assign the computed value to `el_position` without making a new variable:

    el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

(Note, no `int` in front...)

**EDIT: To actually keep the values for the next `loop()`, you do have to store them in global (or static) variables. Something like this appears to be what you were going for:

         int el_current_store = read_el.toInt();  // Change String el to Integer
         int az_current_store = read_az.toInt();  // Change String Az to integer

        /* This is an attemp to calculate the difference in degrees the satellite moves. */

         // Added code below keeps the older value in *_1
         // Puts the newer value in *_0
         el_current_store_1 = el_current_store_0;
         el_current_store_0 = el_current_store;

         az_current_store_1 = az_current_store_0;
         az_current_store_0 = az_current_store;

         int n1 = el_current_store_0;       // first elevation reading ... store it ... how?
         int n2 = el_current_store_1;       // second elevation reading ...
         int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor


body:
I know the title is a little obtuse, let me try to explain:
I am trying to create a library of simple functions for use with my TFT Panel.

The Panel has an include file (`#include "SSD1306Wire.h"`)

I have a sketch and I have the above `#include` file referenced in the sketch
I also want to use my library `tftHelper.h` but that library needs to reference `SSD1306Wire.h` as well to get the helper functions to work.

Is there a way to reference `SSD1306Wire.h` *one* time and be able to use the reference in the functions in my helper library?

I guess, more importantly, what is the proper way to handle a situation like this?

title: Writing Libraries that use libraries that are being used in the sketch

Answers: 2

body:
The proper way to handle this is to have an [#include guard][1] in the header file to prevent the content from being included more than once.

In your header file `filename.h` you would add something like this:

    #ifndef _FILENAME_H_
    #define _FILENAME_H_

    // Your header code here

    #endif /* _FILENAME_H_ */

The `#ifndef` block will prevent the code from being included more than once. Best practice is to always put include guards in header files.

  [1]: https://en.wikipedia.org/wiki/Include_guard

body:
A library has no way of knowing what is in your sketch. The two things are completely separate and there is no way to bridge that gap.

You can't include library A into the sketch and expect library B to know about it. Library B has to explicitly have library A included in it for library B to even have a clue what library A is.

There are two important parts to including a library. Not only does it tell the *translation unit* that you include it in what the library has in it, but it also tells the IDE that you want to use that library and to compile the source code for it.

You see, a library usually contains two distinct things - a header file (or a number of header files) and source code files.  The header file describes the library - what classes it has, any exported functions or variables, etc.  The source code *implements* the library.  When you include a library it just inserts that definition of the library (the header file) into your source code at the point of the `#include`. Just like a copy-and-paste.

The IDE does a little extra magic and associates that header file with a directory which has other files in it. It then finds the source code files in that location and compiles them.

Every file that gets compiled gets compiled separately. This is called a *translation unit* (TU) and each one is completely separate from all the others. None can know what any other file has in it, unless you explicitly tell that file to find something from somewhere else (though you don't tell it *where*, only that it "exists somewhere else"). And that is what the header files do - they tell the translation units what things are available elsewhere.

So if TU A needs resource F it needs to be told. If TU B needs resource F it also needs to be told.

And because of the IDE's extra magic your main sketch has to also be told about every library in use - whether that library is directly used by the sketch or not - so that it knows to go and find and compile the source code for that library.


body: I want to move away from Arduino IDE and start directly working with avrdude. Can anyone tell me some resources and tips on starting and moving forward with using C/embedded C to access more functionality.Would appreciate some help.

title: getting started with programming Arduino board in C/embedded c

Answers: 1

body:
Not an exhaustive answer, but one step would be to realize what the Arduino IDE does behind the scenes before it gives your source code to `avr-gcc`.

From https://github.com/arduino/arduino/wiki/build-process#pre-processing

> The Arduino environment performs a few transformations to your sketch
> before passing it to the `avr-gcc` compiler:
>
>  - All `.ino` files in the sketch folder (shown in the IDE as tabs with no    extension) are concatenated together, starting with the
> file that    matches the folder name followed by the others in
> alphabetical order,    and the `.cpp` extension is added to the
> filename.
>
>  - If not already    present, `#include <Arduino.h>` is added to the sketch. This header    file (found in the core folder for the
> currently selected board)    includes all the definitions needed for
> the standard Arduino core.
>
>  - Prototypes are generated for all function definitions in `.ino` files    that don't already have prototypes. In some rare cases
> prototype    generation may fail for some functions. To work around
> this, you can    provide your own prototypes for these functions.
>
>  - `#line` directives are added to make warning or error messages reflect the original sketch layout.
>
> No pre-processing is done to files in a sketch with any extension
> other than `.ino`. Additionally, `.h` files in the sketch are not
> automatically `#include`d from the main sketch file. Further, if you
> want to call functions defined in a `.c` file from a `.cpp` file (like
> one generated from your sketch), you'll need to wrap its declarations
> in an `extern "C" {}` block that is defined only inside of C++ files.

This is handy to know if you are trying to *port* Arduino sketches to pure `avr-gcc`.

You'll also want to have the header files that define all the various registers specific to the ATMega328p that is the heart of several of the Arduino boards. They can be downloaded as part of [Atmel Studio 7][1], which also includes `avr-gcc` and the various other toolchain utilities and scripts necessary.

You'll also want the processor's reference manual or datasheet. At this time, the data sheet is available at https://www.microchip.com/wwwproducts/en/ATmega328P in the "Documents" tab. This will lay out **everything** you ever need to know about how to use the processor, set up peripherals, rules for the order of commands, names of all the registers, etc.

  [1]: http://www.microchip.com/mplab/avr-support/atmel-studio-7


body:
I have a silly question.
Today I saw a function for arduino, that is pulseIn(). So to test what it does I applied a rectangular wave at a `pin` same as the arduino reference page did and it worked fine. There was a line in the reference page which stated :-
**Works on pulses from 10 microseconds to 3 minutes in length.**
So as it seems it will work upto `100KHz` signal. Is there any way to read signals of much higher frequency than this? like in the range of `MHz` or so?

title: Rectangular Input signal on digital pins

Answers: 2

body:
It depends on the processor. Lets assume Uno/Atmega328p at 16MHz. You might get an order of magnitude faster by writing a pulsein() function in assembler. Finding out sounds like a fun project!

To go much beyond that, you'll probably need hardware support.

body:
Reading high frequency signals can be done. It's possible to read signals up to about 6MHz or maybe even higher (depending on the system clock frequency).

That is, as long as all you want to know is the fundamental frequency of the signal.

Pin 5 of the Arduino Uno (PD5) is connected to Timer 1 and can be set to be the clock source for that timer.  By connecting that to your signal and allowing the timer to count up from zero using that signal as the clock source, and then waiting for a pre-defined time period, you can easily find how many clock pulses have arrived from your signal in that time. From that, you can calculate the frequency of the signal.

> The Timer/Counter can be clocked by an internal or an external clock source. The clock source is
selected by the Clock Select logic which is controlled by the Clock Select bits in the Timer/Counter control
Register B (TCCR1B.CS[2:0]).

Since all you are working with us the number of pulses over a given period you lose any information such as the duty cycle of the signal.

You should read [the datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) **section 20: "TC1 - 16-bit Timer/Counter1 with PWM"** for more detail about how you can use the timer to count the frequency of a signal.


body:
I am using Arduino 1.8.5 ide. I am just creating a class with two typename which name is "Map". This class takes all int and String variations. Like;

    class Map<int, int>;
    class Map<int, String>;
    class Map<String, int>;
    class Map<String, String>;

    Map<int, String> *list = new Map<int, String>();

If I create instance of this class like above in Main.ino file then everything is ok. But if I create it another file with .h extension which is "Test.h" then compilation fails. These are files;

    Main.ino
-
    #include "Map.h"
    #include "Test.h"

    Test *test = new Test();
    Map<int, String> *list = new Map<int, String>();

    void setup() {

    }

    void loop() {

    }

Map.cpp
-
    #include "Arduino.h"
    #include "Map.h"

    template<typename E, typename T> Map<E, T>::Map()
    {

    }

    template class Map<int, int>;
    template class Map<int, String>;
    template class Map<String, int>;
    template class Map<String, String>;

Map.h
-

    #ifndef Map_h
    #define Map_h

    #include "Arduino.h"

    template<typename E, typename T> class Map {

    public:
     Map();
     ~Map();
    };

    #endif

Test.h
-

    #ifndef _Test_h
    #define _Test_h

    #include "Arduino.h"
    #include "Map.h"

    class Test
    {
    public :
     Test();
     ~Test();
     Map<int, String> *list = new Map<int, String>();
    };

    #endif

Error is;

    In file included from C:\Users\zafer\Desktop\Main\Main.ino:3:0:
    Test.h:14: error: expected ';' at end of member declaration
      Map<int, String> *list = new Map<int, String>();

                                            ^

    Test.h:14: error: expected unqualified-id before '>' token
      Map<int, String> *list = new Map<int, String>();

                                                  ^

    Test.h:14: error: wrong number of template arguments (1, should be 2)
      Map<int, String> *list = new Map<int, String>();

                                       ^

    In file included from C:\Users\zafer\Desktop\Main\Main.ino:2:0:
    Map.h:6: error: provided for 'template<class E, class T> class Map'
     template<typename E, typename T> class Map {

                                            ^
    exit status 1
    expected ';' at end of member declaration

Sorry, If it's been already resolved and I couldn't find it.

Thank you.

title: compile error when using two typename in template class

Answers: 1

body:
In this class declaration:

    class Test
    {
    public :
        Test();
        ~Test();
        Map<int, String> *list = new Map<int, String>();
    };

This line is wrong:

        Map<int, String> *list = new Map<int, String>();

You can't execute procedural code when declaring a class. That has to go into the constructor or some other function.

For example, this compiles without errors:

## Test.h

    #ifndef _Test_h
    #define _Test_h

    #include "Arduino.h"
    #include "Map.h"

    class Test
    {
    public :
        Test() { list = new Map<int, String>; } ;
        ~Test();
        Map<int, String> *list;
    };

    #endif


body:
I have three light sensors  TSL2591, of signal I2C, that I need to connect (together) to an Arduino Mega. However, I'm not very sure of how share the SDA and SCL pins of the three sensors and I don't know how to change their address for the Arduino to read and show the data of each sensor.

I have already read sensor's [datasheet][1] but there is not much information about this.

  [1]: https://cdn-shop.adafruit.com/datasheets/TSL25911_Datasheet_EN_v1.pdf

title: Sensor TSL2591 with Arduino Mega

Answers: 1

body:
Looking at the datasheet, the TSL2591 does not *appear* to have a comfigurable address mechanism, therefore you are most likely obliged to use an I2C Multiplexer.

One example of such a device is the [TCA9545A][1], *Low Voltage 4-channel I2C and SMbus Switch With Interrupt Logic and Reset Functions*, that can split one I2C line into 4 buses.

[![TCA9545A pinout][2]][2]

They are very easy to use and the pinout (and datasheet) are self explanatory.

Don't forget that you will need 3k3 Ω resistors on the `INT`, `RESET`, `SDA` and `SCL` lines from the Arduino *and* on **each** of the `INTx`, `SDx`, and `SCx` lines from the TCA9545A:

[![TCA9545A Typical Application Schematic][3]][3]

  [1]: http://www.ti.com/lit/ds/symlink/tca9545a.pdf
  [2]: https://i.stack.imgur.com/EBsjG.png "TCA9545A pinout"
  [3]: https://i.stack.imgur.com/I3Kwy.png "TCA9545A Typical Application Schematic"


body:
Can someone help me what is the meaning of this sketch? It always outputs in the serial monitor:

    Firmware Version: 0x1C = (unknown)
    Scan PICC to see UID, SAK, type, and data blocks...

This is the code of the [MFRC522 library][1] I use:

    #include <SPI.h>
    #include <MFRC522.h>

    constexpr uint8_t RST_PIN = 9;          // Configurable, see typical pin layout above
    constexpr uint8_t SS_PIN = 10;         // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
       Serial.begin(9600);   // Initialize serial communications with the PC
       while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
       SPI.begin();      // Init SPI bus
       mfrc522.PCD_Init();   // Init MFRC522
       mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
       Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
    }

    void loop() {
       // Look for new cards
       if ( ! mfrc522.PICC_IsNewCardPresent()) {
         return;
       }

       // Select one of the cards
       if ( ! mfrc522.PICC_ReadCardSerial()) {
         return;
       }

       // Dump debug info about the card; PICC_HaltA() is automatically called
       mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    }

  [1]: https://github.com/miguelbalboa/rfid

title: MFRC522: Firmware Unknown

Answers: 2

body:
The mention of `unknown` in the output line:

    Firmware Version: 0x1C = (unknown)

isn't a good sign.

Run the `firmware_check` example to verify that first, before trying to run other code.

The `unknown` is output by [line 1302][1] of [MFRC522.cpp][2]:

  default:   Serial.println(F(" = (unknown)"));

The [`firmware_check`][3] example states on [line 49][4]:

      Serial.println(F("Only known versions supported"));

So, your hardware (i.e. the reader) *may* not be supported.

The only thing I can suggest is try another reader. Also, read the [README][5], there maybe some thing there, or contact the author and/or [raise an issue][6] to see if you can get support for your version of the firmware (`0x1C`) added.

  [1]: https://github.com/miguelbalboa/rfid/blob/master/src/MFRC522.cpp#L1302
  [2]: https://github.com/miguelbalboa/rfid/blob/master/src/MFRC522.cpp
  [3]: https://github.com/miguelbalboa/rfid/blob/master/examples/firmware_check/firmware_check.ino
  [4]: https://github.com/miguelbalboa/rfid/blob/master/examples/firmware_check/firmware_check.ino#L49
  [5]: https://github.com/miguelbalboa/rfid/blob/master/README.rst
  [6]: https://github.com/miguelbalboa/rfid/issues

body:
Put a `delay(5)` after

```
mfrc522.PCD_Init();   // Init MFRC522
```

and it will show the correct firmware version.


body:
While I was trying to change the fuse bits of ATmega328P of my Arduino pro mini using a USBasp device to operate it at 3.3 V/8 MHz, it failed due to the bad connection I guess. After that, the USBasp programmer can't detect the chip.

Does the MCU get bricked/locked?

How can I recover this?

Is there any way to solve this problem using an AVR Dragon board? If yes, please let me know the whole process.

title: ATmega328P of Arduino Pro Mini not responding

Answers: 1

body:
> Does the MCU get bricked/locked?

Yes, it's possible. The chip requires a valid clock to run, even when programming, so if the clock settings are corrupt or were set wrong it will no longer be programmable through ICSP.

> How can I recover this?

Depending on what has actually happened you can either [supply an external clock signal](http://shepherdingelectrons.blogspot.com/2016/03/recovering-atmega328p-chip-from.html) to the chip to get it working again, or you may need to [reprogram the chip through the *parallel programming interface*](https://www.gammon.com.au/forum/?id=12898), also known as *HVP* (High Voltage Programming).

> Is there any way to solve this problem using AVR Dragon board?

Yes, the Dragon can do parallel programming. You can read more about how to fix fuses with it [here](http://mythopoeic.org/avr-dragon-fixing-bad-fuse-settings/).


body:
    #define LIN_OUT 1   // Include the resources for the linear output function
    #define Adafruit_ZeroFFT 256  // Sets the ZeroFFT length to 256 points
    #define MERR 10     // Number of error values to store in elist[MERR]
    #define PID_ON 1    // Use PID feedback or not
    #define TRI_PERIOD 100 // Half-period of triangle wave in loops
    #define F_BLACKMAN 0.02463994238109641755656975202572 // Osillation freq. for Blackman filter
    #define ARM_MATH_CM0PLUS
    #include <arm_common_tables.h>
    #include <arm_math.h>
    #include <Adafruit_ZeroFFT.h>
    #include <SPI.h>

    // Photodiode array variables

    byte CLKpin = 4;    // Arduino pin delivering the clock pulses to pin 3 (CLK) of the TSL1402R
    byte SIpin = 5;     // Arduino pin delivering the SI (serial-input) pulse to pin 2 of the TSL1402R
    byte AOpin0 = A1;    // Arduino pin connected to pin 4 (analog output 1)of the TSL1402R
    byte AOpin1 = A2;    // Arduino pin connected to pin 8 (analog output 2)of the TSL1402R

    // Variables for determining the displacment from the ZeroFFT

    int maxindex;       // Index of the maximum of the ZeroFFT
    float maxvalue;     // For comparing the values of the ZeroFFT to find the global maximum
    double kmax;        // Spatial wavenumber corresponding to the dominant fringe modulation Fourier component
    float Am;           // Real part of Fourier coefficent corresponding to kmax
    float Bm;           // Imag part of Fourier coefficent corresponding to kmax
    float theta;        // Phase angle of Fourier transform at kmax
    float preTheta = 0; // Storage for previous value of phase angle
    int Nwrap = 0;      // Number of phase wraps
    float displacement; // Displacement in nanometers
    float predisplacement; // Storage for initial value of displacement
    int w = 0;
    int prevw = 0;
    int wdiff = 0;

    // PID Variables

    unsigned long lastTime;
    double Output=0;  // Output value for PID (voltage to the piezoelectric actuator (in millivolts))
    double Setpoint;  // Desired value of displacement (in nm)
    double kp = 0 / 1;    // 0 proportional gain for PID
    double ki = 2/1;  // (1000 / (138.5)) integral gain for PID
    //double ki = 2/ 1;  // (1000 / (138.5)) integral gain for PID
    double kd = 0/ 100;    // 0 derivative gain for PID
    double error;     // Error signal; difference between setpoint and displacement (in nm)
    double preverror; // Stores previous value of error for derivative control
    float esum;       // Integral of error signal over time
    float D;          // Derivative of error signal
    unsigned long time0 = 0; // Used in calculating the derivative term
    float MSerror = 0;  // Mean squared error
    float RMSerror = 0; // Root mean squared error
    float elist[MERR];// Array of last MERR error values
    int jerr = 0;        // index of integral error term
    float runningRMSerror = 0; // RMS error calc'd from elist

    float m = 0;      // extra variables for one time calculations
    float pchange = 0;
    float lastp = 0;
    float k = 1;
    int p = 1;
    float M = 0;
    //int switchtime = 1200; // Time (in ms) between Setpoint switches

    void setup() {
      Serial.begin(9600); // Initialize serial interface to computer (i.e. serial monitor or plotter)
      INIT_PHOTO();       // Initialize the photodiode array
      READ_PHOTO();       // Read the photodiode array
      DO_ZeroFFT();           // Calculate the ZeroFFT of the photodiode array data
      FIND_PEAK_INDEX();  // Determine index of peak in ZeroFFT
      KMAX();             // Calculate spatial wavevector of the interferogram
      INIT_PHOTO();       // Maybe could be replaced by START_EXPOSURE()
      READ_PHOTO();       // Read photodiode again in preparation for next step
      PHASE_ANGLE();      // Calculate the complex phase angle of the ZeroFFT peak
      DISPLACEMENT();     // Calculate the displacement from the phase angle
      predisplacement = displacement; // Save the initial displacement corresponding to center of PZT range
      Setpoint = 0;       // Define the initial setpoint
      delay(100);         // Allow things to settle before beginning loop
      START_EXPOSURE();   // Turn on the photodiode array and begin integrating
    }

    void loop() {
      KMAX();                 // Calculate kmax from previous cycle's ZeroFFT
      READ_PHOTO();           // Read photodiode array
      PHASE_ANGLE();          // Calculate complex phase angle corresponding to kmax peak
      WRAPPING();            // Determine if a phase wrap occurred
      DISPLACEMENT();        // Calculate the displacement from the unwrapped phase
      DO_ZeroFFT();              // Calculate the ZeroFFT of the photodiode array data
      FIND_PEAK_INDEX();       // Determine index of peak in ZeroFFT
      //OSC_SET();             // Oscillate the setpoint up and down
      PID_LOOP();              // Perform feedback to follow the setpoint (if PID_ON is set to 1)
      //OSC_DAC();               // Send an oscillating voltage to the DAC
      //TRI_DAC();              // Send a triangular wave voltage to the DAC
      START_EXPOSURE();          // Turn on the photodiode array and begin integrating for next cycle
      SERIAL_PRINT();               // Print some outputs to the serial USB port
    }

    // Photodiode functions

    void ClockPulse() { // For sending clock pulses during reading of photodiode
      delayMicroseconds(1);
      digitalWrite(CLKpin, HIGH);
      digitalWrite(CLKpin, LOW);
    }

    void INIT_PHOTO() { // Intialization of photodiode
      // Initialize two Arduino pins as digital output:
        pinMode(CLKpin, OUTPUT);
        pinMode(SIpin, OUTPUT);
      // To set up the ADC, first remove bits set by Arduino library, then choose

        for ( int i = 0; i < 14; i++ )
        {
          digitalWrite(i, LOW);
        }
      // Clock out any existing SI pulse through the ccd register:
        for (int i = 0; i < 260; i++)
        {
          ClockPulse();
        }
      // Create a new SI pulse and clock out that same SI pulse through the sensor register:
        digitalWrite(SIpin, HIGH);
        ClockPulse();
        digitalWrite(SIpin, LOW);
        for (int i = 0; i < 260; i++)
        {
          ClockPulse();
        }
    }

    void READ_PHOTO() { // Read the photodiode

      // Stop the ongoing integration of light quanta from each photodiode by clocking in a SI pulse
      // into the sensors register:
      digitalWrite(SIpin, HIGH);
      ClockPulse();
      digitalWrite(SIpin, LOW);

      // Next, read all 256 pixels in parallel. Store the result in the array. Each clock pulse
      // causes a new pixel to expose its value on the two outputs:
      for (int i = 0; i < 128; i++)
      {
        delayMicroseconds(20);  // We add a delay to stabilize the AO output from the sensor
        ZeroFFT_input[2 * i] = analogRead(AOpin0);        // Output of first half of photodiode array
        ZeroFFT_input[2 * i + 1] = 0;                     // Store zero in the "imaginary" part of the array
        ZeroFFT_input[2 * i + 256] = analogRead(AOpin1);  // Output of second half of photodiode array
        ZeroFFT_input[2 * i + 257] = 0;                   // Store zero in the "imaginary" part of the array
        ClockPulse();
      }

      // Next, AGAIN stop the ongoing integration of light quanta from each photodiode
      // by clocking in a SI pulse. This is necessary because during the readout operation,
      // the 18th clock pulse starts the integration of light intensity again.
      // This way we can turn on the integration when we want using the START_EXPOSURE() command.
      digitalWrite(SIpin, HIGH);
      ClockPulse();
      digitalWrite(SIpin, LOW);

      // The photodiode remains OFF after this function completes.
      // Call START_EXPOSURE() to turn on the photodiode array and begin integrating.
    }

    void START_EXPOSURE() {
      // The photodiode array starts integrating once 18 clock pulses have passed.
      // At that time, the photodiodes are once again active. We clock out the SI pulse through
      // the 256 bit register in order to be ready to halt the ongoing measurement at our will
      // (by clocking in a new SI pulse):
      // To be used after all calculations are finished, but
      // before the next photodiode read operation.
      for (int i = 0; i < 260; i++)
      {
        if (i == 18)
        {
          // Now the photodiodes goes active..
          // An external trigger can be placed here
        }
        ClockPulse();
      }
      // Uncomment the next line to increase the integration time.
      //delay(15);// <-- Add 15 ms integration time
    }

    //Calculation Functions

    void DO_ZeroFFT() {  // Performs the ZeroFFT
      ZeroFFT_reorder();  // Reorders the ZeroFFT_input array to allow the ZeroFFT_run() command to be used
      ZeroFFT_run();      // This is the function that actually does the ZeroFFT
      ZeroFFT_mag_lin();  // Produces a variable ZeroFFT_lin_out that contains the absolute values of the ZeroFFT, 128 elements long.
    }

    void FIND_PEAK_INDEX() { // Finds the index of the major peak in the ZeroFFT
      maxvalue = 0;
      maxindex = 0;
      for (int i = 5; i < 128; i++) // Go through each element of the ZeroFFT (skip the DC peak)
      {
        if (ZeroFFT_lin_out[i] > maxvalue)
        // If the magnitude is larger than the previously seen maximum...
        {
          maxvalue = ZeroFFT_lin_out[i]; // ...store the new max...
          maxindex = i;              // ...and the index at which it occurs.
        }
      }
    }

    void KMAX() {
      // Calculates the spatial wavevector of the interferogram corresponding
      // to the peak in the ZeroFFT.
      kmax = 2 * PI / 256 * maxindex;
    }

    void PHASE_ANGLE() { // Calculates the complex phase angle of the ZeroFFT peak
      // NOTE: This function must be called BEFORE the ZeroFFT is calculated.
      Am = 0;
      Bm = 0;
      for (int i = 0; i < 256; i++) // Calculate the real and imag Fourier components
      {
        Am = Am + float ((ZeroFFT_input[2 * i]) * cos(kmax * i)); //magnitude of real part
        Bm = Bm + float ((ZeroFFT_input[2 * i]) * sin(kmax * i)); //magnitude of imaginary part
      }
      theta = atan2(Bm, Am); // Complext phase angle (in radians)
    }

    void WRAPPING() { // Determines if a phase wrap/unwrap occured and accounts for it
      if ((preTheta ) > (0.5 * PI) && (theta) < (-0.7 * PI)) {
        // Compare the previous theat to the current theta to see if a wrap occured.
        Nwrap = Nwrap + 1; // If so, add 1 to the number of wraps.
      }
      if ((preTheta) < (-0.7 * PI) && (theta) > (0.5 * PI)) {
        // If an unwrap occured (a phase wrap in the other direction)...
        Nwrap = Nwrap - 1; // ...then subtract 1 from the number of wraps.
      }
      preTheta = theta; // Store the current theta for the next cycle
    }

    void DISPLACEMENT() { // Calculate the displacement after the phase angle is determined
      m =   2 * PI * Nwrap;
      //M = theta + m;
      displacement = ((-(theta + m) * 632) * (1 / (4 * PI)) * (1 / sqrt(2))) - predisplacement;
      //displacement = ((-(theta + m) * 632) * (1 / (4 * PI)) * (0.80)) - predisplacement;
    }

    // Servo Functions

    void PID_LOOP() { // Performs feedback signal for PID control
      error = Setpoint - displacement;

      // Store the current error signal; overwrite if necessary
      if( jerr >= MERR ){
        jerr = 0;
      }
      elist[jerr] = error;
      jerr++;

      // Calculate the running RMS error
      runningRMSerror = 0;
      for(int i=0; i<MERR; i++) {
        runningRMSerror += pow(elist[i],2);
      }
      runningRMSerror = sqrt(runningRMSerror/MERR);

      // Calculate the mean-squared and root-mean-square errors over all time
      MSerror = (k - 1) / k * MSerror + pow(error, 2) / k;
      RMSerror = sqrt(MSerror);
      k = k + 1;

      // Integral of error over all time
      esum = esum + error;

      // Derivative of error
      time0 = millis();
      D = (error - preverror) / (time0 - lastTime);

      // The feedback signal (in millivolts)
      // The minus signs are to make sure the piezo moves in the right direction
      Output = -(kp * error) -(ki * esum) -(kd * D);

      // Send the feedback to the DAC if PID_ON is 1
      /*if (PID_ON) {
        val = offset + Output;
        val = max(val, 0);    // Constrain the output voltage so that is stays in range
        val = min(val, 4096);
        DAC_TRANSFER();
      }

      // Save the current time and error for calc'ing the derivative next cycle
      lastTime = time0;
      preverror = error;*/
    }

    void SERIAL_PRINT(){

      Serial.print(displacement);
      Serial.print(" , ");
      Serial.println(millis());
      Serial.print(" ") ;
    }

Hi every one. I tried to compile this code for the Arduino Zero which was originally written for the Arduino Uno. I got the following errors. What am I doing wrong?

Error:

    /Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void READ_PHOTO()':
    DIS_SET_V04_Arduino-zero:144: error: 'ZeroFFT_input' was not declared in this scope
         ZeroFFT_input[2 * i] = analogRead(AOpin0);        // Output of first half of photodiode array
         ^
    /Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void DO_ZeroFFT()':
    DIS_SET_V04_Arduino-zero:186: error: 'ZeroFFT_reorder' was not declared in this scope
       ZeroFFT_reorder();  // Reorders the ZeroFFT_input array to allow the ZeroFFT_run() command to be used
                       ^
    DIS_SET_V04_Arduino-zero:187: error: 'ZeroFFT_run' was not declared in this scope
       ZeroFFT_run();      // This is the function that actually does the ZeroFFT
                   ^
    DIS_SET_V04_Arduino-zero:188: error: 'ZeroFFT_mag_lin' was not declared in this scope
       ZeroFFT_mag_lin();  // Produces a variable ZeroFFT_lin_out that contains the absolute values of the ZeroFFT, 128 elements long.
                       ^
    /Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void FIND_PEAK_INDEX()':
    DIS_SET_V04_Arduino-zero:196: error: 'ZeroFFT_lin_out' was not declared in this scope
         if (ZeroFFT_lin_out[i] > maxvalue)
             ^
    /Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void PHASE_ANGLE()':
    DIS_SET_V04_Arduino-zero:217: error: 'ZeroFFT_input' was not declared in this scope
         Am = Am + float ((ZeroFFT_input[2 * i]) * cos(kmax * i)); //magnitude of real part
                           ^
    exit status 1
    'ZeroFFT_input' was not declared in this scope
    /Users/RAJU/Documents/Arduino/libraries/Adafruit_Zero_FFT_Library/examples/mic_tft/mic_tft.ino
    /Users/RAJU/Documents/Arduino/libraries/Adafruit_Zero_FFT_Library/examples/normalized/normalized.ino

title: How to change the FFT function of the Arduino Uno for the Arduino Zero?

Answers: 1

body:
The [Adafruit ZeroFFT library][1] is not a drop in replacement for the [FFT Library][2].

You can't easily use the same code for both.

  [1]: https://github.com/adafruit/Adafruit_ZeroFFT
  [2]: http://wiki.openmusiclabs.com/wiki/ArduinoFFT


body:
I am trying to develop a burglar alert system. I am using PIR sensor, Arduino Mega and SIM800L. I have connected PIR sensor to interrupt pin. Whenever motion is dected, a function corresponding to the interrupt will be called. In that function I am sending a SMS to notify with an alert message. If motion is detected 2 times, I will call the emergency contact number.

This is the code I have written.

    #include <SoftwareSerial.h>
    #define PIR1 2
    #define SIREN 13
    #define statusLED 12

    SoftwareSerial SMS(11, 10);// rx(11-arduino) connect to tx(gsm module)
                             // tx(10-arduino) connect to rx(gsm module)

    String CONTACT1 = "xxxxxxxxxx";  //mobile number

    boolean status;
    byte motionCtr = 0;
    unsigned long latestMovementTime = 0;

    void setup() {
      pinMode(PIR1,INPUT);
      pinMode(SIREN,OUTPUT);
      pinMode(statusLED,OUTPUT);

      Serial.begin(9600);
      SMS.begin(9600);
      SMS.println("AT+CNMI=2,2,0,0,0");

      delay(5000);
      activateSystem(0);
    }

    void loop() {
      unsigned long currentTime = millis();
      //If motion is not dected for 5 minutes, turn off the siren.
      if(currentTime - latestMovementTime > 300000 && motionCtr>=1){
        stopSiren(0);
      }
      delay(500);
    }

    void activateSystem(byte manual){
      delay(60000); //warm up time for PIR sensor
      attachInterrupt(0,motionDetected,RISING);

      status = true;
      digitalWrite(statusLED,HIGH);

      if(manual){
        Serial.println("System ACTIVATED by SMS.");
        notifyBySMS("System ACTIVATED SMS.");
      }else{
        Serial.println("System ACTIVATED.");
        notifyBySMS("System ACTIVATED.");
      }
    }

    void deactivateSystem(byte manual){
      detachInterrupt(0);

      status = false;
      digitalWrite(statusLED,LOW);

      if(manual){
        Serial.println("System DEACTIVATED by SMS.");
        notifyBySMS("System DEACTIVATED SMS.");
      }else{
        Serial.println("System DEACTIVATED.");
        notifyBySMS("System DEACTIVATED.");
      }
    }

    void motionDetected(){
      startSiren("Motion at bedroom door.");
    }

    void startSiren(String msg){
      //Record the time of latest motion dected.
      latestMovementTime = millis();

      motionCtr++;
      Serial.print("Ctr="+motionCtr);
      Serial.println(msg);
      notifyBySMS(msg);

      //Start the siren only if motion is detected 2 times
      if(motionCtr==2){
        digitalWrite(SIREN,HIGH);
        Serial.println("Siren STARTED.");
        notifyBySMS("Siren STARTED.");
        call(CONTACT1);
    //    call(CONTACT2);
    //    call(CONTACT3);
      }
    }

    void stopSiren(byte manual){
      motionCtr = 0;
      Serial.println("Ctr="+motionCtr);
      digitalWrite(SIREN,LOW);
      if(manual){
        Serial.println("Siren STOPPED manually.");
        notifyBySMS("Siren STOPPED manually.");
      }else{
        Serial.println("Siren STOPPED");
        notifyBySMS("Siren STOPPED.");
      }
    }

    void sendSMS(String mobileNumber, String msg){
      Serial.println("Sending SMS to "+mobileNumber);
      //AT command for text mode of gsm module
      SMS.println("AT+CMGF=1");
      delay(100);
      SMS.println("AT+CMGS=\""+mobileNumber+"\"\r");
      delay(100);
      // the text you want to send
      SMS.println(msg);
      delay(100);
      // ASCII code of CTRL+Z
      SMS.println((char)26);
      delay(5000);
      Serial.println("SMS sent to "+mobileNumber);
    }

    void call(String mobileNumber){
      Serial.println("Calling..."+mobileNumber);
      SMS.println("AT+CMGF=0"); //AT command for PDU mode of gsm module
      SMS.println("ATD"+mobileNumber+";");
      delay(45000);
      SMS.println("ATH");
    }

    void notifyBySMS(String msg){
      sendSMS(CONTACT1,msg);
      delay(1000);
    //  sendSMS(CONTACT2,msg);
    //  delay(1000);
    //  sendSMS(CONTACT3,msg);
    //  delay(1000);
    }

I am receiving the SMS from `setup()`. But I am not receiving the SMS that I have sent from interrupt routine. Also I am receiving the call only sometime, it is random. I guess this is because I am using `delay()` in interrupt routine.

How can I implement such logic without `delay()`.

title: Unable to send SMS from interrupt routine

Answers: 1

body:
As mentioned in the comments Serial won't work in an ISR. Generally, you should do as little as possible in an ISR. Often an ISR will just set a flag to be handled in `loop()`

You will then need to refactor `loop()` to handle the flag set in the ISR. A common method is to use a [finite state machine][1].

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine


body:
I am using a [MAX6675 board](https://www.amazon.com/gp/product/B01M5CT365/ref=oh_aui_detailpage_o04_s00?ie=UTF8&psc=1) and a k-type thermal couple to measure temp. The problem is even when running the example the temp value keeps climbing.

    MAX6675 test
    27.25
    C = 27.25
    F = 130.10
    109.00
    C = 218.00
    F = 816.80
    872.00
    C = 1744.00
    F = 2624.00
    832.00
    C = nan
    F = nan
    512.75
    C = nan
    F = nan

I am using the `max6675.h` library. Is there a way to fix this?

    #include "max6675.h"

    int thermoDO = 4;
    int thermoCS = 5;
    int thermoCLK = 6;

    MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
    int vccPin = 3;
    int gndPin = 2;

    void setup() {
      Serial.begin(9600);
      // use Arduino pins
      pinMode(vccPin, OUTPUT); digitalWrite(vccPin, HIGH);
      pinMode(gndPin, OUTPUT); digitalWrite(gndPin, LOW);

      Serial.println("MAX6675 test");
      // wait for MAX chip to stabilize
      delay(500);
    }

    void loop() {
      // basic readout test, just print the current temp

       Serial.print("C = ");
       Serial.println(thermocouple.readCelsius());
       Serial.print("F = ");
       Serial.println(thermocouple.readFahrenheit());

       delay(1000);
    }

edit: Added code (https://github.com/adafruit/MAX6675-library/blob/master/examples/serialthermocouple/serialthermocouple.pde)

title: MAX6675 gives a climbing reading

Answers: 1

body: After test some other K-type thermal couples on this I am now thinking I just got a bad board. I was able to order a new one and it worked without issue