# Question
Title: How can I power a servo and Arduino from the same power supply?
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.

# Answer
> 0 votes
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.

# Answer
> 0 votes
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!

---
Tags: esp8266, power, servo, nodemcu
---


# Question
Title: Most compact method of powering Arduino from wall socket
There are a lot of methods to power an Arduino from a large range of voltages:

* USB cable from PC or from a phone charger or an USB hub
* step down converters
* step up converters
* switching power supply
* batteries (connected to the power jack or USB or to Vin)

What I can't seem to find is a small 220V-5V converter. I'd like to put an Arduino in the wall, under a light switch, so size matters.

The last resort option is to open a 5V phone charger and replace the metal prongs that go in a socket with two wires, and replace the USB socket with another pair of wires that go the Arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

# Answer
> 8 votes
> The last resort option is to open a 5v phone charger and replace the metal prongs that go in a socket with two wires, and replace the usb socket with another pair of wires that go the arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

You will probably have to do something like that.

Because of the nature of conversion between AC and DC, there has to be some large parts.\* I'm not going to go into the specifics here. There is usually a diode bridge (because AC waveforms reverse the current ~60 times a second) and a transformer (to lower the voltage for the diode bridge). They almost always include a regulator and a capacitor to make sure voltage is exact and it outputs a "clean" power supply.

*Switching power supplies, although considerably more expensive, are a lot smaller and more power efficient.

This adapter seems to be the most compact adapter I can find for 220V. You'll never get something near the size you are desiring, even with a switching power supply. I don't know the size of the Amazon adapter I gave a link for, but in the US (120V), iPhone chargers are very small and they should fit in a standard depth outlet box (with a little room left over for relays and such). If you *really* need to get everything smaller, I recommend using a ATtiny chip.

**How I recommend connecting this:**

I would avoid ripping this apart at all costs from a safety perspective. It would be really easy to send 220V to your Arduino if you're not careful. If you *absolutely have to*, you might want to coat it with some non-conductive epoxy or other coding. Note: this may act as a thermal insulator, therefore reducing the lifespan of the part. You should just coil some wire around the prongs, and then melt a little solder onto each of the terminals. Then, cover that with electrical tape and pigtail (with a wire nut) into a source power line. Note: you probably are doing wiring that could be illegal in your area. Check your local building codes before attempting this.

After that, attach a USB cord to the socket and to the Arduino or the ATtiny/ATmega328 chip 5V/GND input (of coarse, after cutting and stripping one end of the USB cord). I would also, after finalizing all the code and circuitry, seal that with some epoxy or somehow add it to an enclosure to make sure you don't fry your Arduino if a loose wire touches the Arduino circuitry.

## If you don't feel safe doing any of the above, *don't do it*. You can live without a Arduino light switch.

That being said, happy hacking! :P

# Answer
> 13 votes
I can suggest you to try this : AC DC Step Down Converter

It is as small as the Apple's tiny cube, and it can be placed inside of a wall easily. (I'm personally using this with an arduino micro)

# Answer
> 10 votes
Nowadays, most smartphones come with a charger that is linked to the USB plug of the phone.

