title: Servo Buzz / millis()

text:
# Question
Title: Servo Buzz / millis()
I am having a problem with Servo Buzz that I have ascertained is from the `millis()` function using too much time for Arduino to generate a steady pulse for the servos.

I looked at this thread but was unable to figure out a solution from the code (I'm a novice)

Stack Exchange Servo Buzz

I am including my code even though it is very large, the only time I **need** to servos to run smoothly is in `case 4` of my `switch/case`.

```
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Adafruit_MotorShield.h> //LIBRARY FOR MOTOR DRIVER SHIELD
#include "utility/Adafruit_PWMServoDriver.h"
#include <Servo.h> //LIBRARY FOR SERVOS

Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);
Adafruit_StepperMotor *myStepper = AFMS.getStepper(200, 2);
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
#define WHITE 0x7

Servo pan;
Servo tilt;//DECLARE SERVOS
int yy = 0; //STEP COUNTER
//declares ints
uint8_t i=0; //BUTTON INPUTS
int x = 1; //case statement movement
int input_stage = 0;
int time = millis(); //time from when the thing turned on

//user inputs
int total_hour = 0;
int total_minute = 0;
int slide_min = 0;
int slide_max = 0;
int pan_min = 800 ;
int pan_max = 2200;
int tilt_min = 800;
int tilt_max = 2200;

//Integers used for calculations for later
int total_steps = yy;
long total_time = 0;
long step_duration = 0;
int total_pan = 0;
int total_tilt = 0;
long pan_duration = 0;
long tilt_duration = 0;
long step_millis = 0;
long pan_millis = 0;
long tilt_millis = 0;
int step_percent = 0;

// Integers for real time program sliding action
int cur_step = 0;
int pan_pos = 0;
int tilt_pos = 0;
long run_dur = 0;
long start_time = 0;
int total_slide = 0;
long display_refresh = millis();
long display_dur = 1000;
int d = 1;
long end_time = millis();
int m = 0;

void setup(){
  lcd.begin(16, 2);
  lcd.setBacklight(WHITE);
  lcd.print("Welcome to LapsR");//initialize
  delay(2000);

  AFMS.begin();  //initialize motor shield
  pan.attach(10); //attach servos to pins
  tilt.attach(9);

  myStepper->setSpeed(30); // set speed

  lcd.setCursor(0, 0);
  lcd.print("By Doug E FresH!");
  delay(2500);
  lcd.setCursor(0, 1);
  lcd.print("Thanks to: Dave");
  delay(2000);
  lcd.setCursor(0, 1);
  lcd.print("Thanks to:  Max");
  delay(2000);
  pan.writeMicroseconds(1500); //set pan and tilt servos to centre ish
  tilt.writeMicroseconds(1500);
  delay(5000);
  pan.writeMicroseconds(1000); //Jitter Test
  tilt.writeMicroseconds(1000);
  delay(5000);
  pan.writeMicroseconds(2000); //Jitter Test
  tilt.writeMicroseconds(2000);
  delay(5000);
}

void loop(){
  uint8_t buttons = lcd.readButtons();  //read lcd buttons
  lcd.blink(); //set cursor to blink
  int limit1 = 4;  //declare limit switch
  pinMode(limit1, INPUT_PULLUP);  // sets pin mode to button

  //begin case statement
  switch(x){
  case 1:

   if(m==0){ //move slider backwards until it finds a limit switch
    if((digitalRead(limit1) == HIGH)){ // digital read reads the limit switch pin - HIGH means the switch is open
      myStepper->step(2,BACKWARD,DOUBLE);
      lcd.clear();
      lcd.print("stage 1");
      delay(10);
    }
    else{ //move to the next step
      myStepper->release(); //release motor
      m = 1; //set program to 2nd stage
    }
  }
  if(m==1){ // moving ahead jus a bit so there is some pad for innacuracy
    yy = 50; //step counter is initialized
    lcd.clear();
    lcd.print("stage 2");
    delay(1000);
    myStepper->step(50,FORWARD,SINGLE); //move forward 50 steps
    m = 2;//move to the next step
  }
  if(m==2){ //stage 3 dawg
    if((digitalRead(limit1) == HIGH)){//count steps til limit is hit
      myStepper->step(1,FORWARD,SINGLE);//move forward 1 step
      lcd.clear();
      lcd.print("stage 3");
      yy++; //step counter move up one
      delay(10);
    }
    else{  //display step percentage and total steps
      x=2;
      lcd.clear();
      lcd.print("step %");lcd.print((yy-100)/100);
      delay(5000);
      lcd.clear();
      lcd.print("total: ");lcd.print(yy-100);
      delay(5000);

      myStepper->step((yy - 50),BACKWARD,SINGLE); // reset to start position (minus 50 steps for pad)
      myStepper->release(); // release motor
      step_percent = (yy-100)/100; //make calculations
      total_steps = yy-100;
    }
  }

break;

  case 2:

    if(input_stage == 0){ //enter duration
      if(d==1){
        lcd.clear();
        lcd.print("Total Duration?");//start asking for inputs - start with total overall duration hours
        lcd.setCursor(0, 1);
        lcd.print("H: ");
        lcd.print(total_hour);
        lcd.print("  M: ");
        lcd.print(total_minute);
        lcd.setCursor(3,1);
        display_refresh = millis();
        d = 0;
      }
      if (buttons & BUTTON_UP) {  //sets hour up - slight debounce delay
        total_hour = total_hour++;
        delay(250);
        d=1;
      }
      if (buttons & BUTTON_DOWN) { //sets hour down
        total_hour = total_hour--;
        delay(250);
        d = 1;
      }
      if (buttons & BUTTON_SELECT){
        input_stage++;delay(250); //select button moves to next stage
        lcd.clear();
        d=1;
      }
    }
    if(input_stage == 1){
      uint8_t buttons = lcd.readButtons();
      if(d==1){  //when d == 1 update display
        lcd.clear();
        lcd.print("Total Duration?");//ask for minutes
        lcd.setCursor(0, 1);
        lcd.print("H: ");
        lcd.print(total_hour);
        lcd.print("  M: ");
        lcd.print(total_minute);
        lcd.setCursor(9,1);
        d=0;
      }
      if (buttons & BUTTON_UP) {
        total_minute = total_minute++;  //set minutes
        delay(100);
        d=1;
      }
      if (buttons & BUTTON_DOWN) {
        total_minute = total_minute--; //set minutes
        d=1;
        delay(100);
      }
     if (buttons & BUTTON_SELECT){
       input_stage++; // select moves to next stage
       delay(250);
       lcd.clear();
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--; //back moves to previous stage
       delay(250);
       d=1;
     }
   }
   if(input_stage == 2){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Slide%start-fin");//ask for minimum slide percentage
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(slide_min);
       lcd.print("  F: ");
       lcd.print(slide_max);
       lcd.setCursor(3,1);
       d=0;
     }
     if (buttons & BUTTON_UP && slide_min < 100) {
       slide_min = slide_min++; // select start position in percentgae
       d=1;
       delay(100);
       myStepper->step(step_percent, FORWARD, DOUBLE); //move forward one percent - allows user to preview positions
     }
     if (buttons & BUTTON_DOWN && slide_min > 1) { // do not allow motor to move below 0 percent
       slide_min = slide_min--;
       myStepper->step(step_percent, BACKWARD, DOUBLE);//move forward one percent - allows user to preview positions
       d=1;
       delay(100);
     }
     if (buttons & BUTTON_SELECT){ //moves to next stage
       input_stage++;
       delay(250);
       lcd.clear();
       slide_max = slide_min; //sets ending position to set min position
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;delay(250); // previous stage
       d=1;
     }
   }
   if(input_stage == 3){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Slide%start-fin");//ask for max slide percentage
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(slide_min);
       lcd.print("  F: ");
       lcd.print(slide_max);
       lcd.setCursor(9,1);
       d=0;
     }
     if (buttons & BUTTON_UP && slide_max < 100) {
       slide_max = slide_max++;
       d=1;delay(100);
       myStepper->step(step_percent, FORWARD, DOUBLE);  //shows set stepper position
     }
     if (buttons & BUTTON_DOWN  && slide_max > 1) {
       slide_max = slide_max--;
       myStepper->step(step_percent, BACKWARD, DOUBLE);
       d=1;
       delay(100);
     }
     if (buttons & BUTTON_SELECT){ //moves to next stage
       input_stage++;
       delay(250);
       lcd.clear();
       myStepper->step((step_percent*slide_max), BACKWARD, DOUBLE); //sets platform back to home position
       d=1;
       myStepper->release();
     }
     if (buttons & BUTTON_LEFT){
       input_stage--; //moves to previous stage
       delay(250);
       d=1;
     }
   }
   if(input_stage == 4){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Pan start-fin");//ask for min pan
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(pan_min);
       lcd.print("  F: ");
       lcd.print(pan_max);
       lcd.setCursor(3,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       pan_min = pan_min + 10;  //sets displays pan parameters
       pan.writeMicroseconds(pan_min);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_DOWN) {
       pan_min = pan_min - 10;
       d=1;
       delay(10);
       pan.writeMicroseconds(pan_min);
     }
     if (buttons & BUTTON_SELECT){
       input_stage++;
       delay(50);
       lcd.clear();
       pan_max=pan_min; //sets max to min to not cause a brownout
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;
       delay(50);
       d=1;
     }
   }
   if(input_stage == 5){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Pan start-fin");//ask for max pan
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(pan_min);
       lcd.print("  F: ");
       lcd.print(pan_max);
       lcd.setCursor(9,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       pan_max = pan_max + 10;
       d=1;
       delay(10);
       pan.writeMicroseconds(pan_max);
     }
     if (buttons & BUTTON_DOWN) {
       pan_max = pan_max - 10;
       pan.writeMicroseconds(pan_max);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_SELECT){
       input_stage++;
       delay(250);
       lcd.clear();
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;
       delay(250);
       d=1;
     }
   }
   if(input_stage == 6){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("tilt start-fin");//ask for min tilt
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(tilt_min);
       lcd.print("  F: ");
       lcd.print(tilt_max);
       lcd.setCursor(3,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       tilt_min = tilt_min + 10;
       d=1;
       delay(10);
       tilt.writeMicroseconds(tilt_min);
     }
     if (buttons & BUTTON_DOWN) {
       tilt_min = tilt_min - 10;
       tilt.writeMicroseconds(tilt_min);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_SELECT){
       input_stage++;
       delay(250);
       tilt_max=tilt_min;
       lcd.clear();
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;
       delay(250);
       d=1;
     }
   }
   if(input_stage == 7){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.print("tilt start-fin");//ask for max tilt
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(tilt_min);
       lcd.print("  F: ");
       lcd.print(tilt_max);
       lcd.setCursor(9,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       tilt_max = tilt_max + 10;
       tilt.writeMicroseconds(tilt_max);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_DOWN) {
       tilt_max = tilt_max - 10;
       delay(10);
       tilt.writeMicroseconds(tilt_max);
       d=1;
      }
      if (buttons & BUTTON_SELECT){
        input_stage++;delay(250);
      }
      if (buttons & BUTTON_LEFT){
        input_stage--;delay(250);
      }
    }
    if(input_stage == 8){   //confirm parameters
      lcd.noBlink();
      uint8_t buttons = lcd.readButtons();
      lcd.clear();
      lcd.print("SL: ");
      lcd.print(slide_min);
      lcd.print(" - ");
      lcd.print(slide_max);
      lcd.setCursor(0,1);
      lcd.print("PN: ");
      lcd.print(pan_min);
      lcd.print(" - ");
      lcd.print(pan_max);
      delay(2500);
      lcd.clear();
      lcd.print("TI: ");
      lcd.print(tilt_min);
      lcd.print(" - ");
      lcd.print(tilt_max);
      lcd.setCursor(0,1);
      lcd.print("Dur: ");
      lcd.print(total_hour);
      lcd.print(":");
      lcd.print(total_minute);
      delay(2500);
      lcd.clear();
      lcd.print("Left for back");
      lcd.setCursor(0,1);
      lcd.print("Select to go");
      delay(2500);
      if (buttons & BUTTON_SELECT){
        x = 3; //if user is happy with set parametres - continue to run move program
      }
      if (buttons & BUTTON_LEFT){
        input_stage--;delay(50); // if user made a mistake they can press left to go back
      }
    }

break;

    case 3:

    //calculate moving time durations
    total_time = total_hour*60;
    total_time = total_time + total_minute;
    total_time = total_time*60000;
    total_slide = slide_max - slide_min;
    step_duration = total_time/(total_slide*step_percent);
    total_pan = pan_max - pan_min;
    total_tilt = tilt_max - tilt_min;
    pan_duration = total_time/total_pan;
    tilt_duration = total_time/total_tilt;

    //display values for debuging
    lcd.clear();
    lcd.print("total time");
    lcd.setCursor(0,1);
    lcd.print(total_time);
    delay(5000);
    lcd.clear();
    lcd.print("total slide");
    lcd.setCursor(0,1);
    lcd.print(total_slide);
    delay(5000);
    lcd.clear();
    lcd.print("step duration");
    lcd.setCursor(0,1);
    lcd.print(step_duration);
    delay(5000);
    lcd.clear();
    lcd.print("total pan");
    lcd.setCursor(0,1);
    lcd.print(total_pan);
    delay(5000);
    lcd.clear();
    lcd.print("total tilt");
    lcd.setCursor(0,1);
    lcd.print(total_tilt);
    delay(5000);
    lcd.clear();
    lcd.print("pan duration");
    lcd.setCursor(0,1);
    lcd.print(pan_duration);
    delay(5000);
    lcd.clear();
    lcd.print("tilt duration");
    lcd.setCursor(0,1);
    lcd.print(tilt_duration);
    delay(5000);
    step_millis = millis();
    pan_millis = millis();
    tilt_millis = millis();
    pan_pos = pan_min;
    pan.write(pan_pos);
    tilt_pos = tilt_min;
    tilt.write(tilt_min);

    //sets pedestal to user input slide min position
    myStepper->step((step_percent*slide_min), FORWARD, DOUBLE);
    x = 4;
    start_time = millis();
    end_time = millis() + total_time;

break;

    case 4:
    long remaining = end_time - millis(); //make a couple of run time calculations
    run_dur = millis() - start_time;

    if(millis() - step_millis > step_duration){ //take one step after step duration
      myStepper->step(1, FORWARD, SINGLE);
      cur_step++;
      step_millis = millis();  //resets step duration
      myStepper->release();
    }
    if(millis() - pan_millis > pan_duration){ //same as slide
      pan_pos++;
      pan.writeMicroseconds(pan_pos);
      pan_millis = millis();
    }
    if(millis() - tilt_millis > tilt_duration){//same as slide
      tilt_pos++;
      tilt.writeMicroseconds(tilt_pos);
      tilt_millis = millis();
    }
   if(run_dur > total_time){   //resets to top of user input once total duration runs out
     x = 0;
     input_stage = 0;
     myStepper->step(cur_step, BACKWARD, DOUBLE); //sets motor back to home position
     myStepper->release(); //release motor
    }
  }
}

```

# Answer
> 1 votes
You're calling `millis()` a lot in `case 4`. A very simple improvement would be to call it once at the start of `loop()`, storing the result in a variable. Throughout the rest of the function, simply use the value stored in that variable instead of calling `millis()` directly.

I doubt it will solve the problem entirely, but hopefully it will improve it a little.

---
Tags: servo
---


# Question
Title: How to control 19 RGB LED strips with one arduino?
I need to light up 19 RGB LED strips, which it seems would require 19\*3=57 PWM outs and 57 transistors. The transistors aren't an issue, but of course the 57 PWM's is. Even if I hacked the digital IO ports to work as PWM, I still wouldn't have enough.

How can I do this more simply? Is there some kind of device I can get that would let me just pass data to it, perhaps over I2C, and it would control many PWMs? Is there another solution I haven't considered? Maybe whatever is used to control those 8x8 RGB LED dot matrixes?

Any help would be greatly appreciated. Thank you!

# Answer
> 4 votes
You can use addressable LEDs that allow chaining from one LED to another using a serial protocol.

Like this :

This would alow you to set the first row blue, the second purple, each one can be controled independently.

Take a look at Ada Fruit's neopixels to start. These are basically skillfully branded WS2811 & WS2812 LEDs, but they are very well documented and well built. They feature 8 bit per channel RGB color (24 bit color) and take care of PWM internally. You could even chain the end of one strip to another, allowing all control to come from two pins of an arduino.

Assuming you go this route, consider the following:

1. You will need enough RAM to store the full array of pixels in memory, which is 3 bytes per pixel. Alternatively, you can create a custom library with reduced bit depth, or one that stores pixels in clusters, because at the end of the day you are just operating a giant shift register.
2. You will need to supply enough **current** (60mA per led), and supply it at several points along longer strips. You will likely need to use external power sources. You can drive a decent amount of LEDs from Vin (before the power regulator), but not anything near 19 strips.

Now if you already have the strips, and they are analog strips, I think you can find similar drivers that output more power to drive strips, but still use a serial protocol.

You can use my example code here:

```
// NeoPixel Demo minimum
// By leo etchaas
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      55

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 500; // delay for half a second

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
// End of trinket special code

pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

// For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.

for(int i=0;i<NUMPIXELS;i++){

// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(25,255,255)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval); // Delay for a period of time (in milliseconds).

}for(int i;i>0;i-=1){

// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(255,5,255)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval); // Delay for a period of time (in milliseconds).

}
}

```

# Answer
> 1 votes
There are several ways you can do this:

Option 1 - the easy way: You can use a serial-in-parallel out. Google "Arduino SIPO", and you will find examples. You basically send out 8 bits at a time, to a SIPO chip, then "enable" the chip; this changes the 8 "output" pins of the sipo to combinations of high/low as per the 8 bits that went in. You can pwm the "enable" pin. The best part is that each SIPO chip has an overflow - if you put a ninth bit in, you will get the first bit out of the overflow pin, which you can hook up to the input pin of a second SIPO, and so forth.

This option uses about arduino 4 pins, for an unlimited number of output pins.

This also has the advantage that SIPO chips can normally carry much more power than an arduino. Check the spec sheet on the SIPO to see how many milliamps it can carry at once (maximum). An example of a SIP is 74HC595.

Option 2 - Control the common pin for each strip. Basically, you will be using e.g. 3 pins to select the colour, 19 to select which strip - I think some arduinos have that many pins? To light up red on strip 3, you would put the red pin high (and green & blue low); then you would put the pin for strip 3 low, and all the others high. You would step through each pin you want to light, or you could light them in groups - first red goes high (green/blue low), and all the strips you DONT want red on have their cathode high, and those you DO want red on would have their cathode low. drop red down; then do the same for green and blue. This does mean that you can't light up leds more than 1/3 of the time. This can be combined with the SIPO chip above - it may be easier. This does mean that you need to break out the "common" (cathode, normally to ground).

None of these allow very fine-grained control like pwm - you can't just say "led 3, green, 40%"; you will have to do a lot more work. You may burn all your Arduino time just doing the LEDs; this may or may not be a problem. You have the option of offloading your work onto another AtMega chip, or even an AtTiny; I think I would use an AtTiny and three SIPOs - 4 pins of the AtTiny to control the SIPOs, and 4 for SPI to receive the new settings (e.g. send the AtTiny 57 half-bytes, would give you 12-bit colour depth). You would need to do your own "fake pwm", but you could devote the entire AtTiny to running the light show. The AtTiny is programmed the same way as an Arduino; you would use a USBISP to send the program. Just hook up the power and away you go! An AtTiny will set you back around $2, depending on how many you get and where you get them from.

ADDITIONAL!

What about using something like a TLC5940? I haven't looked at the specs, but I found a reference to Arduino code. 16 Channel, 12 bit duty cycle per channel; you would need 4 of them. Apparently they can be daisy-chained as well. http://playground.arduino.cc/Learning/TLC5940

---
Tags: arduino-uno, led, pins, pwm
---


title: modbus slave ID setting

text:
# Question
Title: modbus slave ID setting
I have small problem in setting device ID for Mosbus slave arduino. Here is simple example

In Modus library; device ID being configure hardcode while program. This code works for Me.

```
Modbus slave(1,0,0);

```

Now I wanted to recognise 0-255 device ID , I am using 8:1 digital Multiplexer & DIP switch to select the port. I am reading status of digital pin & depend on status of 8 DIP pin i come to know whats device ID. Below function return device ID. I have checked Serial it returns value properly. If i assign the value to Device ID it wont work . Please let me know how can i solve this.

```
unsigned int ID_Check() {
      unsigned   int ID_value;
      for(int row=0;row<8;row++)
      {
        digitalWrite(SO_enable,array[row][0]);
        digitalWrite(S1_enable,array[row][1]);
        digitalWrite(S2_enable,array[row][2]);
        Status_Out[row]=digitalRead(Output_Read);

      }

  ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
  return(ID_value);
}

```

Below is complete code.I tried to call function loop But it wont work

```
#include <ModbusRtu.h>
int SO_enable=5;
int S1_enable=4;
int S2_enable=3;
int Status_Out[8];
int Output_Read=2;
Modbus slave(ID_Check(),0,0); // this is slave @1 and RS-232 or USB-FTDI
int array[8][3]={
  {
    0,0,0    }
  ,
  {
    0,0,1    }
  ,
  {
    0,1,0    }
  ,
  {
    0,1,1    }
  ,
  {
    1,0,0    }
  ,
  {
    1,0,1    }
  ,
  {
    1,1,0    }
  ,
  {
    1,1,1    }

};

unsigned int ID_Check() {
  unsigned   int ID_value;
  for(int row=0;row<8;row++)
  {
    digitalWrite(SO_enable,array[row][0]);
    digitalWrite(S1_enable,array[row][1]);
    digitalWrite(S2_enable,array[row][2]);
    Status_Out[row]=digitalRead(Output_Read);

  }

  ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
  return(ID_value);
}

uint16_t au16data[16] =
{
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1
};

void setup() {
  slave.begin( 9600 ); // baud-rate at 19200
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Output_Read,INPUT);
}

void loop() {
  slave.poll( au16data, 16 );
}

```

The other way i tried

```
void Modbus_Setup()
{
  Device_ID=ID_Check();
     delay(100);
    Modbus slave(Device_ID, 0, 0);
     slave.begin(9600);
  //slave.setID(Device_ID);

}

```

# Answer
> 1 votes
It looks like the problem may be initialisation order. In C/C++, global variables/objects are usually initialised in the order they are declared, and before any global functions run.

In your case, this means `ID_Check()` gets called before `array` is populated, and before `setup()` runs.

It looks like you need to make sure everything else is setup before your attempting to initialise the `Modbus` object. I'm not familiar with the library, but perhaps there's a way to set the device ID after it's been constructed (i.e. not in the constructor)?

If not, you could declare `slave` as a global pointer, and then instantiate it using `new` in `setup()`.

As a side note, I'm guessing your `Modbus_Setup()` function didn't work because the `slave` object in there is completely separate from the `slave` object that's declared globally and used in `loop()`.

---
Tags: arduino-uno, programming, c++, library, modbus
---


# Question
Title: Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?
Will the 3.3V regulator produce 3.3v when the Arduino is powered from the USB port?

# Answer
> Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?

Yes, provided that

* it is an "official" Leonardo or a competent clone and
* as long as you do not load the power supply excessively with external loads.

**Official circuit diagram here**

The USB supply feeds the 3V3 regulator via MOSFET T1 at the bottom of the sheet and U3, an LP2985 LDO regulator. If your board has the same circuitry as this it should provide 3V3 from USB.

---
> 2 votes

# Answer
The 3.3V regulator is fed by the 5V, whatever that comes from. If you don't use a separate power supply like a wall-wart, the 5V switches automatically to the USB's 5V. That feeds the regulator for the 3.3V.
So yes, it will produce 3.3V.
> 0 votes

---
Tags: power
---


# Question
Title: How to prevent the Serial Monitor from closing upon re-uploading sketch?
I'll be teaching a year 10 class on the Intel Galileo gen2 and there'll be a wide (but high-level) programming curriculum, which includes introduction to console printing, using `Serial`.

I'd like the students to be able to write their printing code in `setup()` so that it's only printed once and easily readable by them. However, it's impossible to be fast enough to upload a sketch and open the Serial Monitor (which flat out refuses to open before the sketch has started), and the Serial Monitor closes itself upon re-uploading code.

Without unnecessary (and potentially for the students, confusing) use of the `delay` function in `setup()`, it's impossible to read any output originating from `setup()`; only things printed in `loop()` (which are constantly re-printed) are ever discoverable.

So; is there a way to somehow keep the Serial Monitor open, or make it capture output from before it's opened, or delay the entire running of the sketch (rather than chucking in delays)?

We'll be using the standard Arduino IDE.

**EDIT**

This script was run in one of two conditions...

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

  // ensure Serial is ready
  delay(1000);

  for (int i=0; i < 10000; i++) {
    Serial.println(i);
  }
}

