# Question
Title: How can I know how far a button is pressed?
I want to make a system that can count coins. The problem that I know have is that I need a way to detect the size of the coin.

The idea that I have is a beam that becomes smaller if you a inject a coin. The size of the beam depends than on the size coin. See it as a button that you can press a little bit or very deep.

But how can I know far the button (beam) is pressed?

# Answer
> 2 votes
Following on from Mark's comment, I'm not convinced that you can measure the size of the beam, using a single optical (analogue) device - generally optical switches, like other switches, are binary, either on or off, and as such would use one of the Arduino's digital inputs.

The type of (hypothetical) button that you describe, taking a mechanical analogue (rather than your optical beam example), would require the use of an analogue input pin, and your "switch" would actually be a linear potentiometer, i.e. a slider, or lever, and the analogue input could then measure the input voltage, which would be proportional to the amount that the button (or lever) has been pressed (or moved). However, the usual linear potentiometer is not spring loaded, so the button would not really have the usual expected push button behaviour, unless, of course, you rigged up some sort of spring loaded button, with a long throw, mechanically connected to a linear potentiometer.

An analogue version of this sort of set up, as far as I am aware, does not exist for a optical solution.

What you could use is a series of optical digital (not analogue) switches (or a single light source and a series of receivers), arranged in a line (perpendicular to the base along which the coin is rolled along) in such a way that they can detect the size of the coin*. If the light is broken for a particular detector, then you know that the radius/size/width of the coin is *at least* the same as that detector's distance from the base.

These optical detectors are then connected to a series of digital inputs, i.e. `D5`, `D6`, `D7` and `D8`, and a series of `if` statements would enable your code to determine the size of the coin.

Assuming that the broken light beam results in a `low`, then the pseudo code would be something like this:

```
if D5 = low & D6 = high
 then coin is a cent
if D5 = low & D6 = low & D7 is high
 then coin is a nickle
if D5 = low & D6 = low & D7 = low & D8 = high
 then coin is a dime
if D5 = low & D6 = low & D7 = low & D8 = low
 then coin is a quarter

```

Obviously you would need a trigger when to take the "snapshot" of the coin passing the detector at the *correct time*, when it is fully blocking the lights, and not just partially blocking the light beams (which could result in a false reading).

---

* I have just realised that this is *exactly* what Jot described in his comment.

---
Tags: button
---


# Question
Title: How can I update global variable within a loop from outside the loop?
I have this code, but its not working. If I type "ReportFRQ 1" (or 0) it reports back that FrqON variable has changed but the behaviour of the loop doesnt. Basically I am trying to switch parts of the loop on and off using variables, which are updated by serial command.

The main body of the code was kindly provided by another answer as a way of commanding the arduino remotely with custom commands. I can get the arduino to do various things, but updating the behaviour of the loop by activating and deactivating different variables does not seem to work...

Any ideas? Thanks

```
#include <avr/pgmspace.h>
#include <FreqCounter.h>

#define BUF_LENGTH 128  /* Buffer for the incoming command. */

unsigned long int frq;
unsigned int frqON;

static bool do_echo = true;

/* Execute a complete command. */
static void exec(char *cmdline)
{
char *command = strsep(&cmdline, " ");

if (strcmp_P(command, PSTR("help")) == 0) {
    Serial.println(F(
        "echo <value>: set echo off (0) or on (1)\r\n"
        "freq: reports current frequency"
        ));
} else if (strcmp_P(command, PSTR("echo")) == 0) {
    do_echo = atoi(cmdline);
} else if (strcmp_P(command, PSTR("freq")) == 0) {
       FreqCounter::f_comp= 8 ;             // Set compensation to 12
       FreqCounter::start(10);            // Start counting with gatetime of 100ms
       while (FreqCounter::f_ready == 0)         // wait until counter ready
       frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
} else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);

} else {
    Serial.print(F("Error: Unknown command: "));
    Serial.println(command);
 }
 }

 void setup()
 {
Serial.begin(57600);
Serial.println("Frequency Counter");
}

void loop() {

/* Process incoming commands. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];
    static int length = 0;

    int data = Serial.read();
    if (do_echo) Serial.write(data);
    if ((data == '\b' || data == '\177') && length) {  // BS and DEL
        length--;
        if (data == '\177') Serial.write('\b');
        Serial.write(" \b");
    }
    else if (data == '\r') {
        if (do_echo) Serial.write('\n');    // output CRLF
        buffer[length] = '\0';
        if (length) exec(buffer);
        length = 0;
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;
 }

 if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

    /* Whatever else needs to be done... */
 }

```

# Answer
You have multiple problems here. First one:

You have a global variable:

```
unsigned int frqON;

```

However in your `exec` function you're creating a variable of the same name and writing to it. This doesn't change the global variable.

```
else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       //creates new local variable "frqOn" which overshadows global variable
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);
}

```

To solve this and change the global variable, simply omit the `int` decleration.

Also your `if` check is wrong:

```
if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

```

When you do `if(frqOn = 1)` you **set** the variable `frqOn` to `1`. You however want to compare the values, i.e. use the comparison operator `==`.
> 0 votes

---
Tags: arduino-ide, arduino-nano, sketch, code-review
---


# Question
Title: Arduino UNO hangs without visible reason
I'm having trouble with Arduino UNO. I bought a cheap clone (what obviously *may* be the reason) along with display+keypad shield (site in Polish). For my project I wrote a menu library, which (along with simple demo project) may be downloaded or cloned from my Bitbucket repository.

My problem is, that when I push "up" or "down" button and hold it, program behaves as it should for couple of seconds and then board freezes. This is definitely not a case of program hang, because when I used serial debugging, and when such freeze happened, message sent from board was cut in half and no new messages were comming. After such hang I can only reset the board.

I investigated my code a lot, but couldn't find a problem. My questions are:

* In what circumstances board may freeze in such way?
* If someone owns similar hardware (display, 5-button keypad) and original UNO, could you try running my program and check, if the hang happens as well?

---

**Edit:** Complete sources of the project, as requested (*now fixed*), *though the newest version is on repository*:

Arduinomenu.ino:

```
#include "Display.h"
#include "Keypad.h"
#include "Menu.h"

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
Display display(lcd, 16, 2);
Keypad keypad;

BaseMenuItem * subItems[] =
{
  new ActionMenuItem("Subaction 1", 4),
  new ActionMenuItem("Subaction 2", 5),
  new ActionMenuItem("Subaction 3", 6),
  new IntMenuItem("Int item", 0, 10, 5),
  new BoolMenuItem("Bool item", true)
};

BaseMenuItem * mainItems[] =
{
  new ActionMenuItem("Action 1", 1),
  new ActionMenuItem("Action 2", 2),
  new ActionMenuItem("Action 3", 3),
  new SubMenuItem("Submenu", subItems, sizeof(subItems) / sizeof(BaseMenuItem *))
};

MainMenu mainMenu(display, mainItems, sizeof(mainItems) / sizeof(BaseMenuItem *));

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

  mainMenu.Show();
}

void loop()
{
  int key = keypad.ReadKey();
  int result = mainMenu.Action(key);
}

```

Display.h:

```
#ifndef DISPLAY_H__
#define DISPLAY_H__

#include <LiquidCrystal.h>

struct Display
{
  LiquidCrystal & lcd;
  unsigned char cols, rows;

  Display(LiquidCrystal & lcd, unsigned char cols, unsigned char rows);
  void Print(unsigned char col, unsigned char row, char * text);
};

#endif

```

Display.cpp:

```
#include "Display.h"

Display::Display(LiquidCrystal & lcd, unsigned char cols, unsigned char rows)
  : lcd(lcd)
{
  this->cols = cols;
  this->rows = rows;
  lcd.begin(cols, rows);
}

void Display::Print(unsigned char col, unsigned char row, char * text)
{
  this->lcd.setCursor(col, row);
  this->lcd.print(text);
}

```

Keypad.h:

```
#ifndef KEYPAD_H__
#define KEYPAD_H__

#define USE_KEYPAD

#define KEY_RIGHT  0
#define KEY_UP     1
#define KEY_DOWN   2
#define KEY_LEFT   3
#define KEY_SELECT 4
#define KEY_NONE   5

#define LAST_READ_DELAY 250

#define keypadPort 0

class Keypad
{
private:
  unsigned long lastRead;
  unsigned char lastKey;
public:
  Keypad();
  unsigned char ReadKey();
};

#endif

```

Keypad.cpp:

```
#include "Keypad.h"
#include "Arduino.h"

Keypad::Keypad()
{
  this->lastRead = millis();
  this->lastKey = KEY_NONE;
}

// Button values (approximate):
// Right    0
// Up       144
// Down     329
// Left     504
// Select   741
unsigned char Keypad::ReadKey()
{
  unsigned long now = millis();
  if (this->lastKey != KEY_NONE && (now - this->lastRead < LAST_READ_DELAY) && (now > this->lastRead))
  {
    return KEY_NONE;
  }

  int key = analogRead(keypadPort);

  if (key > 1000)
    this->lastKey = KEY_NONE;
  else if (key < 50)
    this->lastKey = KEY_RIGHT;
  else if (key < 250)
    this->lastKey = KEY_UP;
  else if (key < 450)
    this->lastKey = KEY_DOWN;
  else if (key < 650)
    this->lastKey = KEY_LEFT;
  else if (key < 850)
    this->lastKey = KEY_SELECT;
  else
    this->lastKey = KEY_NONE;

  this->lastRead = now;

  return this->lastKey;
}

```

Menu.h:

```
#ifndef MENU_H__
#define MENU_H__

#include <stdio.h>
#include <stdlib.h>
#include "Display.h"
#include "Arduino.h"

#ifdef USE_KEYPAD
  #define MENU_ACTION_RIGHT KEY_RIGHT
  #define MENU_ACTION_UP KEY_UP
  #define MENU_ACTION_DOWN KEY_DOWN
  #define MENU_ACTION_LEFT KEY_LEFT
  #define MENU_ACTION_SELECT KEY_SELECT
#else
  #define MENU_ACTION_RIGHT 0
  #define MENU_ACTION_UP 1
  #define MENU_ACTION_DOWN 2
  #define MENU_ACTION_LEFT 3
  #define MENU_ACTION_SELECT 4
#endif

#define TEXT_BACK "Back"
#define TEXT_BACK_LEN 4

#ifndef SELECTION_CHAR
#define SELECTION_CHAR '>'
#endif

#define MENU_TYPE_INT 0
#define MENU_TYPE_BOOL 1
#define MENU_TYPE_SUB 2
#define MENU_TYPE_ACTION 3

#ifndef MAX_MENU_LEVELS
#define MAX_MENU_LEVELS 5
#endif

// Forward declarations -------------------------------------------------------

class MainMenu;

// BaseMenuItem ---------------------------------------------------------------

class BaseMenuItem
{
protected:
  const char * name;
  unsigned char len;

public:
  BaseMenuItem(const char * name);
  void ShowListItem(Display & display, int row, bool selected);
  const char * GetName();
  virtual int GetType() = 0;
};

// MenuItem -------------------------------------------------------------------

class MenuItem : public BaseMenuItem
{
friend class MainMenu;

private:
  void ShowEditMode(Display & display);

protected:
  void ShowEditHeader(Display & display);
  virtual void ShowEditValue(Display & display) = 0;
  virtual void HandleAction(int key) = 0;

public:
  MenuItem(const char * name);
};

// IntMenuItem ----------------------------------------------------------------

class IntMenuItem : public MenuItem
{
friend class MainMenu;

private:
  int value;
  int min;
  int max;

protected:
  void ShowEditValue(Display & display);
  void HandleAction(int key);

public:
  IntMenuItem(const char * name, int min, int max, int defaultValue);
  int GetType();
};

// BoolMenuItem ---------------------------------------------------------------

class BoolMenuItem : public MenuItem
{
friend class MainMenu;

private:
  bool value;

protected:
  void ShowEditValue(Display & display);
  void HandleAction(int key);

public:
  BoolMenuItem(const char * name, bool defaultValue);
  int GetType();
};

// SubMenuItem ----------------------------------------------------------------

class SubMenuItem : public BaseMenuItem
{
friend class MainMenu;

private:
  BaseMenuItem ** items;
  int count;

public:
  SubMenuItem(const char * name, BaseMenuItem ** items, int count);
  int GetCount();
  BaseMenuItem * GetItem(int index);
  int GetType();
};

// ActionMenuItem -------------------------------------------------------------

class ActionMenuItem : public BaseMenuItem
{
private:
  int actionId;

public:
  ActionMenuItem(const char * name, int actionId);
  int GetActionId();
  int GetType();
};

// MainMenu -------------------------------------------------------------------

class MainMenu : public SubMenuItem
{
private:
  SubMenuItem ** itemStack;
  short * positionStack;
  unsigned char stackTop;
  short selectedItem;
  short firstItem;
  Display & display;
  MenuItem * editedItem;

  void ShowBack(int row, bool isSelected);

public:
  MainMenu(Display & display, BaseMenuItem ** items, int count);
  ~MainMenu();
  int Action(int keyAction);
  void Show();
};

#endif

```

Menu.cpp:

```
#include "Menu.h"

char * NewEmptyLine(int width)
{
  char * line = new char[width + 1];

  memset(line, 32, width);
  line[width] = 0;
  return line;
}

void DeleteLine(char * line)
{
  delete line;
}

// BaseMenuItem ---------------------------------------------------------------

void BaseMenuItem::ShowListItem(Display & display, int row, bool selected)
{
  char * line = NewEmptyLine(display.cols);

  if (selected)
    line[0] = SELECTION_CHAR;

  strncpy(line + 2, this->name, min(display.cols - 2, this->len));
  display.Print(0, row, line);

  DeleteLine(line);
}

BaseMenuItem::BaseMenuItem(const char * name)
{
  this->name = name;
  this->len = strlen(this->name);
}

const char * BaseMenuItem::GetName()
{
  return this->name;
}

// MenuItem -------------------------------------------------------------------

void MenuItem::ShowEditHeader(Display & display)
{
  char * line = NewEmptyLine(display.cols);

  strncpy(line, this->name, min(display.cols, this->len));
  display.Print(0, 0, line);

  DeleteLine(line);
}

void MenuItem::ShowEditMode(Display & display)
{
  this->ShowEditHeader(display);
  this->ShowEditValue(display);
}

MenuItem::MenuItem(const char * name) : BaseMenuItem(name)
{

}

// IntMenuItem ----------------------------------------------------------------

IntMenuItem::IntMenuItem(const char * name, int min, int max, int defaultValue)
  : MenuItem(name)
{
  this->min = min;
  this->max = max;
  this->value = defaultValue < this->min ? this->min : (defaultValue > this->max ? this->max : defaultValue);
}

void IntMenuItem::ShowEditValue(Display & display)
{
  char * line = NewEmptyLine(display.cols);

  line[0] = 127;
  line[display.cols - 1] = 126;

  int i = display.cols - 3;
  int temp = abs(this->value);
  do
  {
    line[i] = temp % 10 + 48;
    temp /= 10;
    i--;
  }
  while (temp > 0);

  if (this->value < 0)
    line[i] = '-';

  display.Print(0, 1, line);

  DeleteLine(line);
}

int IntMenuItem::GetType()
{
  return MENU_TYPE_INT;
}

void IntMenuItem::HandleAction(int key)
{
  if (key == MENU_ACTION_LEFT)
  {
    if (this->value - 1 >= this->min)
      this->value--;
  }
  else if (key == MENU_ACTION_RIGHT)
  {
    if (this->value + 1 <= this->max)
      this->value++;
  }
}

// BoolMenuItem ---------------------------------------------------------------

BoolMenuItem::BoolMenuItem(const char * name, bool defaultValue)
  : MenuItem(name)
{
  value = defaultValue;
}

void BoolMenuItem::ShowEditValue(Display & display)
{
  char * line = NewEmptyLine(display.cols);

  line[0] = 127;
  line[display.cols - 1] = 126;

  if (this->value)
  {
    strncpy(line + display.cols - 4, "On", 2);
  }
  else
  {
    strncpy(line + display.cols - 5, "Off", 3);
  }

  display.Print(0, 1, line);

  DeleteLine(line);
}

int BoolMenuItem::GetType()
{
  return MENU_TYPE_BOOL;
}

void BoolMenuItem::HandleAction(int key)
{
  if (key == MENU_ACTION_LEFT || key == MENU_ACTION_RIGHT)
  {
    value = !value;
  }
}

// SubMenuItem ----------------------------------------------------------------

SubMenuItem::SubMenuItem(const char * name, BaseMenuItem ** items, int count) : BaseMenuItem(name)
{
  this->items = items;
  this->count = count;
}

int SubMenuItem::GetCount()
{
  return this->count;
}

BaseMenuItem * SubMenuItem::GetItem(int index)
{
  return this->items[index];
}

int SubMenuItem::GetType()
{
  return MENU_TYPE_SUB;
}

// ActionMenuItem -------------------------------------------------------------

ActionMenuItem::ActionMenuItem(const char * name, int actionId) : BaseMenuItem(name)
{
  this->actionId = actionId;
}

int ActionMenuItem::GetActionId()
{
  return this->actionId;
}

int ActionMenuItem::GetType()
{
  return MENU_TYPE_ACTION;
}

// MainMenu -------------------------------------------------------------------

void MainMenu::ShowBack(int row, bool isSelected)
{
  char * line = NewEmptyLine(display.cols);
  if (isSelected)
  {
    line[0] = SELECTION_CHAR;
  }
  strncpy(line + 2, TEXT_BACK, TEXT_BACK_LEN);
  display.Print(0, row, line);

  DeleteLine(line);
}

void MainMenu::Show()
{
  if (editedItem == NULL)
  {
    bool isSubMenu = stackTop > 0;

    for (int i = 0; i < display.rows; i++)
    {
      if (isSubMenu && i + firstItem == itemStack[stackTop]->GetCount())
      {
        ShowBack(i, i + firstItem == selectedItem);
      }
      else
      {
        itemStack[stackTop]->GetItem(i + firstItem)->ShowListItem(display, i, i + firstItem == selectedItem);
      }
    }
  }
  else
  {
    editedItem->ShowEditMode(display);
  }
}

MainMenu::MainMenu(Display & display, BaseMenuItem ** items, int count) :
  SubMenuItem(NULL, items, count),
  display(display)
{
  // Assuming initially 5 levels of menu max
  itemStack = new SubMenuItem * [MAX_MENU_LEVELS];
  positionStack = new short[MAX_MENU_LEVELS * 2];
  stackTop = 0;
  itemStack[stackTop] = this;
}

MainMenu::~MainMenu()
{
  delete itemStack;
  delete positionStack;
}

int MainMenu::Action(int keyAction)
{
  int lastItemId = stackTop > 0 ? itemStack[stackTop]->GetCount() : itemStack[stackTop]->GetCount() - 1;

  if (editedItem == NULL)
  {
    if (keyAction == MENU_ACTION_UP || keyAction == MENU_ACTION_DOWN)
    {
      if (keyAction == MENU_ACTION_UP)
        this->selectedItem--;
      else
        this->selectedItem++;

      if (selectedItem < 0)
        selectedItem = lastItemId;
      if (selectedItem > lastItemId)
        selectedItem = 0;

      // Adjust items in view

      while (firstItem > selectedItem)
        firstItem--;
      while (firstItem + display.rows - 1 < selectedItem)
        firstItem++;

      Show();
      return -1;
    }
    else if (keyAction == MENU_ACTION_SELECT)
    {
      if (selectedItem == lastItemId && stackTop > 0)
      {
        // Chosen Back

        stackTop--;
        selectedItem = positionStack[stackTop * 2];
        firstItem = positionStack[stackTop * 2 + 1];

        Serial.print("Restored sel/first: ");
        Serial.print(selectedItem);
        Serial.print("/");
        Serial.print(firstItem);
        Serial.print("\n");

        Show();
      }
      else
      {
        int type = itemStack[stackTop]->GetItem(selectedItem)->GetType();
        switch (type)
        {
          case MENU_TYPE_INT:
          {
            editedItem = (MenuItem *)itemStack[stackTop]->GetItem(selectedItem);
            Show();
            break;
          }
          case MENU_TYPE_BOOL:
          {
            editedItem = (MenuItem *)itemStack[stackTop]->GetItem(selectedItem);
            Show();
            break;
          }
          case MENU_TYPE_SUB:
          {
            Serial.print("Entering ");
            Serial.print(((SubMenuItem *)(itemStack[stackTop]->GetItem(selectedItem)))->GetName());
            Serial.print("\n");

            if (stackTop >= MAX_MENU_LEVELS - 1)
              return -1;

            Serial.print("Storing sel/first: ");
            Serial.print(selectedItem);
            Serial.print("/");
            Serial.print(firstItem);
            Serial.print("\n");

            positionStack[stackTop * 2] = selectedItem;
            positionStack[stackTop * 2 + 1] = firstItem;

            itemStack[stackTop + 1] = ((SubMenuItem *)(itemStack[stackTop]->GetItem(selectedItem)));
            stackTop++;
            selectedItem = 0;
            firstItem = 0;

            Show();

            break;
          }
          case MENU_TYPE_ACTION:
          {
            int actionId = ((ActionMenuItem *)(itemStack[stackTop]->GetItem(selectedItem)))->GetActionId();
            return actionId;
          }
        }
      }
    }
  }
  else
  {
    if (keyAction == MENU_ACTION_LEFT || keyAction == MENU_ACTION_RIGHT || keyAction == MENU_ACTION_UP || keyAction == MENU_ACTION_DOWN)
    {
      Serial.print("Item action\n");
      editedItem->HandleAction(keyAction);
      Show();
    }
    else if (keyAction == MENU_ACTION_SELECT)
    {
      editedItem = NULL;
      Show();
    }
  }
  return -1;
}

```

# Answer
> 10 votes
@Michel Keijzers provided overall answer.

And now probable cause:

```
char * GetEmptyLine(int width)
{
  char * line = new char[width + 1];

```

In the `Menu.cpp`. There is no single `delete` in the code at all. But so many calls of `GetEmptyLine`.

Using the Arduino String might have done less evil than this kind of memory leak.

# Answer
> 7 votes
I wouldn't assume by default that it's a hardware problem.