The charger for my HTC says: **5V**, **1A**, I guess this voltage must be regulated (but I haven't checked it has the charger is sealed).

The charger itself has a female USB socket on which you can plug any USB cord to link to your Arduino.

**IMPORTANT!** I have never tried it myself! I would not bet my life on it! It would be wise to check the output voltage is well regulated.

# Answer
> 5 votes
I use this one, 5V, 3W, very small, and only $3 on Aliexpress. http://www.hlktech.net/product\_detail.php?ProId=54

# Answer
> 4 votes
The smallest is probably a plug-in USB charger such as Apple's tiny cube. The cheapest is bound to be a ~9v (output) wall-wart scrounged from the lost and found in a tourist's/traveller's hotel.

# Answer
> 4 votes
There are small board-mount AC/DC converters like this one http://www.digikey.com/product-detail/en/BP5063-5/BP5063-5-ND/658569

# Answer
> 4 votes
An obvious answer has been omitted which is: transformerless power supply. If your average power requirements are low (\<10mA) then this is the most compact way to achieve the desired voltage.

For an in-depth study see: http://ww1.microchip.com/downloads/en/AppNotes/00954A.pdf

Another solution: jeelabs.org /2011/11/27/ultra-low-power-supply/

Some limitations:

* **safety - NONE** \- your circuit might now be floating at line voltage
* heat dissipation - calculate here: www. daycounter.com/Circuits/Transformerless-Power-Supplies/Transformerless-Power-Supplies.phtml
* low current - no servos or relays
* voltage fluctuations on the line might affect the circuit

# Answer
> 4 votes
wanted to do a similar thing and I found and just ordered these:

http://uk.farnell.com/recom-power/rac03-05scr-277/conv-ac-dc-3w-90-305v-in-5v-out/dp/2289701

A fully sealed power supply, disk-shaped, 5cm diameter and 11mm thick. THey are available in 3.3V, 5V, and 12V. They are designed to be put inside walls or behind switches.

# Answer
> 4 votes
Try an LED driver. Their typical output is 11.8V DC, which is in perfect specs for the Arduino. You can find them nowadays in all shapes and sizes, round or square, low profile or boxy. A 500ma version (6W) is more than enough for your needs.

# Answer
> 3 votes
Try something like this. It's 29x15mm and does 220V AC to 5V/3W DC.

# Answer
> 2 votes
What if you replace the nearest outlet with some kind of USB Wall Socket and attach to that (either through a standard USB plug, or inside the wall) ?

# Answer
> 2 votes
This looks like the smallest and cheapest one from all of the above mentioned: http://www.ebay.co.uk/itm/AC-DC-Power-Supply-Buck-Converter-Step-Down-Module-5V-700mA-for-Arduino-U-/121355318138

# Answer
> 2 votes
Nov 2016 Here is a list of compact PCB mounted power supplies that are small (~50mmx25mmx20mm) from Mouser:

http://www.mouser.com/Power/Power-Supplies/AC-DC-Power-Modules/\_/N-dv0g5?Ns=Output+Current-Channel+1%7c0&No=25&P=1yxt7eu

These all take in 120-240VAC and provide outputs in the range of 3 - 5 vdc with varying options for current.

The 5V 1A from Meanwell (IRM-05-5) looks like a good deal at $8.52 each. http://www.mouser.com/ProductDetail/Mean-Well/IRM-05-5/?qs=sGAEpiMZZMuWiaalG5TUgH52QN1%252bIKAVmGC9ENLDVf688EuOMfqROg%3d%3d

Paul.

# Answer
> 1 votes
It's entirely dependent on whether or not you want to isolate the circuit from the mains. You could use a drop resistor a rectifier and a 5v zener diode but I do not recommend this if you are a hobbyist, in fact I don't recommend this at all, but it is done by some manufacturers with appropriate circuit protection.

---
Tags: arduino-uno, power, arduino-nano, arduino-pro-mini, electricity
---


# Question
Title: void loop is only run once why?it can recive only off signal?
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);
}
}
}

```

# Answer
```
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);
    }
  }
}

```
> -1 votes

---
Tags: arduino-uno, home-automation
---


# Question
Title: Problems with passing objects in tree structure
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?

# Answer
> 1 votes
```
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;

```

---
Tags: arduino-uno, c++, object-oriented
---


# Question
Title: Way(s) to store an integer from the serial output and sutract it from the next Serial output
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!
         */

```

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