void loop() {
}

```

When the Serial Monitor was opened **immediately** after upload, all numbers from and including 0 to 9999 were recorded in the monitor.

When the Serial Monitor was opened around 5s **after** upload, only numbers upward of 2243 were observed. This suggests the sketch WAS being re-run (else no numbers would have been captured; the sketch runs in significantly less time than 5s) but that all numbers between 0 and 2243 were not captured by the monitor; as if opening the Serial Monitor late enough to cause a re-run causes some monitor overhead.
This strange loss of numbers is NOT time dependent: increasing the initial delay from 1s to 4s (and waiting longer after upload before opening the Serial) did not at all vary the soonest number recorded, suggesting it is some 'line' based overhead (but of course, how could anything fail for 2243 lines?!)

With that mystery aside, this negates the automatic re-running of the sketch upon Serial Monitor opening from being actually useful.

# Answer
Have you tried hitting the reset button while the serial monitor is open? I have done this on other Arduino boards to capture stuff in the setup loop that was occurring too fast. Otherwise using Serial1 for output connected via a FTDI cable may be the way to go.
> 1 votes

# Answer
I assume you are uploading the code over USB - the same USB that you want to monitor for output from the sketch? If so, the serial monitor has to release the port for the uploader to be able to use it, and vice-versa, as your computer's OS will only assign a USB port to one application at a time.

It may seem like the IDE is one application containing an uploader and a serial monitor, but the IDE is not much more than a "pretty face" that runs separate compiler and uploader applications on your behalf.

Several work-arounds are possible (although I think a `delay()` statement in `setup()` is the clearest of the choices):

* Add a delay statement in the setup function. If you must this, you can put it in `main()` just before the `setup()` call, but you'd take away a learning opportunity.
* Use a separate hardware or software serial channel for the monitor which you could leave connected and wouldn't interfere with uploading;
* Use the `loop()` function instead, and put a forever loop at the bottom to prevent it returning, thus making it a runs-once function.
> 2 votes

---
Tags: serial, arduino-ide
---


# Question
Title: Arduino Ethernet and Uno R3 as a firewall
Is there a way to program the Ethernet Shield and Uno R3 to act as a firewall without using a huge chunk of the allowed bytes on the R3? I plan on using a DC adapter to plug the R3 into a wall, and use the mini-SD card to keep logs while having the ethernet shield plugged into my router.

I know that it is possible to program it to do this but I want to know if there is a simple modification I can make to the web-client library or if I should use the web-server library and modify that?

# Answer
> 0 votes
As an entry level board, I wouldn't suggest trying this on the R3. You can do it to an extent on the Yun which comes with both a network port and wifi.

Now that said, your internet speed will be severely hampered by the lack of resources on the yun. In which case, you might want to steer closer to the Intel Edison, which you can use with the arduino IDE. It is considerably more powerful.

---
Tags: arduino-uno, ethernet, sketch, web-server
---


# Question
Title: Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee
I want to create a growhouse sensor system. I have an Arduino UNO, wireless SD shield and I have just ordered a series 2 XBee XB24.

Any info I find seems to revolve around having 2 Arduinos and 2 XBee modules, why is that?

I am presuming that once I connect the XBee to the shield that I can then connect to my Arduino on the network and send and receive data, am I wrong?

I'm a developer and sysadmin but a noob to Arduino so any help is much appreciated.

# Answer
> 1 votes
The xbee network and the wifi network are both wireless networks, but, they do not communicate with each other.

You have two options.

1. Attach a second XBEE to your computer using one of these https://www.sparkfun.com/products/11812
2. Get a WIFI shield http://arduino.cc/en/Main/ArduinoWiFiShield

# Answer
> 1 votes
Do you remember the term mesh network? Xbee's create a mesh network or multipoint network using 802.15.4 (hurray for google) protocol. This is not compatible with 802.11, the wifi protocol.

If you want everything to talk, you are either going to need to get an Xbee for everything, or wi-fi for everything (or wi-fi + ethernet for that matter).

---
Tags: arduino-uno, xbee, sd-card
---


# Question
Title: How can I increase resolution for current sensor?
I purchased a ACS711 Hall effect-based linear current sensor (http://www.pololu.com/product/2197) and when i read the input it's basically always the same. After doing some research I think it's because there is only a 10bit AD converter and since the current is only changing a little bit it's not enough to catch the change. For my situation I'm pulling around 40-90ma idle and when the motor turns on it jumps up so I want this sensor to see that but it only jumps up to about 120ma. Any tips on how to fix this? Maybe a different sensor? Can I use an amplifier to boost the analog signal?

# Answer
> 2 votes
In default configuration, the Arduino's ADC has a range of 0v-Vcc (5v or 3.3v depending on the model). If you are sure your input voltages will always be way lower than Vcc, spreading the ADC's resolution over that range is a waste of accuracy. What you need to do is to **properly configure your analog reference voltage**.

Basically, this is a way of telling your Arduino "instead of spreading your ADC's bits over a range of 0v to Vcc, just cram all that accuracy between 0v and `[refVoltage]`."

So:

* Measure the highest analog output your sensor will give.
* Setup a voltage divider to output a little more than that
* Connect the voltage divider's output to the AREF pin
* in `setup()`, declare `analogReference(EXTERNAL);`

And that's basically it. As noted, in this specific case you'd probably be better off buying another sensor altogether. However, you won't always have that luxury, and knowing how to set the analog voltage reference always comes in handy.

# Answer
> 0 votes
First, let's look at where you are now. The sensor you have reports current changes at 110mV per amp.

That means 40mA =\> 4.4mv, 90mA =\> 9.9mv, and 120mA =\> 13.2mv -- all very small voltages and small changes in voltage.

Let's work backward, tho. A 5V Arduino in typical ADC mode has a resolution of about 5 mV (5 V / 1024 counts), whilea 3.3V Arduino would have a resolution of about 3.3 mv). Divide those step sizes by 0.11V/A sensitivity and you'll see that a different of 1 count on the ADC will represent about 45ma (5V Vcc) or 30 ma (3.3V Vcc). But there is always inaccuracy and noise, so it's going to be hard to reliably distinguish between 90mA and 120 mA (using your figures).

You can improve that somewhat by switching to a sensor with higher sensitivity (and lower maximum range) like https://www.pololu.com/product/1185 which improves the sensitivity to 185 mV per amp. The step size of the ADC converters would translate to about 26 mA (@5V) or 17.5 mA (@3.3V). That's still pretty tight.

You **might** be able to manage with the more sensitive sensor and a 3.3V Arduino - if you use capacitors to filter out the electrical noise on the sensor to ADC input, and you average multiple readings in your code to further smooth the values. But it would be marginal.

So you need to amplify the sensor. Yes, you could do that with an external amplifier, like an op Amp. A transistor is more difficult because you need it to stay fairly linear which gets trickier, and you may need more than one stage - so an op amp is easier.

There's another tricky factor - you need to compare the voltage from the sensor to some reference - Vcc/2 for your sensor, and 2.5V for the more sensitive one. The current is proportional to the difference between the sensor reading and that reference (the current going one way for sensor output above reference, the other way for sensor output below reference).

I'll mention another option - you could use an Arduino Mega or Leonardo. These chips offer the option of differential inputs (one pin goes to the signal, and one to the reference), and they have built in selectable amplifiers with up to 200x amplification. That should give you plenty of resolution, without needing to use external active analog circuitry.

You will still need to filter the sensor output to smooth spikes from the motor (current spikes translated to voltage spikes by the sensor). You may need to also filter the Arduino Aref input with a cap.

Suppose you were to use an Arduino Mega or Leonard with the sensor you have. You'd want a Vcc/2 reference, which could simply be two identical resistors (say 10K ohm) between Vcc and Ground as a voltage divider (and maybe a cap to ground for filtering). You would still probably need to calibrate by finding the ADC value for no current as your reference and subtract that from the reading you get when current is flowing.

---
Tags: sensors, current
---


# Question
Title: project not working when switching to battery power
I have a project which involves a photocell, an led, a push button, and a small hobby servo (tower pro sg5010) - the project works as expected when the arduino is powered by usb, but when I switch to battery power (4 AA batteries) - it doesn't work.

When powered by batteries, the servo actually starts right up and moves to the correct angle, so I feel like it should be getting enough power, but when I push the push button, it doesn't move to the new angle. I can hear a clicking noise of the servo on a regular interval, like a clock, and my LED flickers on and off at about the same interval.

If I'm doing something wrong, can anyone point it out? If it's just that the servo is not getting enough power, is there a way to add a transistor or something so that I don't have to add a separate power supply for the servo (I'm not sure there's room in my project's enclosure).

I've attached a fritzing diagram as well as my project code.

CODE:

```
#include <Servo.h>