It seems like a software problem, and there can be many reasons that the Arduino hangs, e.g.:

* Too little stack space
* Too little heap space
* Pointer problems

The Arduino does not have safety against too little memory, that means it will overwrite memory -- causing lots of problems -- and hanging is a normal symptom.

What I suggest is:

* Check how many global / local variables you have (and their size), especially arrays and instances of objects; strings can be memory consuming
* Check that you don't have an overly deep stack trace
* To check, you can print out the available memory in several places

For debugging statements, keep in mind that the debug strings can be cut in half just when the microprocessor hangs; maybe the print statements are still in the buffer but will not be sent, so minimize the (length of the) debug statements in such cases.

# Answer
> 2 votes
Using string literals wastes precious RAM. To avoid this you can use the F macro. That way the string is stored in flash memory only. If by freeing up that extra RAM your program doesn't crash or works better you most likely have the answer.

for example:

```
Serial.print(F("RAM "));          // F() macro frees up 4 bytes of RAM
Serial.println(2048 - freeRam());

```

a freeRam function:

```
int freeRam()
{
 extern int __heap_start, *__brkval;
 int v;
 return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}

```

On a project I'm working on I noticed that my Arduino Nano with 2K RAM starts crashing when my free RAM goes below 150 bytes. That free RAM is where the stack is and needs to be accounted for.

---
Tags: arduino-uno, software
---


# Question
Title: Using PWM signal to decrease power of laser over time
I'm trying to turn a laser on and off with an external button. When I press the button, the laser should turn on. When I release the button the laser should turn off. However, I don't want the laser to turn off immediately. I want it to turn off linearly over 500 ms. I'm using PWM to alter the strength of the laser over time. However, will my laser power increase and then decrease in the extremely short time segments due to PWM fluctuation? Will it even be able to execute this reduction of power?

# Answer
I dont know your circuit but... Do you effectively want to use an RC filter to reduce PWM fluxuations so that the laser sees an analog voltage which will translate to a power (presumably)? - that will avoid the pulsing of the laser, but I did believe that the pulsing at full voltage was neccersary in most laser drivers - please post a schematic... Anyway if you want this to be less of an issue if an RC filter is not for you you could increase the PWM frequency (google is your friend) on the arduino...

To have it turn of slowly if your using analog, the RC filter could possibly have large enough capacity to slow the laser turn off. It will also effect rise time so suitable values for R and C will need to be found to suit. Otherwise you could dial down the PWM gradually before hard power off in the arduino software, by initiating a loop which gradually reduces power with time.

Somewhere to start anyway :)
> 1 votes

---
Tags: pwm
---


# Question
Title: Uno - PCA9685 Servos are too shaky before stabilizing - when using two channels
I'm trying to control a Tilt pan with an Arduino Uno. And the Sunrounder servo driver is used to do this, which comes with it's own capacitor out of the box.

The pan has two Servo motors, that help it face any direction.

I have set this up and even calibrated, so that I can input numbers between -90 degrees to +90 degrees horizontally, and 0 to 90 vertically. And it is working...

But the problem is that, when it is idle for too long, or when I connect it in the beginning, The tilt pan shakes intensely for about 20 to 30 seconds and turns every other direction before stabilizing to the correct point. As if it had a seizure!

When I disconnect one of the Servos, this problem solves. Two servos are connected to the first and second channel of the servo driver. So it seems that these two channels have an effect on each other.

Besides, there is not much weight on the tilt pane. And removing the weight does not seem to help.

init code:

```
pwm = Adafruit_PWMServoDriver();
pwm.begin();
pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
yield();

```

turning horizontally:

```
void Platform::setHorizontal(int d){
  if(d > 90)
    d = 90;
  if(d < -90)
    d = -90;
  point->setHorizontal(d);
  d = (d * 2.555) + 70.0; // calibrating.
  pwm.setPWM(0, 0, 325 + d); // 325 = (150 + 600) / 2
}

```

How can I solve this?

# Answer
Start by verifying the power supply is adequate, then go from there. If nothing else try a much bigger capacitor.
> 1 votes

---
Tags: arduino-uno, servo, pwm, adafruit
---


# Question
Title: Trigger countdown with 433MHz transmission
I would like to use an arduino to read 433 MHz transmission from multiple Soil Moisture Sensors. Since I can never be sure all transmissions reach the receiver I'd like to set a countdown from the moment the first transmission is received. If another transmission is received, the countdown starts again. After a defined amount of time (e.g. 10 Minutes) without any more signals or if all signals have been received (e.g 4 Sensors) the receiving unit should stop and come to decision based on the data it got to the point.

For transmitting and receiving I am using the `<RCSwitch.h>`library.

The loop of the receiving unit and one Sensor looks like this:

```
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
void Setup(){
Serial.begin(9600);
mySwitch.enableReceive(4);
}
void loop() {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();

if (value == 0) {
  lcd.clear();
  Serial.print("Unknown encoding");
  }
  else {
  Serial.print(mySwitch.getReceivedValue());
  Serial.print("%");
}

```

The full code includes some differentiation mechanism for all sensors but I figured that might not be relevant for my question.

Question: What's the best way to do this without a real time clock module. As far as I know I can't wait by using `delay(...)`since then I won't receive any data while the processor waiting.

# Answer
> 2 votes
You say *The full code includes some differentiation mechanism for all sensors* so I'll assume there's some function `GetSensorId()` that returns 0 to NUM\_SENSORS - 1.

So, you need to keep track of a) how many sensors have reported in and b) time since the last report. You can't just count how many sensors have reported in since there may be a chance one could report in more than once. So I would use an array:

```
// Assume you never receive 0 from sensor.
const int NO_DATA = 0;
const int NUM_SENSORS = 4;
int sensor_data[NUM_SENSORS];

void setup() {
    // Initialize array
    for (int i = 0; i < NUM_SENSORS; i++) {
        sensor_data[i] = NO_DATA;
    }
}

```

Also, a variable to keep track of time of last message:

```
uint32_t last_message_time = 0;

```

So, in `loop()`:

```
void loop() {
    // Check for data
    if (mySwitch.available()) {
        int value = mySwitch.getReceivedValue();
        if (value == 0) {
            lcd.clear();
            Serial.print("Unknown encoding");
        }
        else {
           // Determine which sensor sent the data
           int sensor_id = GetSensorId();
           Serial.print(value);
           Serial.print("%");
           // Save the data and the time of the message
           sensor_data[id] = value;
           last_message_time = millis();
       }
    }
    // See if all sensors reported
    byte sensors_reported = 0;
    for (int i = 0; i < NUM_SENSORS; i++) {
        if (NO_DATA != sensor_data[i]) {
            sensors_reported += 1;
        }
    }

    // When 0 sensors have reported in, do nothing
    if (0 != sensors_reported) {
        // Otherwise, at least one sensor
        // check the time
        uint32_t elapsed = millis() - last_message_time;

        // If have all data or time's up, do something
        if (NUM_SENSORS == sensors_reported || elapsed > SENSOR_TIMEOUT) {
            // Do something

            // Reset state
            for (int i = 0; i < NUM_SENSORS; i++) {
                sensor_data[i] = NO_DATA;
            }
        }
    }
}

```

---
Tags: arduino-leonardo, arduino-micro, time
---


# Question
Title: Arduino Uno power input - is 5 V at 1 A enough?
I have a Arduino Uno board and phone power bank

Power bank details

* Capacity - 8000 mWh
* Input - DC 5 V and 1 A
* Output - DC 5 V and 1 A

Can I give the power to Arduino Uno using this power bank, through the Arduino Uno USB?

# Answer
I dont see why not - YES you can!

I regularly use usb powerbanks to power projects for testing. so long as you dont ask for too much current (unlikely but project specific) you will be fine!
> 3 votes

# Answer
Short answer: Yes.

It depends on how you are feeding the power into the Uno and what you are trying to do with it.

My Unos use right at 0.35 amps, as measured by my USB volt/amp meter, until I begin adding things like DHT-22 temperature sensors and maybe a DS3231 RTC, then it will go up a bit. I can generally just run from USB power.

Feeding power via USB is not a long-term solution in general, since most other USB sources are current-limited to 500 mA. You could end up building a circuit that works fine on your power supply but not when running on just computer power.

Through testing using metered laboratory power supplies feeding into the barrel connector I am confident that 5V/1A is OK for light work.

And if you are POSITIVE that it is EXACTLY 5V then you can run it directly into the 5V pin and avoid the regulator, which drops the voltage some.
(Of course, without the regulator you put the board at risk.)

Note that If you are trying to run an anemometer you need 9-12V for power for it.