```
> 3 votes

---
Tags: programming
---


# Question
Title: Rectangular Input signal on digital pins
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?

# Answer
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 **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.
> 1 votes

# Answer
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.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Writing Libraries that use libraries that are being used in the sketch
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?

# Answer
> 8 votes
The proper way to handle this is to have an #include guard 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.

# Answer
> 0 votes
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.

---
Tags: arduino-uno
---


# Question
Title: getting started with programming Arduino board in C/embedded c
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.

# Answer
> 2 votes
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, 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.

---
Tags: avrdude
---


# Question
Title: HC-05 bluetooth module not accepting AT commands
I have been attempting to program my HC-05 ZS-040 Bluetooth module for quite some time, and I cannot get the AT commands to return any values. I have searched google for quite some time, and I none of the answers seem to work for me. I have been following along with this website:

https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth

I am using an Arduino Mega 2560 clone by Elegoo to program this Bluetooth module. Currently I have it wired up using this diagram

https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth/HC-05-to-FTDI.png?attredirects=0

Currently I have it modified slightly to use a voltage divider between the Arduino's Tx and the HC-05 Rx, as the HC-05 works on 3.3v logic. The one possibility I think could be causing this problem is that the Arduino Mega is just interpreting all Tx incorrectly as I measured that it sounds ardoun 3.2 volts for a high voltage. According to multiple websites the HC-05 is in AT command mode when the LED flashes slowly, about once every 2 seconds, which is happening. I put it in command mode by holding down the button above the EN pin while providing power to the HC-05.

I have been using pin 14 and 15, which are Hardware Serial3 on the Arduino Mega. Here is the code I have written:

```
  /*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.
 */
#include <SoftwareSerial.h>

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("AT");
  // set the data rate for the SoftwareSerial port
  Serial3.begin(38400);
}

void loop() { // run over and over
  if (Serial3.available()) {
    Serial.write(Serial3.read());
  }
  if (Serial.available()) {
    Serial3.write(Serial.read());
  }
}

```

Any suggestions are much appreciated!

EDIT: I have now received some unrecognizable responses from the controller after sending AT multiple times, here is the screenshot, included is a video of my circuit, which shows how the LED is flashing:

https://drive.google.com/open?id=1mc8PEEnhiKpPzzy5kL9QxTvoQA3NAH6b

The only modification to the code is adding a `Serial.println("TESTING");` in the while loop that reads Serial3. I have tried using other Hardware serial ports as well, all with the same result as the above screenshot.

# Answer
Thanks for all the help! I had given up on getting Bluetooth module to work, however when working with a simple RGB LED, I noticed my mistake. I was using the ground from my breadboard power supply for the module instead of the ground from the Arduino Mega. I rewired my breadboard so the ground and power come from my Arduino Mega, and everything works perfectly! I ended up using the exact same code that I posted in my original question, so it was just that I was not using the ground from my Arduino Mega
> 1 votes

# Answer
**###### Try This : Your Code Updated With Possible Fixes ######**

After examining your code and comparing it to my working code I believe I have found a definitive answer. I'm altering your code so you can copy it and try it. I'll add comments where I've changed it.

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  // set the data rate for the SoftwareSerial port
  // notice that your comment on previous line says SoftwareSerial port
  // but you are setting the Serial3 port -- this is where we use mySerial
  // Serial3.begin(38400); // commented your line of code
  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}

```

I am confident that if you use this newly modified code it will solve your problem. I should've noticed this earlier.

**Here's the rest of my original answer**.

I have struggled with this myself. As a matter of fact it took me a few months of owning some HC-05s before I finally dug up an answer. It's been a while since I worked with it so I'll do my best to explain what to do.

**Arduino Nano**

Also, I use an Arduino Nano to do the programming of the HC-05.

**This Setup Lets You Alter HC-05**

Once you wire it up and run the program (included here) you will be able to send any of the HC-05 commands and they work great. You can change the name of the device, the 4-digit pass-code and everything.

**Crude Snapshot, But Enough To Build Simple Circuit**

I also have a crude snapshot\* of the circuit I used (at the time just for documenting it for my own memory) but I think we can work you thru it. and I know those wires are all crammed together and it almost looks like they are in the same breadboardholes but they are actually hooked up properly. I was so excited it finally worked I snapped the pic too fast.

\*see image below

Here's the code I use:

```
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  //pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  //digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor

  if (BTSerial.available())
    {
     //Serial.println("bt available...");
    Serial.write(BTSerial.read());
    }

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

```

**Does Your HC-05 Have the Button?**