const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonPushed = false;

const int ledPin =  13;      // the number of the LED pin

const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;

boolean servoActivated = false;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;

void setup() {
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

  servo.attach(servoPin);
  servo.write(servoStartAngle);

}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  int photoCellVal = analogRead(photoCellPin);

  if (photoCellVal > photoCellThreshold){
   photoCellActivated = true;
  } else {
   photoCellActivated = false;
  }

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW && buttonPushed == false) {
    // turn LED on:
    buttonPushed = true;
    Serial.println("button pushed");
  } else if (buttonState == LOW && buttonPushed == true){
   buttonPushed = false;
   Serial.println('deactivate');
  }

  if (buttonPushed == true){
   digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }

  if (buttonPushed && servoActivated == false && photoCellActivated == true){
    servoActivated = true;
    Serial.println("activate motor");

    for(angle = servoStartAngle; angle > servoEndAngle; angle--){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
  } else if (buttonPushed == false && servoActivated == true){ //deactivate
    for(angle = servoEndAngle; angle < servoStartAngle; angle++){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
    delay(200);
    servoActivated = false;

  }

  delay(200);
}

```

# Answer
> 3 votes
You may find that, with a high load on batteries, it's depleting the battery quickly; batteries often recover after a while, which may be confusing things further. Try using a multimeter to measure the voltage on the battery, when your program is running.

The Arduino (actually, the chip that runs the Arduino) has brown-out detection - if the voltage drops below a certain level, the Arduino will shut down; if the power comes back up, the Arduino will start up again - but reset. The chip has settings for 1.8v, 2.7v, and 4.3v brownout detection (or none at all!); something I read on the interweb (if you can trust that) said the default was 4.3v. It may be worth flashing an led on startup, so you can tell when the chip is reset.

Also, if you are powering the Arduino through the voltage regulator (using the power socket on the Arduino), then you need about 6-7 volt in just to get 5 volt at the Arduino - this causes further power loss. If using 4 AA batteries through the voltage regulator, you will get 6 volts (probably a little more when the batteries are fresh) going into the regulator - barely or not quite enough! - and the voltage on the Arduino is likely to be below the 5v it needs. Any load (in one of my projects, two large 7-segment displays) can cause the voltage to drop enough to trigger a reset. If you are using the voltage regulator, check the voltage between the 5V and GND pins.

# Answer
> 2 votes
I had an even simpler project only involving a TMP sensor and 433 MHz RF module. On a 9V (150 mAh) block battery it lasted only about 2,5 hours. The Arduino is great for prototyping this sort of stuff, but when you want to build something for battery operation I found that it draws 56 mA just looping without RF or motor!

Counting 2 digital outputs, 1 digital input and 1 analog input in your project, you can run that of an ATTiny85 or ATTiny45. It's the same family and after setup can be programmed with the Arduino environment. You can also opt for a lower speed bootloader 1 MHz or 8 MHz instead of 16 MHz for the Arduino to save energy, you don't seem to calculate that much. The ATTiny will draw about 10 mA looping this way.

Next you'll find also that you can disable the brown out detection in the bootloader, so it just drains the battery until completion.

Saving space in you enclosure by swapping Arduino board for ATTiny chip will allow you to put in more batteries, say 8 AA in two parallel packs of 6V each.

When that doesn't help you'll discover about the sleep modes and disabling ADC when not in use, where you go to sleep for specific intervals and allow the chip to be woken up by interrupts. In sleep mode I found the ATTiny to consume only 0.03 mA.

**Some more information**

Program an ATtiny with Arduino

ATTiny files for Arduino IDE

---
Tags: arduino-uno, led, power, servo, battery
---


# Question
Title: What are (or how do I use) the power saving options of the Arduino to extend battery life?
For solar & battery powered projects, decreasing power consumption is a necessity.

I know a little bit about using a timer and interrupt to put the microcontroller into sleep when it isn't doing anything.

I have also read that you can disable some peripherals to further save power.

Here is a page explaining these: Power Saving Techniques

My question:

* What other techniques are there to save power?
* Are there any libraries that make using these AVR features easier?

# Answer
*Note: I wanted to point out that, even though my answer was accepted, the reader (you) should really read Anindo's answer first if you really want to save energy with any Arduino board. Once you address those items in your design, then you should read my answer and worry about how to set the MCU into low power mode.*

Having said that, there are several techniques to make an Arduino save power. I'll list a few and then point you to a page that explains them all in more detail.

1. While the controller isn't doing anything important (between one read of a sensor and the next, for example), you can put the controller into one of the sleep modes below, with the command `set_sleep_mode (SLEEP_MODE_PWR_DOWN)`. Next to each mode is the approximate power consumption of each mode.

* SLEEP\_MODE\_IDLE: 15 mA
    * SLEEP\_MODE\_ADC: 6.5 mA
    * SLEEP\_MODE\_PWR\_SAVE: 1.62 mA
    * SLEEP\_MODE\_EXT\_STANDBY: 1.62 mA
    * SLEEP\_MODE\_STANDBY : 0.84 mA
    * SLEEP\_MODE\_PWR\_DOWN : 0.36 mA
2. Disable **brown-out detection** (the circuitry that turns off the controller when low voltage is detected).
3. Turn off ADC (analog to digita conversion)
4. Use the internal clock

Then, when you put the controller to sleep, you need to use one or more mechanisms below to wake up the controller and do something with it:

* Wake up with a signal
* Wake up with a timer

This is a summary I made from -

That article applies mostly to ATmega328P, but the technique applies to other Arduino compatible controllers as well. As TheDoctor said well, you will need to check the datashet to make sure your controller suports any of those techniques and how to do it more precisely.
> 35 votes

# Answer
Realistically, the biggest power waster on an Arduino board is the linear voltage regulator on it.

1. As long as the microcontroller on the board, the LEDs, or any other peripherals, draw current, the linear regulator wastes power equal to `difference between supply and board voltage` x `current drawn`.

So, a first fix would be to disconnect the power indicator LED on the board, and not use any of the other LEDs as far as possible. Second, supply the board with as low a voltage as possible that is just sufficient to power the on-board regulator.
2. On the original designs, the voltage regulators used do not boast low quiescent current. This means even with nothing drawing power within the board, the regulator itself wastes a fair bit of power all the time it is on.

An easy fix is to replace the on-board regulator with an LDO (low drop-out linear regulator) rated for extremely low quiescent current. Parametric searches on various vendor sites will yield likely substitutes.
3. Even with the above steps, the Arduino board does not provide a mechanism to set the LDO into low-power mode, if the LDO chosen supports this. Power efficient designs typically use a "sleep mode" pin on voltage regulators to save a fair bit of energy - not an option here.

Even with all possible power saving modes and tricks applied at the microcontroller level, the Arduino simply is not designed to be an ultra-low-power device out of the box. Having experimented with several non-trivial applications, I have found that the best that is realistically achievable is some 10% to 30% power saving depending on application, since the voltage regulator and the LEDs are going to consume the rest anyway.
> 26 votes

# Answer
You could read through the 200-page datasheet, and then mess with some confusing bit shifts and registers, but I recommend this library: http://playground.arduino.cc/Code/Enerlib

Also, if you're using an Uno or any one with a usb-to-serial chip, you could disable that or remove it.
> 13 votes

# Answer
Once your project is working and you need to deploy to "production" environment, you can opt to replace the Arduino with a bare meta ATMega328 or any of the ATTiny family chips. This will get rid of all the power eaters on the Arduino board you don't need. I found:

* Arduino board of 9V block battery - 56 mA
* ATTiny85 bare on 8 MHz without sleep modes etc - 10 mA
* ATTiny85 bare on 8 MHz in sleep mode - 0.03 mA

**Some more information**

Program an ATtiny with Arduino

ATTiny files for Arduino IDE
> 8 votes

---
Tags: power, battery
---


# Question
Title: Controlling image display on LED matrix by buttons
Building a 9x9 LED matrix and facing following 2 problems in Arduino code,

The current code displays 2 images (using byte arrays and then using bitRead) one by one, each for a certain duration of seconds. Persistence of vision is obtained by a delay of 300ms. There is a subroutine called upon in the main loop function with arguments of desired byte array and duration. I want to control the images by using 2 push buttons (push button1 and it displays 1st image until button2 is pressed, push button2 and second image is displayed until button1 is pressed). But the scanning algorithm exits the scan routine upon completion of the given input duration and restarts the routine with new argument (byte array of image2). I WANT THE IMAGE TO BE RETAINED ON THE MATRIX UNTIL BUTTON IS PRESSED. Can't figure out how to accomplish this.

If i nest the routine in a DO WHILE loop, then my problem is that how will the buttons be read from the main loop? Because I believe as long as the subroutine is being executed, main loop will be halted. (or I am totally wrong in this assumption?)

Reference code which I intend to manipulate. (Here its for an 8x8 Matrix. Thats not an issue)

```
byte bigHeart[] = {
    B01100110,
    B11111111,
    B11111111,
    B11111111,
    B01111110,
    B00111100,
    B00011000,
    B00000000};

byte smallHeart[] = {
    B00000000,
    B00000000,
    B00010100,
    B00111110,
    B00111110,
    B00011100,
    B00001000,
    B00000000};

const int columnPins[] = { 2, 3, 4, 5, 6, 7, 8, 9};
const int rowPins[] = { 10,11,12,15,16,17,18,19};

void setup() {
    for (int i = 0; i < 8; i++)
    {
        pinMode(rowPins[i], OUTPUT); // make all the LED pins outputs
        pinMode(columnPins[i], OUTPUT);
        digitalWrite(columnPins[i], HIGH); // disconnect column pins from Ground
    }
}

void loop() {
    int pulseDelay = 800 ; // milliseconds to wait between beats
    show(smallHeart, 80); // show the small heart image for 100 ms
    show(bigHeart, 160); // followed by the big heart for 200ms
    delay(pulseDelay); // show nothing between beats
}

// routine to show a frame of an image stored in the array pointed to by the
// image parameter.
// the frame is repeated for the given duration in milliseconds
void show( byte * image, unsigned long duration)
{
    unsigned long start = millis(); // begin timing the animation
    while (start + duration > millis()) // loop until the duration period has passed
    {
        for(int row = 0; row < 8; row++)
        {
            digitalWrite(rowPins[row], HIGH); // connect row to +5 volts
            for(int column = 0; column < 8; column++)
            {
                boolean pixel = bitRead(image[row],column);
                if(pixel == 1)
                {
                    digitalWrite(columnPins[column], LOW); // connect column to Gnd
                }
                delayMicroseconds(300); // a small delay for each LED
                digitalWrite(columnPins[column], HIGH); // disconnect column from Gnd
            }

            digitalWrite(rowPins[row], LOW); // disconnect LEDs
        }
    }
}

```

# Answer
> 1 votes
OK. Figured out a solution which is working for me. Upon reading a forum on Arduino.cc. That stated a nice analogy to handle this issue.

You have something to heat up on stove while also waiting for an important email which you have to respond to immediately. (You only have a PC in the farthest corner of house at which you have to monitor your outlook :D) How will you do both tasks simultaneously? Run the stove for 10seconds, go to PC to check email, return to stove, run it again for 10 seconds, then again go to PC to check email. Do this until you get the email or your food gets hot enough.

To implement this in our program. I read the states of 2 buttons at start of the main loop. Store their values in 2 variables. Then check the values to check if some button is pressed. if value A is 1 and B is 0, call function A, if A is 0 and B is 1 call function B. The called function comprises of the scan routine. So when called, it performs 1 scan and comes back to the main loop. If no button was pressed meanwhile, the variables have same values, so the same function is called again and it performs the 2nd scan. if a button was pressed meanwhile, then 2nd function is called instead of the 1st one. The speed of all this is enough so that the user does not experience any delays, neither Arduino misses a button pressed while executing the scan.

The LEDs started to flicker when I implemented this code. So I further reduced the delay in the scan routine (time for which each LED is lit before turning it off and lighting the next one) from 300 microsecond to 100 and all went fine. My matrix of 64 LEDs is working fine however I assume that if matrix goes beyond some 100 LEDs then problems like delay or flickering or reduced brightness may arise.

Here is the complete code

```
byte img1[] = {
    B01100110,
    B11111111,
    B11111111,
    B11111111,
    B01111110,
    B00111100,
    B00011000,
    B00000000
};

byte img2[] = {
    B00000000,
    B01100110,
    B01100110,
    B00000000,
    B00011000,
    B10000001,
    B01000010,
    B00111100
};

const int rowPins[] = {13,12,11,10,9,8,7,6};
const int columnPins[] = {5,4,3,2,14,15,16,17};

const int but1 = 18;
const int but2 = 19;

int but1State = 0;
int but2State = 0;
int but1Now;
int but2Now;

int value1;
int value2;

void setup() {

    for (int i = 0; i<8; i++){
        pinMode(rowPins[i], OUTPUT);
        pinMode(columnPins[i], OUTPUT);
        digitalWrite(columnPins[i], HIGH);
    }

    pinMode(but1, INPUT);
    pinMode(but2, INPUT);

    but1State = digitalRead(but1);
    but2State = digitalRead(but2);
}

void loop() {

    but1Now = digitalRead(but1);
    delay(5);
    int but1Now1 = digitalRead(but1);

    if(but1Now == but1Now1)
    {
        if(but1Now != but1State)
        {
            value1 = 1;
            value2 = 0;
            //show(img2);
        }

        but1State = but1Now;
    }

    but2Now = digitalRead(but2);
    delay(5);
    int but2Now1 = digitalRead(but2);

    if(but2Now == but2Now1)
    {
        if(but2Now != but2State)
        {
            value1 = 0;
            value2 = 1;
            //show(img2);
        }

        but2State = but2Now;
    }

    if(value1 == 1)
    {
        show(img1);
    }

    if(value2 == 1)
    {
        show(img2);
    }
}

void show(byte*image) {

    for(int row = 0; row<8; row++)
    {
        digitalWrite(rowPins[row], HIGH);

        for(int col=0; col<8; col++)
        {
            boolean pixel = bitRead(image[row],col);

            if(pixel == 1)
            {
                digitalWrite(columnPins[col], LOW);
            }

            delayMicroseconds(150);
            digitalWrite(columnPins[col], HIGH);
        }

        digitalWrite(rowPins[row], LOW);
    }
}

```

---
Tags: led, button
---


title: estimating battery run time

text:
# Question
Title: estimating battery run time
I have a project which runs a continuous loop and listens for the push of a button to light an led and activate a servo motor on an Arduino Uno (R2). The arduino is powered by 4 AA batteries, and the servo is powered by a 9V. I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this? As a side note, if anyone spots a way to improve battery life in my sketch / wiring, I'd love to know.

Below is my code and attached is the wiring diagram for the project (minus the batteries).

```
    #include <Servo.h>

const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonPushed = false;

const int ledPin =  13;      // the number of the LED pin

const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;

boolean servoActivated = false;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;

void setup() {
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

  servo.attach(servoPin);
  servo.write(servoStartAngle);

}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  int photoCellVal = analogRead(photoCellPin);

  if (photoCellVal > photoCellThreshold){
   photoCellActivated = true;
  } else {
   photoCellActivated = false;
  }

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW && buttonPushed == false) {
    // turn LED on:
    buttonPushed = true;
    Serial.println("button pushed");
  } else if (buttonState == LOW && buttonPushed == true){
   buttonPushed = false;
   Serial.println('deactivate');
  }

  if (buttonPushed == true){
   digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }

  if (buttonPushed && servoActivated == false && photoCellActivated == true){
    servoActivated = true;
    Serial.println("activate motor");

    for(angle = servoStartAngle; angle > servoEndAngle; angle--){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
  } else if (buttonPushed == false && servoActivated == true){ //deactivate
    for(angle = servoEndAngle; angle < servoStartAngle; angle++){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
    delay(200);
    servoActivated = false;

  }

  delay(200);
}

```

# Answer
> I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this?

If your circuit draws 1A @ 12V, a 12V 1Ah battery will power it for approximately one hour. A 9V alkaline typically contains about 565mAh. You can use the datasheets to sum all the power consumption, but its probably easier just to measure it with a multimeter.

> As a side note, if anyone spots a way to improve battery life in my sketch / wiring, I'd love to know.

-Check out the ATTiny series (parametric); they are tiny, low-power, and Arduino-compatible; perfect when you only need a couple of pins.

-Use an interrupt to monitor the button's pin; the MCU can sleep until the interrupt fires.

Generally:
1) The interrupt will set a flag so main() knows that something happened, then wake the processor.
2) Main() resumes, checks the flag, turns on/off the LED accordingly, tells the servo where to go, waits for the servo to get there (delay()), clears the flag, and then puts the MCU back to sleep.

-As others have pointed out, delay() is bad. delay() tells the MCU to **do nothing** (NO-OP) repeatedly, for a period of time. This is different from having **nothing to do** because it's asleep.
> 3 votes

# Answer
I can support what mheavers said in a comment above. Use a Bareduino or any kind of custom Board, use sleep-modes and avoid delay(). I wrote a blog-post about my experiences with this setup here, if you get it right the ATmel can go down below 1mA in sleep. In your case an extreme scenario (depending on your usage pattern) could be to wake-up the Arduino with an interrupt triggered through the sensor and otherwise sleep completely. You will find example on the net where people used a setup like this for remote controls for instance.
> 1 votes

---
Tags: arduino-uno, power, battery
---


title: use shiftIn and shiftOut with attiny85

text:
# Question
Title: use shiftIn and shiftOut with attiny85
I want my Attiny85 to communicate with another attiny85. one attiny should send a message to my other attiny. When he receives the correct message he should turn one led on. Just a very simple test scatch. I don't know why but the led never turns on.

Here is my code:

1st attiny85:

```
int clk_pin = 4,
    data_pin = 3,
    led = 0;

void setup() {
  pinMode(clk_pin, INPUT);
  pinMode(data_pin, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  byte incoming = shiftIn(data_pin, clk_pin, LSBFIRST);

  if (incoming == 2)
  {
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  }
}

```

2nd attiny:

```
int clk_pin = 0,
    data_pin = 1;

void setup(){
  pinMode(clk_pin, OUTPUT);
  pinMode(data_pin, OUTPUT);
}

void loop(){
  byte test = 2;
  shiftOut(data_pin, clk_pin, LSBFIRST, test);

  delay(5000);
}

```

I think there might be something wrong with my shiftIn/shiftOut command. It's actually the first time I'm using this.

Thanks for helping!

# Answer
`shiftIn()` and `shiftOut()` are designed for communicating with different types of shift registers. These are typically external components which don't run code themselves, such as the 74HC595.

You can't use `shiftIn()` to read data that's been written using `shiftOut()`. The reason is that both functions try to act as the host in the communication -- i.e. the one that controls the clock line.

When you call `shiftIn()`, the clock line is pulsed each time it's ready to read a bit (i.e. it tells the shift register when to write). When you call `shiftOut()`, the clock line is pulsed each time it writes a bit (i.e. it tells the shift register when to read).

Neither one will respond to a clock line provided externally. The result is that your ATTiny's aren't synchronised so they won't be reading/writing at the same time.

A much simpler approach would be to setup a conventional serial connection between the two microcontrollers. You could do that either using software or hardware serial. The only caveat is that the sender would need to ensure the receiver is up-and-running before it transmits anything. This could be done using some kind of handshake at startup -- one device repeatedly sends something until the other replies.
> 2 votes

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


title: Arduino Uno with crystal

text:
# Question
Title: Arduino Uno with crystal
Are there Arduino UNO R3s which use a crystal instead of a ceramic resonator?

(Frankly, I don't understand this cheapness: if you really want to save on component cost you can run both AVRs on the same crystal. The 16U2 always has a crystal.)

# Answer
> 3 votes
Some of the Freeduino boards use crystals although the newer ones now use a cheaper USB to serial chip (the CH340) instead of the Atmel chip used on the Arduino Uno.

The diavolino is another build-it-yourself board that has a crystal. I am sure there are many others. The ruggeduino is another that uses a crystal and also markets itself as being practically indestructible. Their "How to Destroy an Arduino" is well worth a read for things to avoid doing to your Uno.

# Answer
> 1 votes
It appears that the Arduino Leonardo uses a crystal:

On the Sparkfun site it's the same price as the Uno R3, so I think I'll go for the Leonardo.

---
Tags: arduino-uno, frequency
---


title: Pulse measurement

text:
# Question
Title: Pulse measurement
I am currently doing the project in pulse measurement using an Arduino Yún. I am using the pulse sensor SEN-11574.

When I verify the code I get this error:

```
Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
collect2: error: ld returned 1 exit status
Error compiling.

```

This is my code:

```
#include <pulse-sensor-arduino.h>

int pulsePin = 0;
int blinkPin = 13;
int fadePin = 5;
int fadeRate = 0;

volatile int BPM;
volatile int Signal;
volatile int IBI = 600;
volatile boolean Pulse = false;
volatile boolean QS = false;

void setup() {

    pinMode(blinkPin, OUTPUT);
    pinMode(fadePin, OUTPUT);
    Serial.begin(115200);
}

void loop() {

    sendDataToProcessing('S', Signal);
    if (QS == true) {
        fadeRate = 255;
        sendDataToProcessing('B',BPM);
        sendDataToProcessing('Q',IBI);
        QS = false;
    }

    ledFadeToBeat();

    delay(5000);
}

void ledFadeToBeat() {
    fadeRate -= 15;
    fadeRate = constrain(fadeRate,0,255);
    analogWrite(fadePin,fadeRate);
}

void sendDataToProcessing(char symbol, int data ) {
    Serial.print(symbol);
    Serial.println(data);
}

```

This is my pulse Arduino cpp file:

```
#include "pulse-sensor-arduino.h"

volatile int rate[10];                        // Array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
volatile unsigned long lastBeatTime = 0;      // Used to find IBI
volatile int P =512;                          // Used to find peak in pulse wave, seeded
volatile int T = 512;                         // Used to find trough in pulse wave, seeded
volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
volatile int pulsePin;

volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
volatile int PulseSensor::BPM;                // Used to hold the pulse rate
volatile int PulseSensor::Signal;             // Holds the incoming raw data
volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

void PulseSensor::begin(int pPin)
{
  pinMode(pulsePin, INPUT);
  pulsePin = pPin;

  // Initializes Timer1 to throw an interrupt every 2 ms.
  TCCR1A = 0x00;
  TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
  OCR1A = 0x7C;   // 2 ms
  TIMSK1 = 0x02;
  sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
// Timer 1 makes sure that we take a reading every 2 miliseconds
ISR(TIMER1_COMPA_vect)
{                         // Triggered when Timer1 counts to 124
  cli();                                      // Disable interrupts while we do this
  PulseSensor::Signal = analogRead(pulsePin); // Read the Pulse Sensor
  sampleCounter += 2;                         // Keep track of the time in ms with this variable
  int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

  // Find the peak and trough of the pulse wave
  if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
    if (PulseSensor::Signal < T){                        // T is the trough
      T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
    }
  }

  if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
    P = PulseSensor::Signal;                             // P is the peak
  }                                        // Keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  //
  // The signal surges up in value every time there is a pulse
  if (N > 250){                                   // Avoid high-frequency noise
    if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
    {
      Pulse = true;                               // Set the Pulse flag when we think there is a pulse
      PulseSensor::IBI = sampleCounter - lastBeatTime;         // Measure time between beats in mS
      lastBeatTime = sampleCounter;               // Keep track of time for next pulse

      if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // Clear secondBeat flag
        for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
          rate[i] = PulseSensor::IBI;
        }
      }

      if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // Clear firstBeat flag
        secondBeat = true;                   // Set the second beat flag
        sei();                               // Enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // Keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // Clear the runningTotal variable

      for(int i=0; i<=8; i++){                // Shift data in the rate array
        rate[i] = rate[i+1];                  // And drop the oldest IBI value
        runningTotal += rate[i];              // Add up the 9 oldest IBI values
      }

      rate[9] = PulseSensor::IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // Add the latest IBI to runningTotal
      runningTotal /= 10;                     // Average the last 10 IBI values
      PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
      PulseSensor::QS = true;                              // Set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
    Pulse = false;                         // Reset the Pulse flag so we can do it again
    amp = P - T;                           // Get amplitude of the pulse wave
    thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
    P = thresh;                            // Reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // If 2.5 seconds go by without a beat
    thresh = 512;                          // Set thresh default
    P = 512;                               // Set P default
    T = 512;                               // Set T default
    lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
    firstBeat = true;                      // Set these to avoid noise
    secondBeat = false;                    // When we get the heartbeat back
  }

  sei();                                   // Enable interrupts when youre done!
} // end ISR