Also, if you want to run a 432 MHz serial radio you will likely need more than 1A to make them work since they need a couple of hundred milliwatts just for the radio. 1A might work, but USB power certainly will not - (they won't even try to work with just USB power).

In any case, it sounds like you are set up nicely to fire the thing up and start programming.

Have fun!
> 0 votes

---
Tags: arduino-uno, power, usb
---


# Question
Title: Stable temperature sensor under voltage fluctuations
I'm looking for an **inexpensive** temperature sensor which is non reliant on the input voltage to return an analog reading back or some sort of digital signal. Accuracy is not very important, for instance +/- 4 C is fine. The lm35 I have been using jumps from 25 to 70 degrees regularly with changes in circuit load.

My other option is to add a separate voltage regulator, but I am trying to avoid that if possible! Thanks!

# Answer
The **DS18B20** is a temperature sensor with a digital interface (1-Wire). It works at 3.3 to 5V and the cable length can be a number of meters. It is accurate to 0.5°C.

The DS18B20 is probably the most used temperature sensor for Arduino projects. Its price starts at less than a dollar/euro. You only need the DS18B20, a pullup resistor of 10k and a digital pin.

In the Arduino IDE, go to the Library Manager and search for 'onewire'. Install the "OneWire by Jim Studt, Tom Pollard, ... Paul Stoffregen, ...".
Then search for 'dallas' and install "DallasTemperature by Miles Burton, ...".
The OneWire library on its own can read the temperature of the DS18B20, but the DallasTemperature makes it easier to use. Look for the examples of the DallasTemperature in the Arduino IDE to start with the DS18B20.

The 1-Wire is a bus, you can add more DS18B20 sensors to the same wire. The DallasTemperature library has two options. Select either a sensor by index, or by its ID. Every DS18B20 has a unique ID inside the sensor.

Sometimes an analog temperature sensor has specific advantages, for example a ntc temperature sensor or a thermocouple sensor. For normal indoor or outdoor usage, the digital temperature sensors are far more easier to use.

Why measure only the temperature ? If you want the baromic pressure and humidity as well, the BME280 has it all. Its temperature accuracy is not very accurate, it is only ±1°C.
> 1 votes

---
Tags: arduino-uno, voltage-level, temperature-sensor
---


# Question
Title: How to select hardware for my Arduino board?
As I embark on my first Arduino project, I have lots of questions. Specifically, what considerations should I make when selecting equipment, and what are the critical parameters to safe operation?

Some elaboration upon my questions can be seen below. However, outlining general principals of equipment selection would be highly useful.

I have an Arduino Uno. The Uno has an input voltage of 6-20 V, and operating voltage of 5 V as from the tech specs. Does this mean that I can select any sensor with less than 20 V output to send data to my Arduino?

I am interested in using a sensor like this Texas Instruments HDC1080 High Accuracy Digital Humidity Sensor, which has a supply of 5.5 V. If my logic is correct, this output should be fine. I should know whether or not I need to buy some sort of shield based purely upon the output pins of the sensor, correct? I know I have 6 analog and 6 PWM/digital pins on the Arduino, so the digital signal should be capable of being processed by my Arduino. However, the interface type on the sensor product is I2C, but I am unsure as to what this means or if it needs to be a consideration.

# Answer
> 0 votes
One question you have (3rd paragraph) brings a caution to mind. Your inputs to the Arduino are typically going to be 5v based, either digital or analog, although I may be phrasing this slightly loosely. A sensor not of the type you reference would provide a digital signal (Low/High relative to ground) or analog, which would be limited via external circuitry to 5v or lower. I think there's a good chance that if you find and use a sensor that pumps 20v into your Arduino, the smoke might be released.

I've read over the sensor you've linked. It was fascinating reading. It appears that the device is focused on being connected to a PC with USB and a Windows interface, but permits direct register access for specific data.

You'd want to research the best way to connect an i2c device to your Arduino, and I'm certain there are plenty of libraries for that. A good place to start is the reference on the "official" Arduino web site for i2c. This same page references use of the library, calling/polling the device and reading/writing data.

What I read in the volumes of the data sheets and user guides for the device you linked appears to cover everything you need to know and a tremendous amount of information you may not need.

It looks like a fun project and well engineered, at least from the sensor reference.

# Answer
> 0 votes
For your first project, power the Arduino Uno with the USB cable and use everything at 5V.
There are tutorials which guide you step-by-step to make something. The Adafruit tutorials are very good.

The HDC1080 is a sensor that works at 3.3V and at 5V. That means you can use it with the 5V Arduino Uno without problem.
This Tindie HDC1080 module points to a HDC1080 library on Github. I suggest you try to make that work.

If you can not get data out of the sensor, then you should start with something very simple. A few leds (with series resistors) or a LDR light sensor is fun to start with.

As soon as you start using higher voltages (for example 12V) you might consider buying a spare Arduino Uno, because the Arduino Uno will be blown when 12V touches one of the pins.

Be also careful with sensors that can only handle 3.3V and not 5V. Since the Arduino Uno runs at 5V, a pin of the Arduino could feed 5V into the sensor and damaging the 3.3V sensor.

---
Tags: sensors, power, safety
---


# Question
Title: Powering potientiometer/button with a digital pin
When I read articles/tutorials about the Arduino Uno, the potentiometer and button always get power from the 5 V pin instead of from digital pins.

May I know whether the two components above can be powered by digital pins?

What is the situation that the components must only get power from 5 V pin instead of digital pins?

# Answer
You can likely use an I/O pin as an output to "power" fairly high-impedance devices such as pullup resistors for buttons, or even potentiometers of moderate to high total resistance.

A reason you might wish to do so would to be able to stop the device from draining power while the entire system is in a low-power sleep mode, or to otherwise disable it beyond merely ignoring its input.

However, it's worth noting that powering an analog device such as a potentiometer from an I/O pin is likely to inject noise and full scale voltage uncertainty into the signal so derived, as the output voltage under load may be neither the same as the supply rail, not "quiet".

And, of course, you must not attempt to use an I/O pin to power lower-impedance (aka more "power hungry") loads via an output pin. Generally, active devices should not be powered in this way - especially ones such as radio transmitters, other microcontrollers or complex logic functions, ultrasonic transmitters, and definitely not motors, relays, or solenoids.
> 6 votes

---
Tags: arduino-uno, power, button, potentiometer
---


title: Send and Read packet XBee AT mode

text:
# Question
Title: Send and Read packet XBee AT mode
I have a simple network created using XBee Series 2 devices.

My network is very simple, my end-device with Arduino Uno read a temperature and Lightning, display this value into LCD and send using XBee to a coordinator. It is setting for sleep and wake up using PIN hibernation.

It is setting like End-Device AT mode.

I try to send a Remote AT command with XCTU from coordinator to my end device and it parse this command and response.

What I try to do is parse received packet into my Arduino code and decide what response (for example discharge it).

It is possible to do using only one Serial? The Arduino Uno and XBee are connected with an XBee shield.

I have try using this code but the Arduino don't display the packet received from the Coordinator.

This is my code:

```
#include <avr/sleep.h>
#define XBEE_sleepPin 7
#include <LiquidCrystal.h>

//Sensor variable
int sensorPin = 0;
int fotoResistenzaPin = A1;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
String data = "";
String name = "Arduino1";

//Time Variable
unsigned long seconds = 1000L;
unsigned long minutes = seconds * 60;
unsigned long hours = minutes * 60;

void setup() {
  pinMode(fotoResistenzaPin, INPUT);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Status:");
  lcd.setCursor(0, 1);
  lcd.print("Connected");
  Serial.begin(9600);
  delay(2000);
}

void xbeesleep() {
  delay (300);
  pinMode (XBEE_sleepPin, OUTPUT);   // put XBee to sleep
  digitalWrite(XBEE_sleepPin, HIGH); // Setting this pin to LOW turns off the pull up resistor, thus saving precious current
  //delay(10 * minutes);
  delay(5 * seconds);
}

void xbeewake() {
  pinMode(XBEE_sleepPin, OUTPUT);  // Set the "wake-up pin" to output
  digitalWrite(XBEE_sleepPin, LOW); // wake-up XBee
  delay(10 * seconds); //make sure that XBee is ready, time to connect to Xbee Coordinator

}

void loop() {
 //wait message
  if (Serial.available()>0) {

    //see if it is a Xbee packet
    if (Serial.read() == 0x7E) {

      for (int i = 0; i < 15; i++) {
        byte skip = Serial.read();
        Serial.println(skip);

        //check if it is a Remote AT commnad
        if (skip == 0x17) {

            //do something when i find the Remote AT command packet
          lcd.setCursor(0, 0);
          lcd.print("Remote AT command ");
        }
      }
    }
  }

  xbeewake();
  int reading = analogRead(sensorPin);
  int val = analogRead(fotoResistenzaPin);
  float voltage = reading * 5.0;
  voltage /= 1024.0;

  float temperatureC = (voltage - 0.5) * 100 ;
  data = name + ',' + temperatureC + ',' + val;
  if (Serial) {
    Serial.println(data);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp: ");
    lcd.print(temperatureC);
    lcd.print(" C");
    lcd.setCursor(0, 1);
    lcd.print("Lightning: ");
    lcd.print(val);
  }
  else {
    lcd.setCursor(0, 0);
    lcd.print("Serial Error ");
    lcd.setCursor(0, 1);
    lcd.print("Stop Trasmission");
  }

  xbeesleep();

}

```

# Answer
I'm not sure about this, but similar to any other serial communication modules used on the Arduino, you need to setup a software serial pins which act as Tx and Rx between the Arduino and the module, XBee in this case. Look at software serial. this should solve your problem. Then you can use the "Serial" object to debug your communication between the two. I have worked with both a GSM and a Wifi module and the method was the same as I have explained above.
> 1 votes

---
Tags: arduino-uno, serial, communication, xbee
---


# Question
Title: Upload code on Arduino Leonardo using command line
I'm trying to upload a compiled .hex file on an Arduino Leonardo, using the terminal. Uploading a sample code using the Arduino IDE works well, and from the Arduino IDE I got the upload command

```
avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

```

But executing it I got the following error

```
Connecting to programmer: .avrdude: Send: . [1b]
avrdude: Send: S [53]
avrdude: Recv: . [15]

avrdude: ser_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

```

What's wrong?

# Answer
The problem with the Leonardo is it doesn't automatically reset when you open the serial port like boards such as the Uno do.

The Arduino IDE contains code to manually reset the board (by opening the serial port at 1200 baud and closing it again) which avrdude doesn't have.

Basically you need a different way to reset the board so it enters the bootloader. That may be as simple as just pressing the reset button at the right time (the LED fades in and out when it's in bootloader mode) or using some command line utility to open the serial port at 1200 baud and close it again just before running avrdude.

I don't have my Leonardo to hand right now, but you might have some luck running:

```
stty -F /dev/ttyACM0 ispeed 1200 ospeed 1200 && avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

```
> 5 votes

# Answer
After try some trial and error I have built a simple binary to upload into the Leonardo bootloader. This binary opens serial at 1200 baud then closes it, and wraps the avrdude binary to write `.hex` into flash.

In Arduino core `CDC.cpp` we can see that CDC not only waiting baudrate 1200, but CDC checking DTR value. If DTR goes high, CDC cancels to jump into the bootloader. That's why I cleared DTR value. I tried this in Ubuntu 16.04.

https://github.com/vanbwodonk/leonardoUploader

Only use this simple command:

```
leonardoUploader /dev/ttyACM0 Blink.ino.hex

```

I hope it helps other people searching for this.
> 5 votes

# Answer
For a Windows solution look here: How can I force a Leonardo to reset with avrdude?. I made simple bat file wrapper that automates avrdude invocation. It identifies Leonardo COM port with WMI, resets this COM port to 1200 baud with mode command, then identifies bootloader COM port and invokes avrdude.

Firmware is supposed to be placed to firmware.hex, but bat file can be changed to be supplied from command line.

I've put the code to GitHub repo: Simple wrapper for avrdude to allow firmware upload to Arduino Leonardo from command line.
> 1 votes

---
Tags: arduino-leonardo, uploading, avrdude, terminal
---


# Question
Title: If this the way to generate a BEEP for a second
This buzzer needs to generate an audible sound for one second. The Buzzer is inside a function that is called by a loop that continues to run. It is possible to stop the loop for this one second. PWM to a piezo disk is what I had in mind. The coding has been simplified to: Stating the PWM // #define MICROSECONDS\_PER\_TIMER0\_OVERFLOW (clockCyclesToMicroseconds(64 * 256)) // set timer\_0 divisor to 64 for PWM frequency of 976.56 Hz (The DEFAULT) // The prescaler is a 3-bit value stored in the three least significant bits of the Timer/Counter register: CS02, CS01, and CS00. TCCR0B = TCCR0B & B11111000 | B00000011; // 976.56 Hz for PIN 5 // TCCR0B = \_BV(CS00) | \_BV(CS01) //Register first 5 bits B11111000 logical 'OR' Divisor = B00000011 and stop is with: TCCR0B = 0; Is that all that I need? #include #include #include #include #include #include #include class TimingISR { public: TimingISR();

```
  char lead_char, unit_sec, tens_sec, num_min;
  int int_unit_sec, int_tens_sec, int_num_min;
  int Count_Seconds, Remainder, brightness = 4, PowerLevel;   //BRIGHT_TYPICAL = 4, BRIGHT_DARKEST = 0, BRIGHTEST = 7
  bool Colon, PointFlag;
  char data_char;
};

// these are all Clobal Variables
  int pin_Clk = 2; //  or 3 for IC2
  int pin_DIO = 3; //  or 2 for IC2
  int PIN_RELAY = 4;  // controls power on/off to 'cook'
  int PIN_Beeper = 5; // PWM beeps when finished
// Main() not included in this transmission, limit is 2 programs
// in case you recognize the above, I now have functions instead of GOTO's in the MAIN()
//*********************************************************************************
// http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/
// Arduino timer CTC interrupt example
// www.engblaze.com

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

//#define LEDPIN 2  will flash on & off once a second if a LED is used
Timer()
void setup()
{
    //pinMode(LEDPIN, OUTPUT);

    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 15624;
    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);
    // enable global interrupts:
    sei();
}

//*********************************************************************************
ISR(TIMER1_COMPA_vect)     // once a second code    Counting down,
   void){  // can only get here if lead_ char is a 'c' or a '1' i.e. 'cook' or 'def'

       If ( Colon = On ) Colon = OFF; else Colon = ON;  //blink
       // on TM1736 4 digit 7 second LED display
    {  if  ( Count_Seconds = 0 )  // Done cooking,  Beep On for one second
// https://arduino-info.wikispaces.com/Arduino-PWM-Frequency
       // set timer 0 divisor to    64 for PWM frequency of   976.56 Hz (The DEFAULT)
        TCCR0B = TCCR0B & B11111000 | B00000011;  // 976.56 Hz  for PIN 5
// https://electronics.stackexchange.com/questions/164834/stop-timer-set-new-value-and-start-again-avr-interrupt
        TCCR0B &= ~(0 << CS00);   // set the CS02, CS01, and CS00 bits in TCCR0B
        TCCR0B &= ~(0 << CS02);
        TCCR0B &= ~(0 << CS03);
        //Write 'DonE' to the TM1736
        lead_char = 'D';  num_min = 'o'; tens_sec =  'n'; unit_sec =  'E';
        Colon = OFF; brightness = 7;//  Full Brightness // for a few seconds
DisplayAll()  // Main() has a character to number converter  // DisplayAll() has an extended Segment table
    }
     {
      if  ( Count_Seconds = -1 ) //  Beep OFF
           TCCR0B &= ~(1 << CS00);   // // clear the CS02, CS01, and CS00 bits in TCCR0B
           TCCR0B &= ~(1 << CS02);
           TCCR0B &= ~(1 << CS03);
     }
       if (  Count_Seconds < -11 )  cli();          // disable global interrupts //stop the interrupt timer
return(0);
       else
          Count_Seconds = Count_Seconds - 1  // don't restart the timer
 { ( if   Count_Seconds < -10 || Count_Seconds > 0 )
          brightness = 4; counterValue = 0; resetCounter; Count_Seconds = Count_Seconds -1
 }
 }   End of Timer
// ----------------------------------------------------

```

# Answer
You have pasted this code together from a couple of samples, I even recognise some of it, but I think you really don't understand what its doing.

If I want to learn how to fly a plane I am not just going to jump in the pilots chair and push the throttles wide open. Its the same with learning to code, and if you try and run this code it will do nothing.

To answer you question, no.

Try doing something really simple and annoying and wire a buzzer up to one of the pins and load this code:

```
static const int BuzzerPin = 5;
void setup()
{
  pinMode(BuzzerPin, OUTPUT);
}
void loop ()
{
  digitalWrite (BuzzerPin, HIGH);
  delay (500);
  digitalWrite (BuzzerPin, LOW);
  delay(500);
}

```

Then once you work out how that works, move on to PWM to work out how that works and then finally try interrupts (if that's what you really want).

(Oh and yes the code is virtually blink.ino which you get with the IDE.)
> 2 votes

---
Tags: arduino-nano, interrupt, pwm, timers
---


# Question
Title: External ADC reading zero while input is zero
Using ADS1115 (or any other external ADC), how its possible to read zero instead of random floating values while no any signal at the ADC's input pin?

The ADS1115 is driven by an op-amp buffer as follows.

The op-amp's `+` input is sometimes connected to a pH sensor, sometimes left unconnected.

# Answer
The behaviour you are seeing is what happens when you have high-impedance inputs. Basically, if you don't drive them, you get random values.

Unfortunately in your case, where the sensor you are using has no output current to speak of, I don't think there's anything you can do about this electronically.

You'll have to solve the problem in some other way if you really need to be able to disconnect the sensor. A mechanical solution would be a connector which shorts when disconnected. Switched headphone connectors do this, for example - when you pull out the jack, they make a connection so that the speakers can be switched on.
> 1 votes

---
Tags: analogread, adc
---


title: Arduino Mega 2560 with SIM808 module

text:
# Question
Title: Arduino Mega 2560 with SIM808 module
I have a SIM808 module like this: https://www.banggood.com/SIM808-Module-GPS-GSM-GPRS-Quad-band-Development-Board-For-Arduino-p-1063106.html

The output header has 5 pins: GND/RX/GND/TX/VCC and I connected them as:

GND/VCC to a LiPo battery, 7.4V@1000mAh

RX-\>pin 14 (written on it TX3)

GND-\>to arduino GND

TX-\>pin 15 (written on it RX3)

and uploaded this code

```
#include <SoftwareSerial.h>

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

void setup()
{

  GSMSerial.begin(19200);
  Serial.begin(19200);
  Serial.println("START");
}

void loop()
{
  if(Serial.available())
    GSMSerial.print((char)Serial.read());
  else  if(GSMSerial.available())
    Serial.print((char)GSMSerial.read());
}

```

But I'm not getting anything on it (when sending "AT" or anything else).

Any help is appreciated.

Thank you!

# Answer
> 1 votes
Don't use `SoftwareSerial` on the `HardwareSerial` pins. Instead of this:

```
#include <SoftwareSerial.h>
SoftwareSerial GSMSerial(15,14);    // RX, TX

```

Just do this:

```
#define GSMSerial Serial3

```

---
Tags: arduino-mega, gsm
---


# Question
Title: Fading red to white to blue continuous loop on ws2812 LED strip
I'm a big noob when it comes to writing a sketch and have set myself a task for an upcoming 4th July project, which has come to a halt.

I'm trying to set a strip of 30 LEDs to fade from red to white to blue through FastLED on a Wemos D1 mini. I also wanted it to flash each colour after the 3 colours have faded and continuously loop these.

I have searched many different forums and managed to get the fade to go from red to blue, but can't for love nor money add the white in-between.

Can someone point me in the right direction?

```
#include "FastLED.h"
#define NUM_LEDS 30
#define DATA_PIN D4
#define COLOUR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {

    FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

    //start from red
    for( int colorStep=0; colorStep <= 255; colorStep++ ) {

        int r = 255;
        int g = 0;
        int b = colorStep;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }

    //into blue
    for( int colorStep=255; colorStep >= 0; colorStep-- ) {

        int r = colorStep;
        int g = 0;
        int b = 255;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }
}

```

# Answer
> -1 votes
Think of a color as a point in 3d as defined by its r g b attributes

Think of two points here, one is your starting color in that 3d space, and another your ending color.

Figure out the path you want to take from the starting color to the ending cokor.

Chop it up in a few steps and use your code to walk the path.

Done

---
Tags: rgb-led
---


# Question
Title: Triggering Sound - Arduino + Contact Mic
I previously created a sound installation using contact mics and computer (ableton+max msp) where sound would be triggered when people touched/tapped on the object/surface. Now I want to do something similar but want to get rid of the computer as it will be at a night club space where people will be walking around so I don't want to leave the computer there. What I exactly want to do is to be able to load some sounds into arduino and again use contact mic on the object and when people touch it, the sound will be triggered. I know it won't be as creative as doing it with ableton where there is live-editing possibility but I'm happy with one type of sound in this one. I can probably find some codes here and there but I'm not sure what I exactly need to use to be able to do this. I have few uno boards and lots of other bits that I've collected but haven't used before, so I would be very happy if you could help me as a novice.

Thank you

# Answer
I'm using piezzos too, for making art installations, and I used max-msp too, but I don't like it too much. It's a whole new world change from the computer to the Arduino. Because it's not only the code, you must deal with electronic components I'm quite a novice too and I don't know how much you know about music and electronic components so maybe I say things wrong or that you already know, but I will say:

* AC Adapter

I will use an AC Adapter better than batteries, because the batteries will run out in a couple of hours and in a night club almost for sure you will have access to some power extension. Arduino usually works with 9v 1A, but it'll go for 2A.

* Music Shield

And you need a music shield, you can buy a cheap one, but I recommend the Adafruit ones, because they come with a lot of more information, and more people are working with them, but they're usually more expensive. With the music shield you need a SD card. Arduino don't have enough memory so you need a music shield with a SD card to storage the sounds.

* Speakers and amps

and finally the speakers, it depends in what kind of speakers are you using, if you're using a big ones like some Yamaha MSP you will need and amplifier, but if you're using little ones like 8ohm 0.25W with the music shield will be enough

* some kind of box

you will need to put the Arduino in some kind of box, and I will secure it in the wall and not in the ground
> 1 votes

# Answer
If you're asking what kind of sensor you'll need, look for capacitive sensors or there's even this instructable that could be implemented with a conductive material (see link below).

You can definitely do this project without a computer, you just need to figure out the following things:

1) Power consumption - How much current will your Arduino, speaker, sensors, etc use? Calculate your "mAh" from this and determine what kind of battery (my recommendation) will fit your needs.

2) Housing for the arduino+circuitry. If you're doing this in a nightclub you want this to be waterproof/somewhat durable.

3) SD card shield/adapter to store the sounds you want.