Okay, so the first thing is to check to see if your HC-05 has the little button on it? If it does that has to be held when you apply power to the circuit. The HC-05 will blink and then it will be in COMMAND mode and you can let go.

**If No Button**

You can see that mine has the button. That is why the first two lines the setup() method are commented out. I don't need D9 to go high (it is not connected to the pin) because mine has the button. If yours has the button (most likely does) then you don't even have to worry about it.

**Looking Back At Your Question**

Now that I look back at your sample code it could be that you're not aware that you have to hold that button when you power up. Or you don't know that you need to connect that wire to keep the HC-05 in command mode.

**Pins For TX / RX**

That's probably the problem you are having, because everything else looks the same -- except you are using 15 and 14 for TX / RX. I am using D10 and D11 for mine and I remember something about those pins in the back of my mind so if yours still doesn't work, try switching to those and try using my code.

I remember the first time I finally got this working and I was dancing around the room. Good luck and I hope you are dancing soon. :)
> 2 votes

---
Tags: serial, arduino-mega, programming, bluetooth
---


title: Sensor TSL2591 with Arduino Mega

text:
# Question
Title: Sensor TSL2591 with Arduino Mega
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 but there is not much information about this.

# Answer
> 5 votes
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, *Low Voltage 4-channel I2C and SMbus Switch With Interrupt Logic and Reset Functions*, that can split one I2C line into 4 buses.

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:

---
Tags: i2c
---


# Question
Title: compile error when using two typename in template class
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.

# Answer
> 3 votes
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

```

---
Tags: c++, compilation-errors
---


# Question
Title: 7-Segment, 3-digit display not displaying correctly
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:

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

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

```

# Answer
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] = {{ // ...

```
> 1 votes

---
Tags: arduino-uno, display, 7-segment
---


# Question
Title: ATmega328P of Arduino Pro Mini not responding
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.

# Answer
> 2 votes
> 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 to the chip to get it working again, or you may need to reprogram the chip through the *parallel programming interface*, 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.

---
Tags: arduino-pro-mini, usbasp
---


# Question
Title: Where should a modified "pins_arduino.h" be stored for Arduino IDE compile?
Our PCB uses an ATmega2560 chip and uses most of the pins, including some that are not defined in the standard `pins_arduino.h` module, since that module only provides for the pins that are brought out to headers on the Arduino Mega2560 PCB.

We have a modified `pins_arduino.h` module that has all pins defined, but it doesn't get included in the Arduino IDE compile. It was cataloged in the same directory as the standard module (that we renamed `original`). The path where the modified module is stored is `C:/Arduino/hardware/arduino/avr/variants/mega`, where the original was also located.

In the sketch, we added `#include "pins_arduino.h"` as well as `#include <pins_arduino.h>`, but neither seemed to have included the modified module, so the extra pins are not accessible. Putting the module in the same library as the sketch didn't help either.

Any suggestions?

# Answer
Now have 2560 “full pin definition” working. This is what I think I did:

1) Download IDE with "Windows ZIP file for non admin install " from https://www.arduino.cc/en/Main/Software

2) Download pins.arduino.h from https://forum.arduino.cc/index.php?action=dlattach;topic=200887.0;attach=60348

3) Open the IDE distribution zip file and extract all files into the location where you want the IDE files and your sketches to reside. Could be anywhere.

4) Before starting arduino.exe from the extracted files, replace the pins.arduino.h file that came with the IDE, with the "all pins defined" version. It is replaced in folder path: .../arduino-1.8.5/hardware/arduino/avr/variants/mega/pins.arduino.h

5) Place sketch within the same path as everything else (e.g. create a folder like “12.My\_Sketches” inside “examples”). For example, I put my test sketch Blinky-2560 in folder path: .../arduino-1.8.5/examples/12.My\_Sketches/Blinky-2560/Blinky-2560.ino

Why it worked this time? The only difference I can see is I got the new pins file inserted in the right place before running the IDE. It is also possible the sketch has to be in the same path as the rest of the IDE (saw that somewhere!?!?). Otherwise I don’t think there was anything else different from what I was doing with the previously installed IDE.