```

This is my pulse Arduino header file:

```
#ifndef PULSE_SENSOR_ARDUINO_H
#define PULSE_SENSOR_ARDUINO_H

#include "Arduino.h"

class PulseSensor
{
public:
  static void begin(int pulsePin);

  static volatile int BPM;
  static volatile int Signal;
  static volatile int IBI;
  static volatile boolean QS;
};

#endif

```

I modified the program, but there is a new error present:

```
Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::begin(int)'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `__vector_17':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:54: multiple definition of `__vector_17'
pulsesensor.cpp.o:pulsesensor.cpp:54: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::Signal'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `sampleCounter'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `lastBeatTime'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.thresh+0x0): multiple definition of `thresh'
pulsesensor.cpp.o:(.data.thresh+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): multiple definition of `PulseSensor::IBI'
pulsesensor.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.T+0x0): multiple definition of `T'
pulsesensor.cpp.o:(.data.T+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.P+0x0): multiple definition of `P'
pulsesensor.cpp.o:(.data.P+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `rate'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::BPM'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::QS'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.firstBeat+0x0): multiple definition of `firstBeat'
pulsesensor.cpp.o:(.data.firstBeat+0x0): first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
/home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `secondBeat'
pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.amp+0x0): multiple definition of `amp'
pulsesensor.cpp.o:(.data.amp+0x0): first defined here
collect2: error: ld returned 1 exit status
Error compiling.

```

Here is my change code

```
#include <pulse-sensor-arduino.h>

int blinkPin = 13;                // Pin to blink LED at each beat
int fadePin = 5;                  // Pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // Used to fade LED on with PWM on fadePin

void setup(){
  pinMode(blinkPin,OUTPUT);         // Pin that will blink to your heartbeat!
  pinMode(fadePin,OUTPUT);          // Pin that will fade to your heartbeat!
  Serial.begin(115200);             // We agree to talk fast!

}

void loop(){
  sendDataToProcessing('P', PulseSensor::Signal);     // Send Processing the raw Pulse Sensor data
  if (PulseSensor::QS == true){                       // Quantified Self flag is true when arduino finds a heartbeat
    fadeRate = 255;                  // Set 'fadeRate' Variable to 255 to fade LED with pulse
    sendDataToProcessing('B',PulseSensor::BPM);   // Send heart rate with a 'B' prefix
    sendDataToProcessing('Q',PulseSensor::IBI);   // Send time between beats with a 'Q' prefix
    PulseSensor::QS = false;                      // Reset the Quantified Self flag for next time
  }

  ledFadeToBeat();

  delay(5000);                             //  Take a break
}

void ledFadeToBeat(){
  fadeRate -= 15;                         //  Set LED fade value
  fadeRate = constrain(fadeRate,0,255);   //  Keep LED fade value from going into negative numbers!
  analogWrite(fadePin,fadeRate);          //  Fade LED
}

void sendDataToProcessing(char symbol, int data ){
    Serial.print(symbol);                // Symbol prefix tells Processing what type of data is coming
    Serial.println(data);                // The data to send culminating in a carriage return
}

```

My cpp file:

```
#include "pulse-sensor-arduino.h"

volatile int rate[10];                        // Array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
volatile unsigned long lastBeatTime = 0;      // Used to find IBI
volatile int P =512;                          // Used to find peak in pulse wave, seeded
volatile int T = 512;                         // Used to find trough in pulse wave, seeded
volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
volatile int pulsePin;

volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
volatile int PulseSensor::BPM;                // Used to hold the pulse rate
volatile int PulseSensor::Signal;             // Holds the incoming raw data
volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

void PulseSensor::begin(int pPin)
{
  pinMode(pulsePin, INPUT);
  pulsePin = pPin;

  // Initializes Timer1 to throw an interrupt every 2 ms.
  TCCR1A = 0x00;
  TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
  OCR1A = 0x7C;   // 2 ms
  TIMSK1 = 0x02;
  sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
// Timer 1 makes sure that we take a reading every 2 miliseconds
ISR(TIMER1_COMPA_vect)
{                         // Triggered when Timer1 counts to 124
  cli();                                      // Disable interrupts while we do this
  PulseSensor::Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // Keep track of the time in ms with this variable
  int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

  //  Find the peak and trough of the pulse wave
  if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
    if (PulseSensor::Signal < T){                        // T is the trough
      T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
    }
  }

  if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
    P = PulseSensor::Signal;                             // P is the peak
  }                                        // Keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // Avoid high frequency noise
    if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
    {
      Pulse = true;                               // Set the Pulse flag when we think there is a pulse
      PulseSensor::IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // Keep track of time for next pulse

      if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // Clear secondBeat flag
        for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
          rate[i] = PulseSensor::IBI;
        }
      }

      if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // Clear firstBeat flag
        secondBeat = true;                   // Set the second beat flag
        sei();                               // Enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // Keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // Clear the runningTotal variable

      for(int i=0; i<=8; i++){                // Shift data in the rate array
        rate[i] = rate[i+1];                  // And drop the oldest IBI value
        runningTotal += rate[i];              // Add up the 9 oldest IBI values
      }

      rate[9] = PulseSensor::IBI;                          // Add the latest IBI to the rate array
      runningTotal += rate[9];                // Add the latest IBI to runningTotal
      runningTotal /= 10;                     // Average the last 10 IBI values
      PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
      PulseSensor::QS = true;                              // Set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
    Pulse = false;                         // Reset the Pulse flag so we can do it again
    amp = P - T;                           // Get amplitude of the pulse wave
    thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
    P = thresh;                            // Reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // If 2.5 seconds go by without a beat
    thresh = 512;                          // Set thresh default
    P = 512;                               // Set P default
    T = 512;                               // Set T default
    lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
    firstBeat = true;                      // Set these to avoid noise
    secondBeat = false;                    // When we get the heartbeat back
  }

  sei();                                   // Enable interrupts when youre done!
} // end ISR