I have lots of experience as a hobbyist so please do not hesitate to ask for more questions. Good luck!!

Link to instructable: https://www.instructables.com/id/DIY-Touch-Sensor/
> 0 votes

---
Tags: arduino-uno, sound
---


title: Pins are not switching

text:
# Question
Title: Pins are not switching
I am trying to make pins 13, 12, 10 and 9 to switch between high and low. That is, when pin 13 is high, pin 12 should be low, then pin 10 should be high and pin 9 should be low.

Code:

```
 unsigned char driver[4] ={13, 12, 10, 9};
 String mystring = "";
 void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   for(int i = 0; i < 4; i++){
     pinMode(driver[i], OUTPUT);
   }
 }

 void backward(){
   digitalWrite(driver[0], HIGH);
   digitalWrite(driver[1], LOW);
   digitalWrite(driver[2], HIGH);
   digitalWrite(driver[3], LOW);
 }

 void forward(){
   digitalWrite(driver[0], LOW);
   digitalWrite(driver[1], HIGH);
   digitalWrite(driver[2], LOW);
   digitalWrite(driver[3], HIGH);
 }

 void STOP(){
   digitalWrite(driver[0], LOW);
   digitalWrite(driver[1], LOW);
   digitalWrite(driver[2], LOW);
   digitalWrite(driver[3], LOW);
 }

 void loop() {
   // put your main code here, to run repeatedly:
   while(Serial.available()){
     delay(10);
     char mychar = Serial.read();
     if(mychar == '\0')
       break;
     mystring += mychar;
   }

   if(mystring == "F" || mystring == "f"){
     forward();
     mystring = "";
     Serial.println("moving forward!");
   }

   else if(mystring == "B" || mystring == "b"){
     backward();
     mystring = "";
     Serial.println("moving backward!");
   }

   else if(mystring == "S" || mystring == "s"){
     STOP();
     mystring = "";
     Serial.println("stopped!");
   }

   else
     mystring = "";
   }

```

When I test it, there is no switching, that is when moving backward, pin 13 is high throughout, pin 12 is low throughout, pin 10 is high throughout, and pin 9 is low throughout