Since the “all pins defined” file is a superset of the standard mega pins.arduino.h file, there is full compatibility with the Arduino ATmega2560 PCB. It would be great if Arduino would make this fully defined pins file the standard that comes with the IDE.

Never did get MegaCore to upload the sketch after the compile.
> 1 votes

# Answer
Add another folder in the /variant folder, and put your modified pins\_arduino.h in there. Then in boards.txt, create another section of lines like the exsting Mega section, use a new board name, and add the path to your new folder.

Adding Megacore to the IDE in a similar manner pretty much does all that for you.
> 0 votes

---
Tags: library, ide
---


# Question
Title: Unable to send SMS from interrupt routine
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()`.

# Answer
> 1 votes
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.

---
Tags: arduino-mega, interrupt
---


# Question
Title: How to change the FFT function of the Arduino Uno for the Arduino Zero?
```
#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

```

# Answer
The Adafruit ZeroFFT library is not a drop in replacement for the FFT Library.

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

---
Tags: arduino-zero
---


title: Can't upload to arduino boards anymore

text:
# Question
Title: Can't upload to arduino boards anymore
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?

# Answer
> -1 votes
# 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:

Meaning this DIP switch pattern is for the ESP:

And This is for the UNO:

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

tldr: Check your DIP switches.

# Answer
> 1 votes
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.

---
Tags: communication, bootloader, uploading
---


# Question
Title: Changing type of one variable dramatically changes compile size
I have a sketch containing the following method:

```
// Writes zeros to the complete screen clearing it:
void clearScreen(uint8_t val) {
  setDrawArea(0x00, 0x7f, 0x00, 0x07); // complete screen
  SSD1306.ssd1306_send_data_start();
  for (int c = 0; c < 128 * 8; c++) {
    SSD1306.ssd1306_send_byte(val);
  }
  SSD1306.ssd1306_send_data_stop();
}

```

The whole sketch compiles with a size of 6730 Bytes. While refactoring the code I mistakenly changed "c" to uint8\_t. After this I compiled to 4124 Bytes. Does this come from the compiler recognizing that the loop condition will never be reached and cut off all code behind or is this some kind of strange optimization event? I'm asking because I can't test the sketch in the moment.

# Answer
Without being able to proof it (since I don't have your libraries and you gave only a small part of the sketch), I think this is what happens:

user3629249 is half right. If you change `c` to type `uint8_t` it only has 8 bits (hence the Name), so its maximum value will be 255. When you add 1 to it at this value, the variable will overflow and going back to 0. Thats normal overflow behavior, like used with the Arduinos Timer registers. (No undefined behavior there) So the maximum value `c` can reach is 255.

When compared to a bigger literal the value of `c` gets promoted to the correct type, so that the two values can be compared. But a variable that is at maximum 255 is always lower than 128\*8. So you have an infinite loop there. The compiler can see this and doesn't include the functions from the rest of `clearScreen()`, since that is unreachable code.

All in all your code won't work as intended with `uint8_t`. You need a bigger type, that can hold the full range, that you operate. And this optimization is not strange, but very reasonable, since you really don't need the rest of `clearScreen()` in that case.
> 2 votes

---
Tags: c++, attiny, compile
---


# Question
Title: Inaccurate PWM Signal Frequency and Timing
I have a Teensy 3.2 and I am using the Arduino IDE to program it. I am trying to generate 8 pulses with the frequency of 40 kHz and this needs to be repeated every second. I have written 3 different codes and none of them is working quite the way I wanted. The duty cycle of the pulses are not always constant (i.e. the falling edge often shifts in the time axis), indicating an inaccuracy with the delay between the `analogWrite` commands. There seems to be an issue with delays not being consistent and changing within the 8 pulses and between the 8 pulses. **This inaccuracy is different between the 3 different codes, but exists in all of them.** Changing the processor speed between 16 MHz and 120 MHz does not appear to change the problem (except in code 3 where NOP is dependent on it). Is there a way to make the cycles more consistent at 40 kHz? Do I need to use an external timer or oscillator? The two images below display the two problems. The first image shows the differences in time delays and output frequency. The red dashed lines are provided to show the discrepancy in the same pulse at successive iterations of the code. The second image shows a recurring issue where the square wave is not in fact a square, and doesn't seem to be caused by software problems.

**Image 1:**

**Image 2:**

The codes I have written can be found below:

**Code 1:**

```
const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  analogWriteFrequency(pin1, 40000);
  analogWriteFrequency(pin2, 40000);
}