```

# Answer
> 2 votes
(1)The declaration

```
 volatile boolean Pulse = false;

```

occurs in two locations.

Is that intended?

(2) Also

```
volatile int PulseSensor::BPM;                // used to hold the pulse rate
volatile int PulseSensor::IBI = 600;          // holds the time between beats, must be seeded!
volatile int PulseSensor::Signal;             // holds the incoming raw data

```

---
Tags: programming, sensors, arduino-yun, arduino-ide
---


# Question
Title: Value of the counter collide on my lcd while decreasing. How can I remove it?
```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);
int visitor=0;  //variable for counting visitor number

unsigned long timer_1,timer_2;  //variables for recording time for ir_1 and ir_2

void setup() {
   lcd.begin(20,4);
   pinMode(A0,INPUT);
   pinMode(A1,INPUT);
}

void loop(){
 lcd.setCursor(0,4);
   lcd.print("visitor=");
   lcd.setCursor(8, 4);

   lcd.print(visitor);

   if(digitalRead(A0)==1 && digitalRead(A1)==0)
  {
    timer_1= millis();
  }
  if(digitalRead(A0)==0 && digitalRead(A1)==1)
  {
    timer_2= millis();
  }
  if(timer_1>timer_2)
  {
   lcd.setCursor(8,4);
   visitor=visitor+1;
   lcd.print(visitor);
   delay(2000);
   timer_1=0;
   timer_2=0;
  }
 else if(timer_1<timer_2)
  {
   lcd.setCursor(8,4);
   visitor=visitor-1;
    if (visitor<=0)
  {
    visitor=0;
  }
   lcd.print(visitor);
   delay(2000);
   timer_1=0;
   timer_2=0;

  }

}