# Answer
What line ending are you using in your IDE? Because if it is other than 'no line ending', you are also sending a new line, carriage return or both. Those control caracter get included in mystring.

Better to be safe and filter out control caracter. Try this:

```
String mystring = "";

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

void loop() {

  while (Serial.available()) {
    delay(10);
    char mychar = Serial.read();
    if (mychar == '\0')
      break;

    if (isAlpha(mychar)) {
      //  Doesn't include control caracters in mystring
      mystring += mychar;
    }
  }

  if (mystring != "") {
    Serial.print("***"); Serial.print(mystring); Serial.println("***");
    if (mystring == "F") {
      Serial.println("mystring is equal to 'F'");
    } else {
      Serial.println("mystring is not equal to 'F'");
    }
    mystring = "";
  }
}

```
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: Constructing my own serial command syntax to control arduino
I know this is a basic question, but as a hardware electronics guy and not a programmer I cannot seem to fathom how to do this - so any examples of code would be greatly appreciated:

I want the arduino to spit out some initialization chatter on startup - (ok, done easy).

Then I want it to listen for serial commands, they can all be same length if that helps but I want them to be strings. i.e. identifier followed by value

Command --- Result

PWR\_TRUE --- Power on device

PWR\_FLSE --- Power off device

REP\_FREQ --- Print frequency over serial

SP000752 --- Set power value to 752

SP016675 --- Set power value to 16675

Obviously the commands are two types, the first two being booleans and then integers, but I cant seem to find any examples not working off a single ascii character value, which is useless to me. I need more information and then from the message be able to break it down into something the arduino does.

An example of how to import whole commands and either do something, and / or chop the command up to get the value out, would be most useful.

Many thanks in advance :)

EDIT/UPDATE: I now seem to have found a solution thanks to Edgar as given in the comments. However I now have another question relating to updating the variables so as to effect the loop, as well as performing actions upon receipt of commands (which itself now works) LINK HERE

# Answer
> 2 votes
Expanding on my comment... I wrote a simple command line interpreter that you can use as a base, or an inspiration, for your own interpreter. In order to not make a link-only answer, I will put here an annotated and simplified version.

The incoming characters are handled by `loop()`. They are stored into a static buffer until a carriage return (CR = `'\r'`) is received. When the CR is received:

* the buffer is NUL-terminated in order to make it a proper C string
* it is handed to the `exec()` function for interpretation
* the variable storing the command length is reset to zero for the next command

Here is the code:

```
while (Serial.available()) {
    static char buffer[BUF_LENGTH];
    static int length = 0;  // length of line received so far
    int data = Serial.read();
    if (data == '\r') {
        buffer[length] = '\0';     // properly terminate the string
        if (length) exec(buffer);  // give to interpreter
        length = 0;                // reset for next command
    } else if (length < BUF_LENGTH - 1) {
        buffer[length++] = data;   // buffer the incoming byte
    }
}

```

The `exec()` interpreter function uses `strsep()` to split the command line into a command verb and subsequent parameters. It then compares the command verb with all supported commands in a long `if`... `else if` sequence, like this:

```
static void exec(char *cmdline)
{
    char *command = strsep(&cmdline, " ");

    if (strcmp(command, "mode") == 0) {
        int pin = atoi(strsep(&cmdline, " "));
        int mode = atoi(cmdline);
        pinMode(pin, mode);
    } else if (strcmp(command, "read") == 0) {
        int pin = atoi(cmdline);
        Serial.println(digitalRead(pin));
    } else if (strcmp(command, "write") == 0) {
        int pin = atoi(strsep(&cmdline, " "));
        int value = atoi(cmdline);
        digitalWrite(pin, value);
    } else {
        Serial.print(F("Error: Unknown command: "));
        Serial.println(command);
    }
}

```

This one supports the three commands:

* `mode <pin> <mode>`, meaning `pinMode()`
* `read <pin>`, meaning `digitalRead()`
* `write <pin> <value>`, meaning `digitalWrite()`

The full version is here: Simple Arduino command line interpreter. Compared to the version in this answer, the main differences are:

* it echoes the characters it reads, and does so in a way which is friendly to terminal emulators:
    + it echoes CR as CRLF
    + it handles BS (backspace) and echoes it as BS + space + BS
* it uses `strcmp_P()` instead of `strcmp()`, with the `PSTR()` macro, in order to keep the constant strings in Flash only
* it supports more commands, including "help".

# Answer
> 2 votes
You need to read the serial input into a string(char\[\]) or String. You then need to parse that string to read a series of acceptable characters and then convert that into an action.

***This is semi-pseudo code (not compiled, not tested, not complete)***

```
bool quit = false;
const int MaxCommand = 10;
char command[MaxCommand];
while (!quit)
{
   int index[0];
   bool wholeCommand = false;
   bool invalidCommand = false;
   while (!wholeCommand && !invalidCommand)
   {
      while (!Serial.available())
        ;
      command[index++] = Serial.read();
      invalidCommand = CheckInvalidCommand();
      wholeCommand = CheckWholeCommand();
   }
   if (invalidCommand)
   {
      Serial.print("That's an invalid command");
   }
   else if (wholeCommand)
   {
      if (strcmp(wholeCommand, "PWR_TRUE") == 0) // 0 means it matches
      {
         power(true);
      }
      else if strcmp(wholeCommand, "PWR_TRUE") == 0) // 0 means it matches
      {
         power (false);
      }
   }
}

```

However That's the hard way to do it. A much easier way is to utilities the user's CPU a bit more and get them to type data in a more computer friendly method. After all users are easier to program, particularly with a base ball bat.

Make you language fixed length:

* POWER TRUE |FALSE
* REPOR FREQ
* SETPW NUMBER

For instance use 5 letters for the command and then until the end of the line for arguments.

Probably the easiest way of manipulating strings for a newbie is to look at the String object class, but the C library string functions maybe the only way to truly get what you want (strcmp, strlen, strtok, strcpy, etc)

---

EDIT If you are struggling to code something on the Arduino then what I do is try and knock it up on Visual Studio. In this case you will need a simulated Serial object.

```
/// Code to simulate a Serial object on a Windows PC - Not Arduino code!!!
#pragma once
#include <afx.h>

class CSerial
{
public:
    CSerial () {}
    virtual ~CSerial () {}

    void begin (const int& baudRate) {}
    void flush (void) {}
    int available (void) {return 1;}
    unsigned char read (void) {return 42;}

    void print (const char* data) {_tprintf(L"%s", data);}
    void println (const char* data = NULL) {_tprintf(L"%s\n", data);}
    void print (const int& data) {_tprintf(L"%d", data);}
    void println (const int& data) {_tprintf(L"%d\n", data);}
};

static CSerial Serial = CSerial();

```

You will need to change `read()` and `available()` so that they return meaningful data. You could do this be adding a `char[]` to the class that is prepopulated with data, such as `"POWER TRUE\nREPOR FREQ\nPOWER FALSE"` and then use an `int` as an index into that.

# Answer
> 2 votes
Perhaps you should consider using https://github.com/j123b567/scpi-parser

It's an API library that allows you to build an 'instrument' that uses a recognized standard 'SCPI' as the communications protocol. It makes your device compliant with an industry standard, and can be implemented using tested code. Your example protocol is pretty SCPI-like already.

---
Tags: programming, arduino-ide, arduino-nano, atmega328, sketch
---


# Question
Title: What is actually an IC (Integrated Circuit)?
They say that you must know what IC your board has before loading a new program from the Arduino IDE and that the information is available on the top of the IC, but where is it exactly and what is an IC?

# Answer
> 4 votes
IC stands for *integrated circuit*, which is a generic term encompassing any class of devices that has multiple electronic components (transistors, and possibly capacitors, resistors, diodes, and more) encased and interconnected within. The opposite of an integrated circuit is a discrete component, which is a single electronic component in its own package that relies on wiring (or a circuit board) to connect to other components.