void loop() {
  analogWrite(pin1,128);   //for 50% duty cycle
  delayMicroseconds(188);  //It takes 187.5us to generate 8 pulses at the given frequency
  analogWrite(pin1,0);
  delay(1000);
}

```

**Code 2:**

```
const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayMicroseconds(10);
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayMicroseconds(10);
      analogWrite(pin2, 0);
  }
}

```

**Code 3:**

```
const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

// Variable N determines the length of the delay.
// Execution of NOP corresponds to 62.5ns delay
// when the processor speed is 16 MHz.
const int N = 50;
#define NOP __asm__ __volatile__ ("nop\n\t")

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayNOP();
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayNOP();
      analogWrite(pin2, 0);
  }
}

void delayNOP(){
  for(int j =0; j<=N; j++){
    NOP;
  }
}

```

# Answer
> 1 votes
it seems in the first picture that the two pulses have different duty cycles which is why it appears shifted. It looks like the 'on' part stays on for less time than the 'off' so your duty cycle is probably \<50 but your frequency might still be 40kHz.

I think the most accurate way of getting 40kHz just with a teensy is to use timer interrupts as Majenko suggested. Check out the documentation for it here, its pretty straight forward,you set the timer to go off every 12.5us and in the ISR simply toggle a digital pin and keep count of how many times you've toggled it. If your teensy needs to run other interrupts you should change the priority using myTimer.priority(number); to possibly give the 40kHz interrupt a higher priority. One thing, don't use digitalWrite in the ISR as its slow af, either try digitalWriteFast or use assembly language to toggle it as pointed by Majenko.

Alternatively you could use a 555 timer which is easy to setup and I'm pretty sure it's been used to gerate 40kHz at 50% duty cycle, although it might be a bit tricky finding the correct capacitor/resistor values if they're too small/non-standard. Then you would hook up the output of the 555 timer to whatever you're hooking it up to and also to a digital input pin on the micro. Then you would have to set an external interrupt on that pin so whenever the 555 goes high the interrupt on the pin would fire and you would keep track of how many pulses have been generated.

Alternatively, you could use a digital signal synthesizer. I used the ad9837 for one of my projects. It can generate something like 0-3Mhz with a 5Mhz external clock at a resolution of 0.02 which is pretty good. I've got an altium design for it if you don't want to buy the module and an adapted version of the adafruit miniGen library which works with teensy3.5 link. Then you'd need to do the same feedback loop as the 555 to keep track of how many pulses have been produced (or your way of waiting X microseconds). The module is actually pretty low power so you could power it from a digital pin and turn that pin on/off every second.

I think you should try the interrupt method first, as it's the easiest. Also, I get that you want 8 pulses evey one second but maybe for debugging purposes have the 40kHz pulse go constantly and change your scope to measure frequency so you can see how far off you are from 40khz.Then once you know you're actually getting 40khz have it run every 1second.

# Answer
> 0 votes
One option is to use the IntervalTimer of the Teensy:

```
// Set up the variables and objects:
IntervalTimer myTimer;
volatile int count = 0;

// ... later, start it:
count = 0;
myTimer.begin(togglePin, 12);

// ... and:
void togglePin() {
    GPIOB_PTOR = 1<<8; // Note: find the right register and bit for your chosen pin.
    count++;
    // 16  toggles is 8 pulses.
    if (count == 16) {
        myTimer.end();
    }
}

```

Note: this hasn't been tested, and you will need to do some research to get the right register and bit number, and also configure the pin for output and to your default level.

---
Tags: pwm, timers, teensy
---