```

Two IR sensors are placed in A0 and A1.

While the value of `visitor` is decreasing from 10 to 9 the LCD is showing 90 because the '0' of previous 10 is here. How can I remove it?

# Answer
A simple option would be to call `lcd.clear()` at the start of `loop()`. That will clear the entire LCD display. Everything else should work fine because it looks like you're outputting the entire display contents every time round.

Alternatively, you could remove the extra digit by printing a space over it, e.g.:

```
if (visitor < 10) print(" ");
lcd.print(visitor);

```

If `visitor` is a 1-digit number (i.e. less than 10), it will output a space at the start, getting rid of any underlying digits leftover from a previous iteration. If you want the number to be left-aligned then you could print the space after the number instead.
> 2 votes

---
Tags: lcd, ir
---


# Question
Title: Using multiple timers and avoiding conflicts
I would like to use three timers in CTC mode to launch three Interrupt Service Routines at different frequencies.

In this application I need to use the servo library, millis() and micros() functions.

**Timer3** (Working)

Thanks to this question, Timer3 has been set up in the following way:

```
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count:  @~744 Hz
  OCR3A = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  ISR(TIMER3_COMPB_vect)
  {
     cont++;
  }

```

**Timer4** I've tried with this configuration:

```
cli();          // disable global interrupts
TCCR4A = 0;     // set entire TCCR3A register to 0
TCCR4B = 0;     // same for TCCR3B