Taking a look at the Arduino Uno R3 below (click for larger image), the long rectangular black thing is the primary IC. You can see the ATMEL logo on it, followed by a short series of numbers (a date code if I'm not mistaken). Below is the chip model itself; in this case, "ATMEGA328P-PU". With respect to the Arduino IDE, it's sufficient to know that the chip is an ATmega328P, which is sometimes incorrectly called ATmega328 in the Arduino world.

If you look closely, there are also several other ICs on the board. To the right of the ATmega328P is a small 5-pin package; if I'm not mistaken it's an LP2985-33DBVR, which is a low-dropout voltage regulator. On smaller packages like this they often have more cryptic legends printed on them, in this case if you squint at the full-size picture you can make out "LPFL". Fortunately for most Arduino development purposes, knowing the model of these auxiliary ICs is generally not necessary. Just below that, above the crystal (the metal oblong can marked SPK16.000G) is an 8-pin package marked 09TI R5R, which I believe is a LMV358IDGKR dual op-amp.

Another IC of note on this board is the small square 32-pin package below the crystal; this is an ATmega16U2. In the case of the Arduino Uno R3, rather than being the primary microcontroller, this serves as the USB-to-serial converter.

Note that to the right of the crystal is a small three-pin package marked "340"; this is a FDN340P MOSFET. While this model of MOSFET (as with many others) contains an integrated diode across its drain and source and could thus *technically* be classified as an integrated circuit, most would still consider it a discrete component.

# Answer
> 9 votes
It's funny that you have a picture of one in your profile pic. :)

The arrow points to the most obvious integrated circuit or chip in you pic, there is another square one to the left of the TX and RX markings. There are lots of different types of ICs -- most are black and come in different shapes and sizes, different number of legs, but most have some form of writing on the back that Google can use to locate the data sheet, or general help. Have a quick look on Wikipedia for a more authoritative description.

---
Tags: arduino-uno
---


# Question
Title: mega2560- Interrupts reading digital input
Hi I am very new to Arduino, with very little programming experience.

I am using mega 2560 and trying to understand how interrupt works.

I have a code written, it is very similar as the example code Memsic2125, so i am gonna use that in here.

For my case, I am reading from my hardware, 5x5 array of sensors.

What I would like to do is to have it -- *print out x and y using interrupts* , **I want to print outputs the x and y every 10ms. Instead of printing it continuously right now.**

I will be sending it out in 16 bits. I tried some other example and read a lot of material. but still couldn't get it to work.

Any idea, suggestion, help, comment is appreciated.

```
const int xPin = 2;
const int yPin = 3;

void setup() {

  Serial.begin(9600);
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
}

void loop() {

  int pulseX, pulseY;

  int x, y;

  // read pulse from x- and y-axes:
  pulseX = pulseIn(xPin, HIGH);
  pulseY = pulseIn(yPin, HIGH);

  x= ((pulseX / 10) - 500) * 8;
  y= ((pulseY / 10) - 500) * 8;

  // print x,y
  Serial.print("x,y= ( ");

  Serial.print(x);   Serial.print(,);
  Serial.print(y);   Serial.println(")");

  delay(100);
}

```

# Answer
There isn't any interrupt code in what you posted. What exactly is the problem? One important note is that you shouldn't try to print to Serial line in the interrupt handler as serial is itself driven from interrupts which are switched off during your handler code. If all you really want to do is to print something every 10ms then you don't need any interrupt. Just use the "Blink Without Delay" style of timing and keep the other code from blocking.
> 1 votes

# Answer
The simplest would-be to read the data and loop around for your desired time.

Alternatively, time stamp the events and onkybread the data if the desired time has elapsed.

Or to use a timer interrupt for that.
> 0 votes

---
Tags: atmega2560, pulsein
---


# Question
Title: How do I choose proper diodes for a 74HC595 shift register with a wired OR connection?
I want to use a wired OR connection to connect some pins of the 74HC595 shift register to an Arduino Digital Input Pin. How do I choose proper diodes for this situation?

* Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.
* The `V_F` forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.
* Switching time has to be low enough to match the shift register's frequency.

So far, so good? What did I miss?

By the way, I haven't decided on the voltage for `VCC`, yet. Most likely, either `5 V` or `3.3 V`.

# Answer
> 2 votes
For this, almost any diode will work. Searching, it turns out that the 1N4148 is a popular ubiquitous choice. But don't go out of your way to obtain this particular diode.

> Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.

You should turn your thinking around. Consider the nominal high voltage of the 74HC595, subtract the forward bias diode voltage drop (usually 0.7V for a silicon diode) and divide that by the resistor you pick. That will be the current passing out of the 74HC595, through the diode and resistor. Only a small amount of current will pass into the Arduino. It should be negligible for most applications. You should pick a resistor high enough to only allow milliamps of current to pass through this circuit.

> The V\_F forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.

Check the voltage margin allow for a logical high input to the Arduino (Atmel processor). I think 3V - 0.7V = 2.3V is still considered a logical high. However, if you think this is too close, then switch to the 5 volt Arduino where the 0.7 volt drop will make less difference.

> Switching time has to be low enough to match the shift register's frequency.

I doubt this will be a problem. That is, I doubt the CMOS logic will surpass the speed at which the diode can turn on / off.

---
Tags: shift-register, input, components, digital-in
---


title: Oscillating Analog Readings

text:
# Question
Title: Oscillating Analog Readings
I am using a JIC 139 UV Sensor (datasheet) with an Arduino Mega 2560 and should be reading smooth curves as I bring a UV source to towards the sensor. Instead, my curves are increasing and oscillating. How can I remove the oscillations and what is the cause of these oscillations?

Code:

```
float mapfloat(long x, long in_min, long in_max, long out_min, long out_max)
{
    return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
}

int averageAnalogRead(int pinToRead)
{
    byte numberOfReadings = 8;
    unsigned int runningValue = 0;

    for(int x = 0 ; x < numberOfReadings ; x++)
        runningValue += analogRead(pinToRead);
    runningValue /= numberOfReadings;

    delay(100);

    return(runningValue);
}

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

void loop() {

   float pinRead0 = averageAnalogRead(0);
   float pVolt0 = pinRead0 / 1024.0 * 5.0;

   // In mW/m^2
   Serial.println(pVolt0);
   //  Serial.println(mapfloat(pVolt0, 0.0, 5.0, 0.0, 15.0));

   delay(100);
}

```

\`

Here is a sample screenshot from the Serial Plotter at 3 different distances from the UV Source:

Would post cicuit but don't have enough reputation. Will post as response. **edit:** I added a very large capacitor(3300 uf) between the output pin and ground which seemed to smooth the values a little bit but the noise still exists

**edit:** The x-axis is number of readings and the y-axis is voltage(0-5v) calculated from analogRead()

# Answer
Without seeing circuit and construction details and oscilloscope traces, it's difficult or impossible to say what the problem is. It may be due to op amp instability due to a large capacitive load. It may reflect a beat frequency between some sensor and MCU signals, or aliasing between 60-Hz noise and your data-conversion rate.

Regarding op amp instability, see for example the article *Op Amps Driving Capacitive Loads*, by Grayson King. Here is a quote from that article:

> Q. *How does capacitive loading affect op amp performance?*
> A. To put it simply, it can turn your amplifier into an oscillator. Here's how: \[...\]

Rather than just connecting that big 3300 μF capacitor to the output pin, perhaps instead try attaching an Active Low Pass Filter to the output, or a unity-gain op amp followed by a Passive Low Pass Filter; etc. Put big capacitors across power into the UV source and power into the sensor, instead of on the sensor output.

Regarding beat frequencies and aliasing, low-frequency oscillation like that seen in the trace may occur as a difference of two higher-frequency signals, or as a sampling artifact. To check this out, attach an oscilloscope to the UV source and see if its power consumption oscillates; and/or try a more-rational sampling scheme than that shown in your code.

For example, instead of taking 8 readings within one millisecond in `averageAnalogRead()` and then waiting 100 ms, perhaps add a `delay(1)` inside the loop so that readings are spread out slightly more. Remove the `delay(100)` from within `averageAnalogRead()`. Compensate by changing the other `delay(100)` in `loop()` to, for example, `delay(191)` or `delay(193)`. Try various delay amounts to see if they have an effect on the waveform.
> 1 votes

---
Tags: arduino-mega, sensors, analogread, op-amp
---


title: Problem with the Frequency meter code

text:
# Question
Title: Problem with the Frequency meter code
I am trying to build a frequency meter using Interrupts and Timer1, which works as if the system receives an Interrupt it would get the timer's data and would calculate

> Signal's Frequency = 1 / (Counter * Timer's Period) =\> F\_s = F\_t/TCNT

but the result is way off, and it does not even make sense. I have had altered my code to look that if the timer's data is not valid or sth, but the number that the timer counter has counted is sth that I expect.

Here is my code:

```
int f=0;
char msg[50];

void setup()
{
  Serial.begin(115200);
  noInterrupts();           // disable all interrupts
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  TCCR1A = 0;
  TCCR1B = 0;
  OCR1A = 0;
  OCR1B = 0;
  TCCR1B |= (0<<CS12)|(1<<CS11)|(0<<CS10);    // Clock 2MHZ
  TCNT1  = 0;
  TIMSK1 = 0; // disable timer overflow interrupt
  interrupts();
  attachInterrupt(1,pin_ISR,RISING);
}

void pin_ISR(){
  //digitalWrite(13,!digitalRead(13));
  f = 2000000/TCNT1;
  TCNT1=0;
}

void loop()
{
  sprintf(msg,"Humidity:%d \n",f);
  Serial.print(msg);
}

```

# Answer
As stated in my comment, your code is *kind of* fine. Id mostly works, but it looses a few microseconds on each iteration. If you are looking at multi-kHz frequencies, you probably want to avoid loosing microseconds. The solution is simple: *never* reset the counter. I changed you ISR as follows:

```
uint16_t previous_counter;

void pin_ISR(){
    uint16_t counter = TCNT1;
    f = 2000000/(counter - previous_counter);
    previous_counter = counter;
}

```

and now it gives the correct frequency... on average. There are some variations though, dues mostly to delays caused by other interrupts.

**Edit 1**: If you want to avoid the fluctuations caused by other interrupts, your best bet is probably to use the input capture feature of Timer 1.

**Edit 2**: Here is why your measurement was somewhat off. Your original ISR essentially does something like this:

```
void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    loose_some_time();
    TCNT1 = 0;
}

```

The time you loose in the ISR is the part of the signal period you are not measuring, which means you are underestimating the period by that much. In the ISR you posted, this is mostly the time taken by a 32-bit division, which is quite significant. A simple improvement would be to clear `TCNT1` right after reading it:

```
void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    TCNT1 = 0;
    loose_some_time();
}

```

and now the average period you measure is *almost* right. It is not perfect though, as the whole reading and writing of `TCNT1` takes 8 CPU cycles.

The alternative I am suggesting, where you *never* clear the timer, is the correct way of measuring a period with a timer interrupt: you don't loose a single CPU cycle. The best way is to use input capture: you get rid of the software-induced jitter.

**Note**: You should also take care of the very valid points raised in Jot's answer, about making `f` volatile and reading it with interrupts disabled.
> 2 votes

# Answer
Did you find an example that works that way ? Is it, for example, allowed that the TCNT1 is cleared in an interrupt routine? The TCCR1A is cleared, but not set to a value ?
\[**edit**\] Clearing TCCR1A is okay. Clearing TCNT1 is also okay, but can be improved as @EdgarBonet shows.

The calculation uses a long of 2MHz, but the others are 16 bits. Could you force that calculation with long ? `f = int( 2000000L / long( TCNT1));`
\[**edit**\] It is not needed to force the compiler into a 'long' calculation, it already does so.

The 'f' variable is used in an interrupt and outside that interrupt. It must be made 'volatile': `volatile int f=0;`

The 'f' is used in the loop, but the interrupt could happen when 'f' is only half read or half written. The ATmega328P is a 8-bit microcontroller and 'f' is a 16-bits variable. I suggest to disable the interrupts and make a copy.

```
noInterrupts();
int fcopy = f;
interrupts();
sprintf(msg,"Humidity:%d \n",fcopy);

```

What is the range that you want to measure ?

Do you know that there are good libraries to measure a frequency ? They are the FreqMeasure Library and the FreqCount Library.

\[ADDED\]
Try to slow down the loop with a delay. If you fill the transmit buffer of the Arduino Uno TX, then the Serial.println wait for each character if there is a place in the transmit buffer.
> 0 votes

# Answer
Your approach is basically a reciprocal counter and it can work, if you start and stop the timer in the isr. The logic is essentially this:

If timer is on stop the timer and save the timer count. Else initialize the timer and start counting.

For counting a wide range of frequencies, you may need to consider timer over flow.

Edit: any solution that reads a multi byte counter while it is running will produce the wrong results. Google atomicity to understand why.
> 0 votes

# Answer
So I have had asked this question on the Arduino forum and some one has fixed my code which gives me the accuracy that I expect. The problem was that the division was better not to be in the ISR routine but in the main loop. Here's the link to that answer because that guy should be credited as he helped me big time. https://forum.arduino.cc/index.php?topic=486573.0

Thanks to all who replied to me, I have learned many things about ISR's and their limitations.
> 0 votes

---
Tags: arduino-uno, interrupt, timers, frequency
---


# Question
Title: Using the SD library with the ESP8266 DevKit
The situation is as follows, I've connected a SPI TFT screen to the ESP8266 DevKit, set my own MISO,MOSI, CD, SCK pins and it works fine, wanted to do the same for using the SD card reader, but then I realized that the SD library is using the pre-defined pins with no visible way override this.. There must be a way, no?

I did try editing the pins\_xxx files:

```
static const uint8_t SS   = 10;
static const uint8_t MOSI = D7; //11;
static const uint8_t MISO = D5; //12;
static const uint8_t SCK  = D6; //13;

```

But it did not work, I'm not that well familiar about the build process.. So, is there a way to accomplish this? Maybe a different library?

P.S. I am using the Arduino IDE for the ESP.

# Answer
After some trial and error got both the screen and sd card reader working sharing the MISO and SCK lines. I was using a display wit the Adafruit ST7735 driver (and their library), worked fine with both hardware and software, but the SD card reader (generic, not even a part number on it) was able to work only with hardware SPI as the standard SD library does not support software SPI for some reason. The most important takeaway is this: **The SD library internally uses the predefined MOSI,MISO and SCK pins, but fot the ESP8266 dev kit they were mapped to pins labeled HMOSI, HMISO and HSCLK - D7, D6 and D5.** Now that I think about it, the H must stand for "Hardware", if only I had this epiphany sooner.
> 0 votes

---
Tags: esp8266, spi, sd
---


# Question
Title: Arduino Mega 2560 with SIM808 module - Incomplete SMS response
I have this code to read a SMS:

```
String read_SMS(int index)
{
  Serial.println("--START READ SMS POSITION" + String(index) + "--");
  delay(400);
  sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
  delay(2000);
  String tmp;
  tmp = readATcommand("AT+CMGR=1", 4000);
  Serial.println("Content: " + tmp);
  Serial.println("--END READ SMS POSITION" + String(index) + "--");
}

String readATcommand(String ATcommand, unsigned int timeout)
{
  char response[800];
  unsigned long previous;
  memset(response, '\0', 800);    // Initialice the string

  int x = 0;

  GSMSerial.println(ATcommand);
  delay(3000);
  previous = millis();
  do {
    if (GSMSerial.available() > 0) {
      response[x] = GSMSerial.read();
      x++;
    }
  } while ((millis() - previous) < timeout);   // Waits for the asnwer with time out

  return (String) response;
}

// sending AT commands to the Sim808 module
int8_t sendATcommand(String ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0, answer = 0;
  char response[200];
  unsigned long previous;

  memset(response, '\0', 200);    // Initialice the string

  delay(100);

  // Clean the input buffer
  while (GSMSerial.available() > 0 ) GSMSerial.read();

  if (ATcommand[0] != '\0') {
    // Send the AT command
    GSMSerial.println(ATcommand);
    //Serial.print(F("AT Command: "));
    //Serial.println(ATcommand);
  }

  // Waiting for the answer
  x = 0;
  previous = millis();

  do {

    // if there are data in the UART input buffer, reads it and checks for the asnwer
    if (GSMSerial.available() > 0) {

      response[x] = GSMSerial.read();
      x++;
      // check if the desired answer (OK) is in the response of the module
      if (strstr(response, expected_answer) != NULL) {
        answer = 1;
      }
    }

  } while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

  //Serial.println(F("START RESPONSE:"));
  //Serial.println(response);
  //Serial.println(F("END RESPONSE"));
  //if (answer == 0) {
  //  Serial.println("Could not get the expected answer!");
  //}
  //else {
  //  Serial.println("Found expected answer!");
  //}

  return answer;
}

```

What can be wrong in the readATcommand function as it replies with an incomplete response:

```
--START READ SMS POSITION1--
Content:
AT+CMGR=1

+CMGR: "REC READ","+407245402XX","","17/06/29,10:
--END READ SMS POSITION1--

```

But, when I run it from a terminal, the AT+CMGR=1 replies with:

```
AT+CMGR=1

+CMGR: "REC READ","+40724540234","","17/06/29,10:03:06+12"
Salut

OK

```

As you can see the message body is not there + the time of the SMS is also incomplete.

Thank you!

# Answer
Don't delay.

In the three seconds that you wait between sending the AT command and reading the response the entire response has arrived and been placed in the serial RX buffer - which has overflowed because there's more than 64 bytes in the response. So you lose data.

You should never use `delay()` when reading from serial, it's dangerous (as you see).

Instead you should be just immediately reading until you see the correct response from the command you sent - which will either be "OK" or "ERROR". Everything before that is the content of the response to your command.
> 2 votes

---
Tags: arduino-uno, arduino-mega, gsm
---


title: Synchronising LEDs

text:
# Question
Title: Synchronising LEDs
Say I have 3 LEDs. I want LED1 to blink 5 times. At its third blink, LED2 should start blinking as well, also 5 times. While LED2 is at its 3rd blink, LED3 should start blinking. How do I do this in Arduino? Here's what I have.

```
int timeStep = 200; // delay time
int myPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // array with Pins
int myPinsSize = sizeof(myPins) / sizeof(myPins[0]); // Length of my array
int counter = 0;

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  for (int i = 0; i < myPinsSize; i++) {
    pinMode(myPins[i], OUTPUT);
  }
}

// the loop function runs over and over again forever
void loop() {
  LEDsequence();
  if(counter >= 9) {
    counter = 0;
  } else {
    counter++;
  }
}

void LEDsequence() {
  if(counter < 5) {
    switchOn(0);
  }
  if(counter >= 2 && counter < 7) {
    switchOn(1);
  }
  if(counter >=4 && counter < 9) {
    switchOn(2);
  }
  delay(timeStep);
  switchAllOff();
}

void switchOn(int index) {
  digitalWrite(myPins[index], HIGH);
}

void switchOff(int index) {
 digitalWrite(myPins[index], LOW);
}

void switchAllOff() {
  for (int i = 0; i < myPinsSize; i++) {
    digitalWrite(myPins[i], LOW);
  }
}

```

# Answer
Building on Michel's answer (this is a bit long to put in a comment):

Rather than using a 2 dimensional array or an array of strings (which is also a 2d array) it would be far more efficient to use a bitmask system.

```
const uint8_t TIME_PERIODS = 20;
const uint8_t NR_LEDS = 3;
const uint8_t ledStates[] = [1,0,1,0,3,0,3,0,7,0,6,0,6,0,4,0,4,0,4,0];

```

and then the loop becomes:

```
  for (int period = 0; period < TIME_PERIODS; period++)
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, ledStates[period] & 1<<led ); // set the led on or off
    }
    delay(500); // 0.5 s
  }

```

How this works:
`1<<led` will be 0001 in binary for led=0, 0010 for led = 1, 0100 for led = 2.
So if `ledStates[period]` was 3 (0011 in binary) then `ledStates[period] & 1<<led` will be non-zero for leds 0 and 1 and zero for led 2. The way the switch function is written any non zero value turns the LED on, 0 turns it off.

Why do it this way? Mainly size. Memory is always important, this uses 1 byte per state rather than 3. It could even be expanded to up to 8 LEDs without increasing the amount of memory used.
> 1 votes

# Answer
Since you have 3 leds, make a 2 dimensional array, first index for the leds (3), second for the period in which you want to have the led on or off.

E.g.

```
const uint8_t NR_LEDS      = 3;
const uint8_t TIME_PERIODS = 20;

uint8_t period[NR_LEDS][TIME_PERIODS] = [
// Time  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17, 18, 19
        {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // Led 1
        {0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, // Led 2
        {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }}; // Led 3

```

This means over 18 time periods, each state shows which led is on and off. You can use HIGH or LOW, but that makes the lines too wide.

Now you can easily create a loop:

```
void loop()
{
  for (int period = 0; period  < TIME_PERIODS; period ++) // Time
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, states[led, period ]); // set the led on or off
    }
    delay(1000); // 1 s
  }
}

void switch(uint8_t led, uint8_t state)
{
  digitalWrite(led, state == 0 ? LOW : HIGH);
}

```

So instead of switchOn and switchOff, use the switch and set it on or off by a parameter.

Also, this way it is very easy to change the schema (you can always visually see it in code). If you want longer schemes you can change the array into strings, like:

```
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "10101010100000000000", // LED 1
        "00001010101010000000", // LED 2
        "00000000101010101010", // LED 3

```

And check the index within the correct string and check for '0' and '1' instead of 0 and 1.

Since blinking is done for all leds 'in sync' (meaning during blinking leds change at the same time), you can also define a '1' as blink and '0' as off.

Than change:

```
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "10101010100000000000", // LED 1
        "00001010101010000000", // LED 2
        "00000000101010101010", // LED 3

```

to

```
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "111110000", // LED 1
        "001111100", // LED 2
        "000011111", // LED 3

```

And change the loop in

```
void loop()
{
  for (int period = 0; period < TIME_PERIODS; period ++) // Time
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, states[led, period]); // set the led on or off
    }
    delay(500); // 0.5 s

    for (int led = 0; led < NR_LEDS; led++)
    {
       switch(led, '0');
    }
    delay(500); // 0.5 s
  }
}

```

(use a constant for 0.5 s delay) and optionally create a function for the two small for loops above)
> 0 votes

# Answer
> How do I do this in Arduino? Here's what I have.

easy:

1) write a routine that blink a pattern on a given pin;

something like this would work

```
void myblinking(uint8_t pin, uint8_t *ptrn, uint8_t steps) {
  uint8_t index;

  pinMode(pin, OUTPUT);  //set pin as output
  for (index=0; index<steps; index++) {
    digitalWrite(pin, !digitalRead(pin)); delay(ptrn[index]); //flip pin, waste sometime
  }
}

```
2. then all you need is to call that routine, like this:

myblink(LED\_PIN0, led\_ptrn0, 10); //blink led\_pin0, per led\_ptrn0, for 10 steps myblink(LED\_PIN1, led\_ptrn1, 20); //blink led\_pin1, per led\_ptrn1, for 20 steps ...
> 0 votes

---
Tags: arduino-ide
---


title: Possible ArduinoJson bug on ESP8266?

text:
# Question
Title: Possible ArduinoJson bug on ESP8266?
I'm making a small IOT project using the ESP8266 in which I make 2 API calls:

1. api.openweathermap.org for weather data
2. api.timezonedb.com

The request logic is the same for both calls, the only difference being how I parse the response string. The first response is parsed fine, while the other isn't.

1. I print the String responses to Serial, they look fine.
2. Tried both Dynamic and Static buffers to no avail.
3. Making the request only to the second API, still not being parsed.
4. If I make a test and just make the response a String, char\[\] or char\*, it parses fine.

Parsing logic \[works\]:

```
StaticJsonBuffer<1000> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);
float raw = root[String("main")][String("temp")].as<float>();

```

Parsing logic: \[does not work\]

```
StaticJsonBuffer<500> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);

String data = root[String("formatted")].as<String>();

```

The response object looks like this:

```
{
  "status": "OK",
  "message": "",
  "formatted": "2017-06-30 11:34:13"
}

```

Request logic:

```
String RequestAPI::performRequest(String url, char* host){
WiFiClient client;
if (!client.connect(host, port)) {
    lcd -> clearScreen();
    lcd -> drawText("Failed to connect to API", 0, 0, this -> randomUint16());
    delay(5000);
    return "";
}

char endOfHeaders[] = "\r\n\r\n";
client.print(
String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n"
);
// Skiping HTTP headers from the response
client.find(endOfHeaders);

unsigned long startTime = millis();
while(client.available() == 0){
    if(millis() - startTime > this -> timeout){
        lcd -> clearScreen();
        lcd -> drawText("API request failed", 0, 0, this -> randomUint16());
        delay(5000);
        return "";
    }
}

String response = "";
while(client.available()){
    response += client.readStringUntil('\r');
}
Serial.println(response);

return response;
}

```

Now I'm thinking, could the empty message be causing a bug? Or am I doing something wrong?

# Answer
> 1 votes
The issue was caused because of: https://en.wikipedia.org/wiki/Chunked\_transfer\_encoding

Was not obvious as the data printed to the serial looked completely fine. Fixed with the below code:

```
client.print(
  String("GET ") + url + " HTTP/1.0\r\n" +
  "Host: " + host + "\r\n" +
  "Connection: close\r\n\r\n"
);

```

Dunno why it worked for one API but not the other though.

---
Tags: esp8266, json
---