// set compare match register to desired timer count: @ ~744 Hz
OCR4A = 20;
// turn on CTC mode:
TCCR4B |= (1 << WGM42);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR4B |= (1 << CS40) | (1 << CS42);
// enable timer compare interrupt:
TIMSK4 |= (1 << OCIE4B);
//TIMSK4 |= (1 << OCIE4A); same issue
// enable global interrupts:
sei();

ISR(TIMER4_COMPB_vect) //TIMER4_COMPA_vect same issue
{
  cont++;
}

```

But the compiler returns an error caused by the servo library conflict:

> Servo\Servo.cpp.o: In function '\__vector\_42': C:\Program Files (x86)\Arduino\libraries\Servo/Servo.cpp:117: multiple definition of '\__vector\_42' Timer4B\_800Hz.cpp.o:C:\Program Files (x86)\Arduino/Timer4B\_800Hz.ino:49: first defined here c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

As Gerben suggested in a comment in this question:

> They are just hogging all timers. I guess you have to alter the library slightly by removing the #define \_useTimer3 line, or try putting a #undef \_useTimer3 right after the include. – Gerben

I would avoid changing the servo library since motors play a critcal role in the application.

**Timer 5** Same issue

Which timers and output compare registers can I use to set up the three ISR correctly?

# Answer
The problem is the Servo library. This library is claiming all the timers, so you can't use them yourself. What I do to fix this is edit the Servo.h (or ServoTimers.h) file.

```
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//#define _useTimer5
#define _useTimer1
#define _useTimer3
//#define _useTimer4
//typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers }   timer16_Sequence_t;
typedef enum { _timer1, _timer3, _Nbr_16timers } timer16_Sequence_t;

```

This will remove the 2 timers (4 and 5) for the Mega boards, but you can still attach 24 servo's. If you need more, you should edit this file again.
> 1 votes

---
Tags: arduino-mega, library, interrupt, timers, servo
---


title: create a interruption-proof power

text:
# Question
Title: create a interruption-proof power
I need to create a interruption-proof power for a project of mine, very similar to the design of this link.

My problem is that I need to adjust the current delivered of the solar panel (21V, 1.2A) to 5V and simultaneously charge a battery 12V, 18Ah. If the solar panel does not supply power, the battery takes its place.

Does anyone know any circuit to do something? Or can someone give me a light as do something?

# Answer
Rough block diagrams below show two ways this can be achieved - "Easiest" costs least but is inefficient. "Better" uses PV panel output more efficiently. Details of either can be discussed if of interest.

'Schottky diodes' should be used to minimise losses.

(1) "Easiest"

Connect PV panel to battery with diode.
Panel is clamped to battery voltage (+ diode drop).
This will not hurt the PV panel but wastes some of the available power.
\[What is the formal PV panel specification. Is it 21V O/C or loaded or .... Do you have a datasheet link for it?\].

Use 12V (nominal) to 5V converter to power load. This could be

* A linear regulator - only about 40% efficient - very wasteful.
* A buck converter (build or buy from eg ebay)

(2) "Better"

Use a buck regulator to charge the battery - ideally an MPPT (maximum power point transfer) controller. Details can be discussed if you are interested.

Use a second buck regulator to power the load. This must be capable of (at least) 11V to 22V input. Power this from a Schottky diode from the PV panel AND a Schottky diode from the battery. When the panel voltage is \> battery voltage the panel will power the load.
> 1 votes

---
Tags: power, solar
---


# Question
Title: unable to install usbserial driver for GPRS shield with mac air vs. 10.9
Despite all my efforts and web crawling I can not install the necessary driver to connect my Arduino uno R3 to the GPRS shield from seeedstudio. I have attempted downloading the VCP driver from http://www.ftdichip.com/Drivers/VCP.htm I have tried the solution offered here https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac for Yosemite and beyond through the AppleUSBFTDI driver as well as the solution offered by FTDI's script. Any help will be greatly appreciated. Please let me know if I can provide any more information.

# Answer
The USB serial connection is provided by the Arduino, not the shield, and the naming pattern for an Uno on OSX will not be tty.usbserial### but rather something else (tty.usbmodem### perhaps?).

If I recall correctly, an Uno does not require a driver on OSX though older/unofficial FTDI based boards (as well as unofficial boards based on yet other fixed function chips) do require drivers.

(On Linux it is typically /dev/ttyUSB# for fixed function and /dev/ttyACM# for an Uno, both using kernel module drivers shipped with most distributions. On Windows they are all COM# and drivers are typically required)
> 1 votes

---
Tags: serial, usb, ftdi
---