# Question
Title: How to properly receive data from accelerometer @ arduino in processing and map it?
I'm busy making a project where my accelerometer @arduino can controle a ellipse @processing

But the problem is, it doesn't work. With the code I have now, I can receive the data from the accelerometer in processing. But my map function doesn't seem to work because with my code, the ellipse doesn't move at all. When i want to map the val (string) it says it must be a float to be mapped. I've tried to convert the string into a float but it doesn't work at all..

Hope someone can help me out!

My arduino Code:

```
#include <Wire.h>
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

int waardeX;
int waardeY;

Adafruit_MMA8451 mma = Adafruit_MMA8451();            //maak object acceleromter aan

void setup(void) {
  Serial.begin(9600);                                 //begin Seriële verbinding
  Serial.println("Adafruit MMA8451 test!");           //print waardes accelerometer

  if (! mma.begin()) {                                //mma.begin() om de sensor te herkennen.
    Serial.println("Couldnt start");                  //"MMA8451 found!" bij goed signaal, "Couldnt start" bij slecht signaal
    while (1);
  }
  Serial.println("MMA8451 found!");

  mma.setRange(MMA8451_RANGE_2_G);                    //lees range van 2_G (voor relatief slome bewegingen)

  Serial.print("Range = "); Serial.print(2 << mma.getRange());
  Serial.println("G");

}

void loop() {

  // Read the 'raw' data in 14-bit counts
  mma.read();                                         //lees rauwe data accelerometer uit
  Serial.print("X:\t"); Serial.print(mma.x);          //lees x waardes
  Serial.print("\tY:\t"); Serial.print(mma.y);        // lees y waardes
  Serial.println();                                   //print de waardes met een delay van 500ms
  delay(500);

  /* Get a new sensor event */
  sensors_event_t event;

  Serial.write(waardeX);
  Serial.write(waardeY);
}

```

Processing code:

```
import processing.serial.*;

Serial myPort;                                   //Maak Serial object aan
String waardeX;                                      //Ontvangen data van serial poort.

//int waardeX;
int waardeX1;
int waardeY2;
int waardeY;

void setup() {
  printArray(Serial.list());
  String portName = Serial.list()[0];            //0 is mijn Arduino poort.
  myPort = new Serial(this, portName, 9600);     //open de poort. Zelfde als serial.begin(9600) bij arduino zodat arduino en processing hetzelfde communiceren.

  size(500, 500);                                //Grootte van het scherm
}

void draw() {
  background(255);                               //Achtergrondkleur
  ellipse(waardeX1, waardeY, 20, 20);               //20,20 is grootte/breedte cirkel
  fill(200, 10, 100);                                       //maak het bolletje zwart

  waardeX1 = (int)map(waardeX, 4000, -4000, 0, 500);        //waardeX mappen naar waa
//  waardeY = (int)map(waardeY2, -4000, 4000, 0, 500);

  {
    if ( myPort.available() > 0)
    {  // Als de data beschikbaar is:
      val = myPort.readStringUntil('\n');         //Lees het en zet het in val
    }
        println(waardeX); //print it out in the console
  }
}

```

# Answer
The problem you are facing is that you are sending the string:

```
X:⇥23.87⇥Y:⇥11.34

```

and trying to interpret that as a single number. It's just not going to happen. There's two numbers and two labels there.

Instead you are going to have to parse the string to get at the individual components.

You might want to look at the java String.split() function to convert the string into an array of 4 items, then you can use the second and fourth slices (slices 1 and 3 since it's zero-based) and convert them to floats.
> 1 votes

---
Tags: arduino-uno, accelerometer, code-review, signal-processing
---


# Question
Title: WiFi thermometers: save different location string as const across many devices
I've built a very simple WiFi thermometer out of an Adafruit ESP8266 HUZZAH breakout board and a TMP36 temperature sensor. I have it reporting the temperature over wifi to my computer which will be storing the data in a database for monitoring purposes. I'd like to make multiple of these devices and place them around the house. My question: I currently have the location of the board as a `const char*` on the board itself. Doing this for multiple devices is just a bad idea and a nightmare to manage. Is there some way of setting a location variable on the board that will persist across shutdowns? Or am I coming at the problem from completely the wrong direction?

# Answer
> 1 votes
With a set of DIP switches or jumpers on some of the GPIO, you could encode a unique number for each one - 16 of them with 4 I/Os f/ex. The same code could run on all of them, sample the unique ID report it along with the temperature. Let the PC-side map IDs to locations.

---
Tags: esp8266, adafruit
---


title: Set PWM frequency to 25 kHz

text:
# Question
Title: Set PWM frequency to 25 kHz
I currently can set four PWM pins to around 31 kHz with the following code:

```
void setup()
{
    TCCR1B = TCCR1B & B11111000 | B00000001; // Set PWM frequency for D9 & D10:
    pinMode(pwmPin9, OUTPUT); // Sets the pin as output
    pinMode(pwmPin10, OUTPUT); // Sets the pin as output

    TCCR2B = TCCR2B & B11111000 | B00000001; // Set PWM for D3 & D11
    pinMode(pwmPin3, OUTPUT); // Sets the pin as output
    pinMode(pwmPin11, OUTPUT); // Sets the pin as output
}

```

I found this setup somewhere, but I don't know how I can set these four PWM pins to around 25 kHz instead. How is that possible?

# Answer
> 14 votes
I am posting this second answer since I realized it is possible to have 4 PWM channels at 25 kHz with 161 steps on a single Arduino Uno. This involves changing the main clock frequency to 8 MHz, which has some side effects since the whole program will run half as fast. It also involves reconfiguring the three timers, which means loosing the Arduino timing functions (`millis()`, `micros()`, `delay()` and `delayMicroseconds()`). If these trade-offs are acceptable, here is how it goes:

```
void setup()
{
    // Set the main system clock to 8 MHz.
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();

    // Configure Timer 0 for phase correct PWM @ 25 kHz.
    TCCR0A = 0;           // undo the configuration done by...
    TCCR0B = 0;           // ...the Arduino core library
    TCNT0  = 0;           // reset timer
    TCCR0A = _BV(COM0B1)  // non-inverted PWM on ch. B
        | _BV(WGM00);  // mode 5: ph. correct PWM, TOP = OCR0A
    TCCR0B = _BV(WGM02)   // ditto
        | _BV(CS00);   // prescaler = 1
    OCR0A  = 160;         // TOP = 160

    // Same for Timer 1.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
        | _BV(COM1B1)  // same on ch. B
        | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
        | _BV(CS10);   // prescaler = 1
    ICR1   = 160;

    // Same for Timer 2.
    TCCR2A = 0;
    TCCR2B = 0;
    TCNT2  = 0;
    TCCR2A = _BV(COM2B1)  // non-inverted PWM on ch. B
        | _BV(WGM20);  // mode 5: ph. correct PWM, TOP = OCR2A
    TCCR2B = _BV(WGM22)   // ditto
        | _BV(CS20);   // prescaler = 1
    OCR2A  = 160;
}

void loop()
{
    analogWrite( 3,   1);  // duty cycle = 1/160
    analogWrite( 5,  53);  // ~ 1/3
    analogWrite( 9, 107);  // ~ 2/3
    analogWrite(10, 159);  // 159/160
}

```

Unlike the other answer, this does not need a modified version of `analogWrite()`: the standard one will work fine. Only care should be taken that:

1. The value written should be between 0 (meaning always LOW) and 160 (always HIGH), inclusive.
2. Only pins 3, 5, 9 and 10 are available. Attempting to `analogWrite()` to pins 6 or 11 will not only fail to deliver a PWM output, it will also change the frequency on pin 5 or 3 respectively.

# Answer
> 13 votes
You can configure Timer 1 to cycle at 25 kHz in phase correct PWM mode, and use it's two outputs on pins 9 and 10 like so:

```
// PWM output @ 25 kHz, only on pins 9 and 10.
// Output value should be between 0 and 320, inclusive.
void analogWrite25k(int pin, int value)
{
    switch (pin) {
        case 9:
            OCR1A = value;
            break;
        case 10:
            OCR1B = value;
            break;
        default:
            // no other pin will work
            break;
    }
}

void setup()
{
    // Configure Timer 1 for PWM @ 25 kHz.
    TCCR1A = 0;           // undo the configuration done by...
    TCCR1B = 0;           // ...the Arduino core library
    TCNT1  = 0;           // reset timer
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
           | _BV(COM1B1)  // same on ch; B
           | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
           | _BV(CS10);   // prescaler = 1
    ICR1   = 320;         // TOP = 320

    // Set the PWM pins as output.
    pinMode( 9, OUTPUT);
    pinMode(10, OUTPUT);
}

void loop()
{
    // Just an example:
    analogWrite25k( 9, 110);
    analogWrite25k(10, 210);
    for (;;) ;  // infinite loop
}

```

Writing a value of 0 with `analogWrite25k()` means the pin will be always LOW, whereas 320 means always HIGH. The regular `analogWrite()` should *almost* work, but it will interpret 255 the same as 320 (i.e. always HIGH).

This code assumes an Arduino Uno or similar board (ATmega168 or 328 @ 16 MHz). The method used here requires a 16-bit timer, and thus it uses Timer 1 as it's the only one available on the Uno; that's why only two outputs are available. The method could be adapted to other AVR-based boards with a 16-bit timer. As Gerben noted, that timer should have a corresponding ICRx register. There are 4 such timers on the Arduino Mega, each with 3 outputs.

---
Tags: pwm, frequency
---


# Question
Title: Do I need more voltage to close this circuit?
I'm hacking together a RF-controlled garage door opener. I'm tapping the "receiving" end in to the push button wires.

When the two wires touch, it toggles the garage door motor.

I'm trying to basically "close" this circuit through a 5V Trinket Pro with...

`pinMode(A0,OUTPUT);` in `setup` and `digitalWrite(A0,LOW);` in the `loop`.

Using the multimeter, it would seem that the wires for the push button are normally closed (I think that's correct) as I get a 15v read on the multimeter when I check the current.

When I touch the wires, the current drops to 0.

My understanding was that the `digitalWrite(A0,LOW);` would basically "complete" the circuit, but it doesn't seem to do anything.

So, my question is: Given I've only got 5v running through the Trinket Pro, is that not enough to toggle the garage door circuit given it's putting out 15v in it's NC state?

If that's the case, is there some other way around that without needing to push 15v of power?

# Answer
The Trinket really doesn't want to see 15v across one of its I/O pins. You'll do better using a solid-state (SSR) or mechanical relay to close the 15v motor-start circuit, one that can be activated by the 5v output of the Arduino pin.

Update:
A relay has 4 specs that you need to consider up front:

* The coil (or switching input of a SSR) voltage, and
* The coil (or switching input) current;

These are what the Arduino or an add-on switching circuit will have to drive. And:

* The contact max voltage, to limit arcing when they open
* the contact max current, to limit them heating,

Or, in the case of an SSR, to prevent letting out the Magic Smoke that makes them work.

If you use a relay you'll need a driver circuit between the Arduino pin and the relay, with a snubber - a diode that grounds the reverse voltage "kickback" from the relay coil when you open its circuit - also to protect the Magic Smoke in your Arduino.

You're hacking into your remote "clicker", not the garage-door tractor itself, right? If that's the case, just about anything with a 5v coil 15v+ contacts will do. The remote button only has to switch a tiny transmitter on/off. If you do need to hack into the tractor, you'll want to find out what's behind its receiver terminal. It's probably not the motor but another relay, but....

A ready source of such a relay is your/another garage door remote receiver. It has a relay in it that is already doing that job.
> 2 votes

---
Tags: power, voltage-level, adafruit
---


# Question
Title: Arduino Prototype on Breadboard: "avrdude: stk500_recv(): programmer is not responding"
I have created an arduino prototype using the exact instructions found on this page:

https://www.arduino.cc/en/Main/Standalone

However, when I plug in the micro USB power supply and try to upload a program, here's the error I get:

```
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

```

I have tried the following solutions, to no avail: 1) press the restart button (in a variety of ways and lengths of time) 2) Enable verbose output 3) trying the different board types in the Arduino IDE 4) Checking the COM port

I have no idea what to do I've basically tried everything I could find, on this website and others.

I hope you guys can help! Thanks very much :)

# Answer
Remove the pins connected to Tx and Rx while uploading the code , it worrked for me. also include all the libraries currently used in your program. Good luck!!
> 0 votes

# Answer
Check for Baudrate, the Arduino Serial Terminal, and serial port terminal should exactly match.

Or either check your Rx and Tx pins for respective voltages Either there may be problem related to power supply. It is better you also mention the code
> 0 votes

---
Tags: serial, programming, sketch, prototype
---


# Question
Title: Arduino Project Power Consumption Calculations
I have built an automated window blind controller that will adjust the angle of a servo based on the value received via a light dependent resistor. Once every 10 minutes the MCU wakes up, gets the current value of the LDR, adjusts the angle of the servo accordingly and then goes back to SLEEP\_MODE\_PWR\_DOWN using the watchdog timer. I am using a 5v 16MHz ATMega168 Arduino Pro Mini as the MCU. I have removed both of the on board LEDs to reduce idle power consumption. I am also powering directly from the VCC pin so that I bypass the on board regulator reducing power consumption even more. I'm trying to determine what is the best battery power option for this project. The project is still in testing but appears to be working as intended.

Here is the sketch:

```
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <VarSpeedServo.h>

const int ldrPin = A0;          //Analog pin that the light dependent resistor is connected to
const int ldrPower = 8;         //Supply 5v to ldr just before reading and then shutoff after
const int servoPin = 9;         //Digital pin that the Clone Futaba S3003 servo is connected to

//PARAMETERS FOR LOW BATTERY WARNING
const int xVPin = A1;             //Analog pin that the external +V non-boosted power supply is connected to
const int lowVLED = 10;           //Digital pin LED is connected to.  Used to identify battery levels
const int flashDelay = 250;       //LED flash length for low battery warning
const int numFlash_Low = 3;       //Number of LED flashes for LOW battery warning
const int numFlash_Mid = 1;       //Number of LED flashes for MID battery warning
int runningTotalVoltage;          //Variable that stores the sum total of the voltage readings
float voltage = 0.00;             //Calculate voltage
unsigned sampleCount = 0;         //Variable that stores the current voltage sampling number
unsigned char LEDFlashCount = 0;  //Variable that stores the current LED flash number
const int voltageSamples = 20;    //Total number of voltage readings to take
float boostVoltage = 5.27;        //Variable for the output voltage from the 5v boost coverter
float minValert = 3.20;           //Variable for the very low battery level (for 3.7v Li-on battery)
float midValert = 3.60;           //Variable for early warning low battery level (for 3.7v Li-on battery)

//PARAMETERS FOR THE SERVO
VarSpeedServo myservo;        //Create servo object to control servo
const int angle1 = 2350;      //Variable for "Fully Closed" servo moving counter-clockwise rotation
const int angle2 = 1900;      //Variable for "Partially Open" servo moving conter-clockwise rotation
const int angle3 = 1468;      //Variable for "Fully Open" servo moving counter-clockwise rotation
int dest = 0;                 //Servo destination depending on sensor reading
const int spd = 15;           //Controls the speed of the servo moving between positions; 5 is slow
int prevPos = 0;              //Keep track of the angle two loops prior
int currPos = 0;              //Keep track of the angle one loop prior
int nextPos = 0;              //Keep track of the angle moving to during current loop

//PARAMETERS FOR THE VARIOUS LIGHT LEVELS THAT TRIGGER THE SERVO TO ROTATE
int lightLevel;               //The analog reading from the LDR
const int lowLight = 400;
const int midLight = 800;

int ATimer;
int BatTimer;
int SleepTime = 80;  //80 = 10 Min
int BatCheckTime = 8;  //8 = 1 Min

//WATCHDOG INTERRUPT
ISR (WDT_vect)
{
  wdt_disable();
}

void setup()
{
  //Serial.begin(9600);
  myservo.attach(servoPin);
  myservo.write(angle3, spd, true);
  pinMode(lowVLED, OUTPUT);
  pinMode(ldrPower, OUTPUT);
  doFirstRun();
}

void loop()
{
  BatteryCheckTimer();
  AwakeTimer();
  if (BatTimer == BatCheckTime)
  {
    doBattCheck();
  }

  if (ATimer == SleepTime)
  {
    doWhileAwake();
  } //End of Main loop if timer was reached

//Preparing to go to sleep

  byte old_ADCSRA = ADCSRA;                        // disable ADC //
  ADCSRA = 0;                                      // disable ADC //

  byte old_PRR = PRR;                              // disable Internal modules//
  PRR = 0xFF;                                      // disable Internal modules//

  MCUSR = 0;                                       // clear various "reset" flags//

  // Watchdog Timer Parameters//
  WDTCSR = bit (WDCE) | bit (WDE);                 // allow changes, disable reset
  WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0);   // set WDIE, and 8 seconds delay
  wdt_reset();                                     // pat the dog once program has executed.

  // Sleep Activation //
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);            //Sleep mode Selection//
  sleep_enable();                                  //Sleep Now//

  sleep_cpu ();                                    //CPU is now sleeping

// Once awake, code executes from this point. Once CPU wakes up do the follwoing to restore full operations
  sleep_disable();
  PRR = old_PRR;
  ADCSRA = old_ADCSRA;
}

void BatteryCheckTimer()
{
  BatTimer++;
}

void AwakeTimer()
{
  ATimer++;
}

void doFirstRun()
{
  digitalWrite(ldrPower, HIGH);
  delay(flashDelay);
  lightLevel = analogRead(ldrPin);  //Query photo cell
  digitalWrite(ldrPower, LOW);
  //Define the ranges based on how bright it is, and set corresponding servo position
  if (lightLevel <= lowLight)
  {
    //Servo rotates to fully closed
    dest=angle1;
    nextPos=angle1;
  }
  else if (lightLevel > lowLight && lightLevel <= midLight)
  {
    //Servo rotates to partially open
    dest=angle2;
    nextPos=angle2;
  }
  else if (lightLevel > midLight)
  {
    //servo rotates to fully open
    dest=angle3;
    nextPos=angle3;
  }
  prevPos = nextPos;
  currPos = nextPos;
  myservo.attach(servoPin);         //Connect to servo
  myservo.write(dest, spd, true);   //Move the servo to the new position
  delay(flashDelay);
  myservo.detach();                 //Detach servo to keep it from humming on strain
  ATimer = 0;
  BatTimer = 0;
}

void doBattCheck()
{
  while (sampleCount < voltageSamples)
  {
    runningTotalVoltage += analogRead(xVPin);
    sampleCount++;
    delay(10);
  }
  //The boostVoltage value is external power source dependent.  If using a 5v boost conveter
  //check the boost output voltage and then enter that number in the boostVoltage variable.
  voltage = ((runningTotalVoltage/voltageSamples) * (boostVoltage/1023));
  if (voltage >= minValert && voltage <= midValert)
  {
    while (LEDFlashCount < numFlash_Mid)
    {
      digitalWrite(lowVLED, HIGH);
      delay(flashDelay);
      digitalWrite(lowVLED, LOW);
      LEDFlashCount++;
      delay(flashDelay);
    }
  }
  else if (voltage < minValert)
  {
    while (LEDFlashCount < numFlash_Low)
    {
      digitalWrite(lowVLED, HIGH);
      delay(flashDelay);
      digitalWrite(lowVLED, LOW);
      LEDFlashCount++;
      delay(flashDelay);
    }
  }
  sampleCount = 0;
  runningTotalVoltage = 0;
  LEDFlashCount = 0;
  BatTimer = 0;
}

void doWhileAwake()
{
  digitalWrite(ldrPower, HIGH);
  delay(flashDelay);
  lightLevel = analogRead(ldrPin);  //Query photo cell
  digitalWrite(ldrPower, LOW);
  //Define the ranges based on how bright it is, and set corresponding servo position
  if (lightLevel <= lowLight)
  {
    //Servo rotates to fully closed
    dest=angle1;
    nextPos=angle1;
  }
  else if (lightLevel > lowLight && lightLevel <= midLight)
  {
    //Servo rotates to partially open
    dest=angle2;
    nextPos=angle2;
  }
  else if (lightLevel > midLight)
  {
    //servo rotates to fully open
    dest=angle3;
    nextPos=angle3;
  }
  //IF the photocell reading is different from last sample then execute servo controls
  if (nextPos == prevPos && nextPos != currPos)
  {
    prevPos = currPos;
    ATimer = 0;
  }
  else if (nextPos != prevPos && nextPos != currPos)
  {
    prevPos = currPos;
    currPos = nextPos;  //Remember angle so we can compare it again next round
    pos_change();
  }
  else
  {
    prevPos = currPos;
    ATimer = 0;
  }
}

//This code moves the servo to the desired position
void pos_change()
{
  myservo.attach(servoPin);         //Connect to servo
  myservo.write(dest, spd, true);   //Move the servo to the new position
  delay(flashDelay);
  myservo.detach();                 //Detach servo to keep it from humming on strain
  ATimer = 0;
}

```

So, I hooked up a multi-meter and set it to monitor current draw. I watched it for 30 minutes and below are the results.

1. Constant current draw is 26.8 microamps.
2. Every minute the sketch wakes up and quickly checks the battery voltage. This process takes less than a seconds and the current draw increases to 38.8 microamps.
3. Every ten minutes the sketch wakes up and checks the LDR sensor. If the sensor reading is different from the last reading the servo moves to a new preset angle. When this happens the current draw increases to about 11 milliamps. I forced a servo rotation a couple of times during this time period so that I could measure the current draw. However, during the course of a normal day, I would expect the servo to rotate no more than four times (when the sun is rising, when the sun is at its highest level, when the sun is setting, and finally when the sun has completely set).

For the last 12 days I have been running the project from a single 18650 3.7v LiPo battery. When I started the battery was at 4.12v. Battery reading today is about 3.68v. Seems to me that the project is draining the battery faster than it should be. I drained the battery and then fully charged it before starting the test so I know the battery is good. I used an inline power bank capacity tester to measure the battery capacity during charge and when it was done it registered 2405 mah.

Here are the components of this project:

1. Arduino pro mini with on board LEDs and voltage regulator removed.
2. LDR sensor with 10k resistor
3. LED with 220K resistor for low battery warning
4. 5v boost converter with on board LEDs removed (used to boost the 3.7v LiPo battery to 5v; actually boosts to about 5.27v)
5. Knock-off clone Futaba S3003 servo

Ultimately I would like to be able to power this project from a couple of 18650 batteries for 3 months or maybe 3 AA batteries for the same period of time. Based on my research and power consumption expectations, I should be able to do it. If I can't get any better power consumption out of this little think, I might hookup a small solar panel with a LiPo battery charge controller to help extend the battery life.

Any thoughts? Thanks.

# Answer
> 1 votes
You should measure with a power meter the consumption of the arduino in the two conditions, active and standby. Remember that batteries last only for the 80% of their total capacity. If you can't achieve better results, you should build it with an attiny85.

# Answer
> 1 votes
If you look at the discharge curves of LiPo batteries, you can see the voltage will drop a bit faster when full. Then flatten out, and have a big voltage drop when they are almost empty. So I'm not sure you can tell from the 0.44V drop that the battery is being discharged faster.

If there is a problem, I think it is either the boost converters quiescent current, or the servo. Also not that because you have to convert the 3.7V up to 5V, the current coming from the battery will have to increase by 1.35 times (at 100% efficiency).

What booster are you using? How do you turn off the servo?

PS1; I always use this calculator to get an approximate battery life.

PS2; I'd connect the pull-up resistor on the LDR to a digital pin, so you can activate it only when you need to measure the light level, saving 2-5 µA.

# Answer
> 1 votes
The constant draw of 26.8 μA amounts to 0.6432 mAh per day. 38.8 μA for one second per minute is an additional 0.0048 mAh per day, and a second of 11 mA draw six times per hour would be 0.44 mAh per day. This totals to 1.088 mAh per day, or 13.056 mAh in 12 days. That's less than 5% of the 2405 mAh mentioned as the LiPo's capacity. Judging from the usual discharge voltage graphs, battery voltage should still be above 4 V at that point.

If the above is correct, you might have a defective battery, or defective current measurements. You could charge the battery in question, then connect a 100KΩ–150KΩ resistor across it. As the battery discharges, measure and record its voltage a couple of times a day. If you charge up several batteries at the same time, you could set one aside as an experimental control, attach a resistor across one of them, and attach another to your circuit.

The 26.8 μA draw while in power-down sleep is higher than I'd expect \[by a factor of 3 or so\]. If it includes boost converter quiescent current, perhaps use a PFET to shut down the converter when the servo isn't needed. I'm supposing the Arduino is powered directly from the battery, and that you have a boost converter to get servo power. Will the servo work ok straight from the battery?

You could power the Arduino straight from one LiPo, and power the converter and/or servo from another, to make it more likely the system will degrade safely as the batteries run down.

\[Edit:\] Although your Pro Mini is a 5V version, since you are powering directly from the VCC pin you can run it at a lower voltage. See §30.3 Speed Grades, in spec sheet, for the “Safe Operating Area”, ie, the guaranteed-to-work voltage-vs-MHz region. From Figure 30-1, Maximum Frequency vs. VCC, 3.78 V safely supports 16 MHz operation. Running the Pro Mini at 16 MHz below that voltage is out of spec, but I'd expect it to work fine even at appreciably lower voltages.

Prescaling the system clock \[see last paragraph, below\] also reduces voltage requirements. As the system clock scales down, current draw scales down more than linearly. \[End Edit\]

When trying to reduce current draw in sleep mode, work with a sketch that just tries out various setups; that is, a sketch that doesn't read the LDR or control the servo. A simple test sketch makes it easier to figure out what is going on. You can try tests such as all irrelevant pins initialized to low outputs, or to pulled-up inputs, etc.

It looks like the code doesn't do any intensive processing. The CPU needn't run at 16 MHz while executing delays. Instead, you could prescale the system clock (ref. §10.10, System Clock Prescaler, in spec sheet) which will drop CPU current from a few milliamps to under a milliamp during delays. You'd divide your delay counts by the scale factor, and might also change ADC clock scaling (ref. §25.4, Prescaling and Conversion Timing, in spec sheet).

---
Tags: power, servo, arduino-pro-mini, battery, sleep
---


# Question
Title: Sharp GP2Y0A710K0F IR sensor behaving strangely
I have just purchased a new Sharp GP2Y0A710K0F IR sensor online. As a sanity check, I wrote this simple code to check if the sensor is working correctly. The code is expected to print output voltage from the sensor, which is based on the distance

```
int sensorpin = A5;
int val = 0;

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

void loop()
{
val = analogRead(sensorpin);
Serial.println(val);
delay(100);
}

```

Now the output is quite strange. The output values start from zero and keep on increasing until they reach 1023, and then gradually decrease down to zero and this keeps on happening, even if something is kept in front of the sensor.

Is my sensor a faulty one? or is it supposed to give out similar outputs. If it has to, how do I convert these values to meter or centimeters.

The product description on the manufacturer's website said that it has a 3 pin interface, however it has a 5 pin one, the wires being Red, Black, Yellow, White, Green if seen from the left side. I guessed from the datasheet that Red and Black are for power and Yellow for signal output and hence I have connected only these 3 wires. The Green and White wires are unconnected. Also, pin numbers aren't marked.

# Answer
> 1 votes
I suspect you have it wired wrongly.

You need to consult the outline diagram in the datasheet and work out which colour wire is which function. It's this bit:

By your wiring description it sounds like you may be powering it through Vo and reading the result through VCC, which won't work - and at worst may damage it.

---
Tags: arduino-uno, sensors, analogread, ir
---


# Question
Title: What purpose does the yellow and green LEDs have on the Arduino?
I have wired up a small project with a shift register (see below), but depending on how I put the 74HC595 IC (8-bit shift register with 3-state output register), the green and yellow LEDs of the Arduino stop shining.

What are these LEDs for? Do they tell something about a possible damage of the IC/short circuit in the setup?

# Answer
> 13 votes
The green LED is marked with `ON`, and it indicates that the Arduino has power.

The yellow LED is marked `L` and is just connected to pin 13. So when you set pin 13 to HIGH the LED lights up. You can however still use pin 13 for other things.

When the green LED stops shining you most likely have a short somewhere. As the short will drain all power away, so the Arduino has no power left to light the LED(s).

# Answer
> 6 votes
Also be warned that the `L` LED (the one activated by pin 13) may light up if pin 13 is high-impedance (set to input), and is not connected to anything.

On my Uno, a trivial sketch like this lights up the `L` LED:

```
void setup ()
  {
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

This is because the LED is not driven directly by pin 13, but by an op-amp (U5B) which -- if the pin is configured as an input -- may pick up enough stray voltage to activate and light up the LED.

This can be confusing because you might look at your board and think "huh? I didn't command that LED to come on".

# Answer
> 2 votes
Also note that there is the TX and RX pins on Uno (orange/yellowish) are for the USB connection. When the LED labeled TX is lit up, the Arduino is transmitting data to the computer. When the RX is lit up, it is receiving data from the computer.

# Answer
> 1 votes
Just wanted to re-iterate that On the MEGA 2560 Revision 3 you can't change the L led pin 13 due to the op-amp like Nick Reported.

Spent a couple hours on this scratching my head only to find this out

---
Tags: arduino-uno
---


title: Serial.println not outputting

text:
# Question
Title: Serial.println not outputting
I ran the following really simple code on my micro and the monitor is just blank, not displaying any zeroes or anything and the Tx light isn't lighting up. I haven't used analog inputs much so I don't know what could be causing this. Can anyone help? Thanks, here's the code

```
int sensePin = 0;
void setup() {
    analogReference(DEFAULT);
    Serial.begin(9600);
}

void loop() {
  Serial.println(analogRead(sensePin));
  delay(500);

}

```

# Answer
> 1 votes
The answer to no ouput, and suspecting your data source is to replace the data source with a constant value or a string until you get that problem sorted, and then go back to your data source and debug that if necessary.

That said, I don't see any issue with you trying to print the output of an analog read. Obviously you should get *something*, even if it's just a single zero on each line, twice a second.

* Is your monitor the Arduino built-in monitor?
* Is it set to 9600 baud, as you've set your output rate in the program?
* Is there anything else connected to the Tx pin, Pin-1 (Arduino numbering, not chip numbering)?
* There were no error messages from the compiler or loader, right? (The libraries, bless-'em, always get a few warnings; unfortunately we have to ignore those).
* You've no reason to believe the Arduino is other than 100% good?

---
Tags: analogread, arduino-micro, genuine
---


# Question
Title: ADXL345 I2C setup not returning anything
My hookup is like this:

GND - GND VCC - 5V CS - 5V SDO - GND SDA - A4 SCL - A5

Here is the code:

```
#include <Wire.h>
#include <ADXL345.h>

ADXL345 accelerometer;

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

  // Initialize ADXL345
  Serial.println("Initialize ADXL345");

  if (!accelerometer.begin())
  {
    Serial.println("Could not find a valid ADXL345 sensor, check wiring!");
    delay(500);
  }
  if (accelerometer.begin())
  {

  // Values for Free Fall detection
  accelerometer.setFreeFallThreshold(0.35); // Recommended 0.3 - 0.6 g
  accelerometer.setFreeFallDuration(0.1);  // Recommended 0.1 s

  // Select INT 1 for get activities
  accelerometer.useInterrupt(ADXL345_INT1);

  // Check settings
  checkSetup();
  }
}

void checkSetup()
{
  Serial.print("Free Fall Threshold = "); Serial.println(accelerometer.getFreeFallThreshold());
  Serial.print("Free Fall Duration = "); Serial.println(accelerometer.getFreeFallDuration());
}

void loop(void)
{
  delay(50);

  // Read values for activities
  Vector norm = accelerometer.readNormalize();

  // Read activities
  Activites activ = accelerometer.readActivites();

  if (activ.isFreeFall)
  {
    Serial.println("Free Fall Detected!");
  }
}

```

It comes from this Github link: https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345\_free\_fall/ADXL345\_free\_fall.ino

Initially, it would return "Could not find a valid ADXL345 sensor, check wiring!" in serial monitor. After messing with some wiring and changing to SPI and back to I2C, it only returns "Initialize ADXL345".

I've added the second if() statement because it wouldn't say anything other than "Initialize ADXL345" even with the first if() statement, or with the first if() followed by an else. It should print the Free Fall Threshold and Duration but it hasn't. I have to leave and won't be back until tomorrow, so when I get back I'll try removing the checkSetup() command and maybe put something else in it's place to verify it's working. I feel like the answer is staring me in the face.

EDIT: Okay so after I finally got up from my computer for once, a thought popped into my mind and I figured the reason why checkSetup() isn't returning either string is because it's declared after setup() calls checkSetup()? Am I right? I feel like this would be the case in other languages.

# Answer
You may have damaged the chip with 5 V already. Sparkfun didn't include a regulator in their breakout. Your pull-ups are also too small; significant current flows when the I2C lines are pulled low. Use two 4.7k or 10k resistors instead. Assuming your Redboard is just like the Uno, connect pin 2 to the INT1 pin of the breakout, to make use of the interrupt capabilities. You also need to call `attachInterrupt()` and register a handler.

However, you bought this module from Sparkfun, as well as your Redboard. You should first follow their tutorial and library before trying any others. Theirs is SPI-based though. If you must use I2C, try out the Adafruit library.
> 0 votes

---
Tags: i2c, accelerometer
---


# Question
Title: How to communicate from Python to Arduino Softserial
That is driving me nuts so I need your help.

Master : PC with Ubuntu, a USB to serial converter (chipset CP2102), connected to Arduino Uno Pin 10, 11 and GND. The Arduino Uno is plugged in the same PC.

Port for the converter is `/dev/ttyUSB1` Port for the Arduino is `/dev/ACM0`

I tried to communicate by Serial through the converter (I do not want to use ACM0 as it is buggy and sometimes suddenly change to ACM1, messing up my big testing program).

On Arduino side :

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
int inByte = 0;         // incoming serial byte

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

void loop() {
  if (mySerial.available()) {
    char inByte = mySerial.read();
    mySerial.println(inByte);
    Serial.println(inByte);
  }
  delay(10);
}

```

The Python script (simple one to debug)

```
import serial
arduino = serial.Serial('/dev/ttyUSB1', 9600)
arduino.timeout=0.5
arduino.bytesize=8
arduino.stopbits=1
code=49 #ASCII Code for 1
arduino.write(chr(code).encode('utf-8'))
print(chr(code))
print(chr(code).encode('utf-8'))
print(arduino.readline())
print("done")
arduino.close()

```

When I run it, I have on Arduino Serial monitor a `g`

and Python script output

```
1
b'1'
b'Ly\x00'
done

```

By the way, the very same code over `/dev/ttyACM0` and standard serial rather than Softwareserial works perfectly (as long as the port remains ACM0 of course)

# Answer
> 1 votes
That is all me, look for an answer for ages, finally post a question, to end up finding the answer in the following hour...

this is because Arduino takes TTL as input and not RS-232...

similar here : https://electronics.stackexchange.com/questions/42584/arduino-uno-weird-characters-sent-to-com-softwareserial

---
Tags: serial, python
---


title: compare uint8_t to char array

text:
# Question
Title: compare uint8_t to char array
I am not actually using ad arduino but an atmel chip. but my question is c microprocessor related

I am reading an uart which returns data in the form uint8\_t \[100\] I can print the return just fine, the return is "OK"

but when I try to use strcmp(read, "OK") I do not get the expected value, I get a mismatch ( strcmp returns 13, not 0)

```
uint8_t  sigfox_rd_buf[100] = {0};
uint8_t sig_rd = 0;

io_sigfox->read(io_sigfox,&sig_rd, 1);
while(sig_rd != 10) // read until end char
 {
     sigfox_rd_buf[i] = sig_rd;
     i++;
     io_sigfox->read(io_sigfox,&sig_rd, 1);
 }
 if(strcmp((char *)sigfox_rd_buf,"OK") == 0 )
 {
  do_something()
 }
 else
{
complain();
}

```

and I always end up in complain for some reason.. please help!! :)

# Answer
> 1 votes
When using strcmp(), strings should be terminated with a NULL character. Which, by the way, is a zero. Your code should work as is if you replace the Line Feed character (10 or 0x0a) with a NULL (0 or 0x00). That is assuming the string you are getting back is 0x4f, 0x4b & 0x0a. Or you could play it safe and replace strcmp with strncmp. Then explicitly state the number of characters to compare:

```
if(strncmp((char *)sigfox_rd_buf,"OK",2) == 0 )

```

---
Tags: c
---


title: PWM Every Other Pin Doesn't Read

text:
# Question
Title: PWM Every Other Pin Doesn't Read
**Scenario**

I've plugged 6 pins from my RC receiver into my Arduino in order to read the incoming values.

**Problem**

I'm using Digital PWM~ pins 2-6. Oddly the Arduino only reads odd channels:

```
1480, 0, 1175, 0, 991, 0

```

I've that if I physically reverse the cables (2-7, 3-6, 4-5) going into the Arduino I get ALL values:

```
988, 983, 1511, 1174, 1490, 1487

```

I've found that if I go back to my initial pin setup and merely flip neighbors (2-3, 4-5, 6-7) that works as well.

**Question**

What could possibly be causing this?

**Code**

```
Here is the current code I've written

int ch1, ch2, ch3, ch4, ch5, ch6;
int ch1Pin = 2;
int ch2Pin = 3;
int ch3Pin = 4;
int ch4Pin = 5;
int ch5Pin = 6;
int ch6Pin = 7;

void setup() {
  pinMode(ch1Pin, INPUT);
  pinMode(ch2Pin, INPUT);
  pinMode(ch3Pin, INPUT);
  pinMode(ch4Pin, INPUT);
  pinMode(ch5Pin, INPUT);
  pinMode(ch6Pin, INPUT);

  Serial.begin(9600);
}

void loop() {
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);

  String p = (String)ch1;
  p += ", " + (String)ch2;
  p += ", " + (String)ch3;
  p += ", " + (String)ch4;
  p += ", " + (String)ch5;
  p += ", " + (String)ch6;
  Serial.println(p);

//  delay(100);
}

```

**Photo**

# EDIT

Since posting this question I've found that reversing the `chXpin` values accomplishes the same effect as reversing the physical pins. This makes me thing it's a software issue so I'm digging in further.

# TEMPORARY SOLUTION

I'm not sure why this works but flipping the neighbor order of `pulseIn` fixed the issue:

```
  /* OLD
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  */

  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);

```

Why did that work? It makes no sense to me.

# Answer
`pulseIn()` is a *blocking function*: it waits until it gets a complete pulse, or until it times out. While it's waiting, the Arduino cannot do anything else, and it will miss pulses on other channels.

The RC receiver sends the pulses sequentially. Then, if you try to read them in the right sequence, it may work. If you read them out of sequence, you will miss some pulses, and the corresponding `pulseIn()` calls can timeout, returning zeros.

For this kind of job I would use the pin change interrupt on pins 2 – 7. This should allow reading the six pulses continuously without blocking the whole program. But it's low-level (AVR-level) programming, probably not doable with the standard Arduino libraries.

**Edit**: Here is what I had in mind when suggesting the use of the pin change interrupt. Notice that the pin numbers are “hardwired” into the code and cannot be changed easily. This is because:

1. Pins 2 – 7 share a single pin change interrupt request (PCINT2\_vect), thus a single ISR is needed to time the six channels.
2. They also share a port (port D), meaning they can all be read by the ISR in a single instruction.

The other possible choices having these nice properties would be pins 8 – 13 (PCINT0\_vect, port B) or A0 – A5 (PCINT1\_vect, port C).

```
/*
 * Read 6 PWM signals from an RC receiver.
 *
 * Channels 0-5 are on digital pins 2-7 (i.e. PD2-PD7 = PCINT18-23).
 */

// This always contains the last length measured on each channel.
volatile uint16_t last_pulse_lengths[6];

// Interrupt triggered on every change in pins 2-7.
ISR(PCINT2_vect)
{
    static uint8_t last_pin_states;
    static uint16_t start_times[6];  // start time for each channel
    uint8_t pin_states = PIND >> 2;  // shifted to bits 0-5
    uint16_t now = micros();

    // Check every changed bit of the port.
    for (int i = 0; i < 6; i++) {
        uint8_t mask = _BV(i);

        // Record start time on rising edge.
        if ((pin_states & mask) && !(last_pin_states & mask))
            start_times[i] = now;

        // Record pulse length on falling edge.
        if (!(pin_states & mask) && (last_pin_states & mask))
            last_pulse_lengths[i] = now - start_times[i];
    }
    last_pin_states = pin_states;
}

// Return the pulse lengths avoiding race conditions.
static void get_pulse_lengths(uint16_t lengths[6])
{
    for (int i = 0; i < 6; i++) {
        noInterrupts();
        uint16_t tmp = last_pulse_lengths[i];
        interrupts();
        lengths[i] = tmp;
    }
}

void setup()
{
    // Setup the pin change interrupt.
    PCIFR  = _BV(PCIF2);  // clear pin change interrupt flag
    PCICR  = _BV(PCIE2);  // enable pin change interrupt
    PCMSK2 = 0xfc;        // sense changes on pins 2-7 (i.e. PD2-PD7)

    Serial.begin(9600);
}

void loop()
{
    // Report the pulse lengths on the serial console.
    uint16_t pulse_lengths[6];
    get_pulse_lengths(pulse_lengths);
    for (int i = 0; i < 6; i++) {
        Serial.print(pulse_lengths[i]);
        if (i < 5) Serial.print(", ");
        else Serial.println();
    }

    delay(1000);
}

```
> 1 votes

---
Tags: arduino-uno, pwm, input
---


title: RGB LED blinks when analogWrite is low

text:
# Question
Title: RGB LED blinks when analogWrite is low
I have set up an LED who's brightness is controlled by a sonar sensor. The sonar works well and I can see the values coming from it through the serial monitor. The LED fades until about 700 using analogWrite

```
#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 5000

int LED_PIN = 3;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
    delay(50);
    int uS = sonar.ping();
    long int max_uS = 8000;
    float brightness = (1-(((float)uS/(float)max_uS)))*1024;
    if(brightness < 0){
        brightness = 0;
    }
    Serial.print("Distance: ");
    Serial.print(uS / US_ROUNDTRIP_IN);
    Serial.print("\" ");
    Serial.print(uS);
    Serial.print(" ");
    Serial.println(brightness, 5);

    analogWrite(LED_PIN, brightness);
}

```

When I view the serial monitor, I've made it output a line that looks like this:

```
Distance: 10" 1500 830.00000

```

830 is the number I'm using for my `analogWrite`. I can move my hand farther and closer to the distance sensor and when I do, the light fades, but after 13" (which is brightness = 774) the LED looks like it turns back on high.

Between 1"-13" it fades very smoothly, except at 13" the light is almost out, then at about 14" it turns on again almost at full brightness and is very hit or miss from there. Even though the numbers in the serial monitor are holding steady.

Any reason for this?

# Answer
The maximum value you can pass to `analogWrite()` is 255. Anything higher than that will wrap around back to 0.

You should scale your value to fit into 0-255 instead of 0-1024.
> 2 votes

---
Tags: rgb-led
---


# Question
Title: What is the wiring of arduino motor shield to Nano?
I have the basic version of the stepper motor driver and a Nano, I see the pins are set to plug directly in to a Uno or similar Arduino, but according to the documentation it just needs most of the digital pins connected to the arduino - https://learn.adafruit.com/adafruit-motor-shield/faq

As it seems they are the opposite position to plug into a breadboard for testing, I may need to wire and solder them (11 to D11, 3 to D3, 5 to D5, 6 to D6). Is this correct or does the Nano not have the power/amperage/timing or something to run this type of shield, hence the lack of compatibility listed for that shield?

# Answer
I found that this does work with the Nano - the only reason they don't list it is because it doesn't fit in to the shield I suppose.
> 0 votes

# Answer
I believe, though it's not clear, that the shield in question uses a 74HC595 shift register to control the main motor drivers - the other pins are for the servo interfaces (and they are just wired 1:1). Theoretically you can therefore use any pins you like to control the motor drivers themselves.

It's not the same as the Adafruit one which looks to use direct Arduino control of the motor drivers.
> 0 votes

# Answer
Or just another simple version (which is more hardcore such as brute force): Get expansion shield for nano to uno :)

I think this is just a sandwich version, which just takes additional space and cost.
> 0 votes

---
Tags: arduino-nano, shields, arduino-motor-shield
---


# Question
Title: Triggering capacitive touch on a touch device
As you can see in the video, it is possible to trigger a touch with arduino. I have tried a couple of methods but with no success.

* I have a wire soldered on to a coin which is being used to trigger the touch.
* I tried to directly connect pin 2 from arduino to the coin (no touch applies)
* I tried to connect a relay and transistor, seems necessary for this project but I didnt get it to work either.

I will say I have very little knowledge of relay/transistor and the wiring part of it, so Im guessing thats where the problem is.

My parts:

Transistor P2N2222A: http://www.onsemi.com/pub\_link/Collateral/P2N2222A-D.PDF

Relay: JZC-11F

Sketch used:

```
  void setup() {
  digitalWrite(2,LOW);
}

void loop() {

  pinMode(2, INPUT);
  delay(500);

  pinMode(2, OUTPUT);
  delay(500);

}

```

If possible please provide a frizting schematic showing how to connect.

# Answer
> 1 votes
Capacitive touch screens are design (both the hardware and software) to work with human fingers and human like movements. It could be that you are not only working against the physical aspects of influencing capacitance at the screen location you are interested in controlling, but also the software which is trying to reject noise and "unwanted touches".

That said, this stack exchange question / answer addresses some of your questions and even proposes an (untested) circuit to try. I would suggest to skip the "accepted" answer and read the answer with the highest score.

Based on the above response, I would suggest changing your strategy. I might try connecting the Arduino directly to the metal probe. Then changing the software to alternate between putting a negative then positive voltage potential on the metal probe. Avoiding using the Atmel's input or high impedance configuration. I might also try a smaller metal probe that covers a smaller area of the target device. Perhaps something that is conductive and easily reforms to a flat screen as if it were a finger tip. Something like a small ball of aluminum foil. Also, make sure that there is nothing else touching the screen like tape or a stray wire. Such objects may cause the target's software to consider all touch events as noise or as "unwanted touches".

---
Tags: arduino-uno, wires
---


title: What does "+=" mean?

text:
# Question
Title: What does "+=" mean?
I'm working with an esp8266 and want to have it default to an access point when it cannot connect to a wifi network. I'm using chriscook8's example from github here.

chriscook8 uses "+=" in several places and I can't find an explanation of what that means.

Here is an example from setup():

```
void setup() {
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.println("Startup");
  // read eeprom for ssid and pass
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 32; ++i)
  {
    esid += char(EEPROM.read(i));  //<- here
  }

```

What does += do?

# Answer
It adds the value or variable on the right to the variable on the left and assigns the result to the variable on the left.

```
A += B

```

is the same as:

```
A = A + B

```

It's short-hand.

In the case of a String it concatenates the right hand item on to the end of the left hand item.
> 6 votes

# Answer
`+=` is a common programming shortcut. An example: (pseudo-code)

```
num1 = 7
num2 = 15
#these two lines are exactly the same
num1 += num2
num1 = num1 + num2

```

`+=` is extremely useful for increasing the value of a variable by another variable. It also works similarly with `-=`, `*=`, and `/=`
> 3 votes

# Answer
In the earliest days of the C language (I'm talking late 60's here), the compilers did not do much (if any) optimization, and a lot of the constructs in C were put in so that a programmer could get a more optimized program by using hints like +=. So, in those days, `A = A + 5` generated three PDP11 instructions, while `A += 5` was only a single PDP11 instruction. That meant that most programmers learned to write it that way. But because it was more concise and to many also more readable, the C constructs with `<op>=` have made it into most modern languages.
> 0 votes

---
Tags: c++
---


# Question
Title: Access method from main sketch inside class
I am lost at this one. In Java, I would do it this way:

Inside the main sketch, I would instantiate the object from the class:

```
do = new DoClass(this);

```

I would also include a method inside the main sketch:

```
public void doSomething(){}

```

Then, inside the DoClass, I would have the following constructor:

```
    public class DoClass{
       Sketch sketch;
       public DoClass(Sketch skt){
          this.sketch = stk;
       }
 }

```

Then, at some point, I would call, from DoClass:

```
stk.doSomething():

```

which should be the same as calling:

```
doSomething();

```

from the main sketch. Any ideas how to achieve that? If yes, could you please show an example of how to achive the above example in Arduino?

# Answer
The great thing about Java is that it was designed to have a similar syntax as C++ and Arduino will gladly compile C++. So if you're familiar with Java this should be pretty easy for you.

check out This Tutorial

As for your example...

Much like Java, it is best practice to put C++ classes in their own files, but it is not required. If you use Java you are used to "importing" modules and classes into the class you are creating. Similarly C++ imports header files (behind the scenes it is much different, but functionally the same).

To do this first you would create a header file. This is just a text file with the extension ".h" or ".hpp" intead of ".txt" - traditionally .h is used only for c files and .hpp would be for c++. The header file will include the class and method prototypes.

Before I get to your example, as a side note:

*Your example using the "sketch" variable is somewhat confusing because a sketch is just what the world of Arduino calls a program and it would not be used as variable.*

"DoClass.hpp"

```
class DoClass {
  int var;
public:
  DoClass(int var);
  int getVar();
};

```

"DoClass.cpp"

```
#include "DoClass.hpp"

DoClass::DoClass(int variable){
  var = variable
}

int DoClass::getVar(){
  return var;
}

```

The "::" means "member of" so the *getVar()* is a method of DoClass.

These files should be saved in your sketch folder. If you are creating a class that will be reused you can place it in ../sketches/libraries/.

```
#include "DoClass.hpp"
setup(){
  ...
}

DoClass myClass(5);  // creates class
int testVal;

loop(){
  ...
  testVal = myClass.getVar();

}

```
> 1 votes

# Answer
Unlike Java, which insists on everything being inside a class, C++ allows “plain” functions which do not belong to any class. In fact, `main()` in standard C++, as well `setup()` and `loop()` in Arduino code, are all plain functions. Then, the main program (or “sketch” if you wish) is not an object, you cannot give it to the constructor of your class. Instead, you would give it a pointer to the particular function it needs. This is called a *callback*, because the library is calling back something from your main program.

Here is how I would write it in C++:

```
/*
 * Class definition.
 */

class DoClass {

    // Define a callback type: a pointer to a function taking no
    // arguments and returning void.
    typedef void (*callback_t)();

public:
    // Constructor.
    DoClass(callback_t _callback)
        // Initialize internal callback with the one given as parameter.
        : callback(_callback)
        // empty function body
        {}

    // This class method invokes the callback.
    void doIt() { callback(); }

private:
    // The callback is kept as private internal data.
    callback_t callback;
};

/*
 * Main program.
 */

// This is the function we are going to provide as a callback.
void doSomething()
{
    Serial.println(F("Doing some work..."));
}

// Instantiate the class statically.
DoClass doObject(doSomething);

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

void loop()
{
    doObject.doIt();  // <- this will invoke our callback.
    delay(1000);
}

```

The class could be instantiated dynamically (`DoClass *doObject = new DoClass(doSomething);`). I prefer to do it statically when possible, because dynamic memory allocation can easily led to memory fragmentation problems in such small platforms.
> 1 votes

---
Tags: class
---


# Question
Title: How to user timer interrupts for times longer than can TNCTx can keep track of?
I am trying to program my Arduino Mega 2560 to effectively create a PWM signal on any digital pin using timer interrupts and timer1. The pins will pulse a finite amount of times (not indefinitely). I am first trying this with a 256-prescaler value, which I believe means that each increment of my TCNT1 is 16.0 microseconds, and since it is a 16-bit register, it can reach a max. value of 1048567 microseconds.

I am designing the program so that the period and duty cycle are changed by Serial commands that the user can send (I already have that part figured out). I am using clear timer on compare mode and OCR1A and OCR1B to toggle the digital pin between HIGH and LOW.

If the desired period is less than 1048567 microseconds, I can divide the period by the modified clock (modified by the prescaler) to figure out the OCR1A value, and then based on the desired duty cycle, calculate OCR1B. Then I set the ISR vectors for A and B to toggle the pin and count down until the desired number of cycles is completed.

What I would like to also allow the user to do is set periods/duty cycles that would be longer than 1048567 microseconds, but I'm not sure how to accomplish that. For example, if I wanted to have the pin be HIGH for 2 seconds with a total period of 10 seconds, I would choose values for OCR1B and OCR1A that, through the ISR(TIMER1\_COMPA\_vect) and ISR(TIMER1\_COMPB\_vect), I could keep track (through a counter variable) of how many interrupts had occurred. If enough interrupts had occurred to equal the time of that the pin had to be HIGH and/or LOW, the ISRs would actually trigger the toggling of the pin (instead of just counting the number of interrupts).

How could I choose the OCR1B and OCR1A values that would accomplish this optimally? Is it reasonable to keep track of time this way as a workaround to the limitation of the timer counter max value? I am open to any suggestion and I appreciate any input. Thank you.

# Answer
> 2 votes
By maintaining your own second-level prescaler you can quite easily keep track of longer periods.

The most efficient method is to use a "divide and multiply by two" scheme.

---

1. Start with a custom pre-scaler of 1.
2. While the count period is \> 65535:
    1. Multiply the pre-scaler by 2.
    2. Divide the count period by 2

---

```
uint16_t ps = 1;
uint32_t period = 429864;

while (period > 65535) {
    ps <<= 1;
    period >>= 1;
}

```

Then you can load the count period register with the now divided count period and use a variable to count the number of times the interrupt has been triggered. When it equals your custom pre-scaler value you reset the count to 0 and run your actual interrupt routine.

The left and right shifts multiply by two and divide by two respectively in a very efficient manner. Far more than multiplying by 10, or dividing the period by 65536 and using that as a prescaler.

---
Tags: arduino-mega, timers, isr
---


title: 100khz square wave with 50% duty cycle

text:
# Question
Title: 100khz square wave with 50% duty cycle
How to generate 100khz square wave with 50% duty cycle using arduino uno The following code was tried but did not give appropriate output

```
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delayMicroseconds(5); // wait for 5 micro seconds, 100khz frequency with  50%
                           // duty cycle
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delayMicroseconds(5);              // wait for 5 micro seconds
}

```

# Answer
> 4 votes
The problem with your program is that it does not loop fast enough. Each call to `delayMicroseconds()` should take roughly the requested time to execute, but the CPU also needs time to execute the rest of your code, including the time needed to return from `loop()` and call it again. The period of the signal ends up being considerably longer than the desired 10 µs.

The simplest software-only approach would be to get rid of the delay using the technique described in the Blink Without Delay Arduino tutorial. With one twist: instead of

```
// save the last time you blinked the LED
previousMillis = currentMillis;

```

you would use

```
// save the last time you should have blinked the LED
previousMillis += interval;

```

This way the small timing errors do not add up: you get, *on average* the correct period. Oh, and obviously, you track time in microseconds, not milliseconds:

```
const uint16_t TOGGLE_TIME = 5;  // toggle pin every 5 us

void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    static uint16_t last_toggle;
    static uint8_t pin_state = LOW;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        pin_state = !pin_state;       // invert pin state
        digitalWrite(13, pin_state);
        last_toggle += TOGGLE_TIME;
    }
}

```

This may somehow work if you have a fast enough Arduino, maybe a Due or a Zero. If you have an AVR-based board (like the Uno and actually most Arduinos), you will not get anything faster than ≈ 50 kHz with this. This is because `digitalWrite()` is sooo slooow, it cannot cope with your 100 kHz. You can improve things by using direct port access\[\] instead of `digitalWrite()`:

```
void loop() {
    static uint16_t last_toggle;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        PINB = _BV(PB5);             // invert pin state
        last_toggle += TOGGLE_TIME;
    }
}

```

Now you have roughly the requested frequency, but with some terrible jitter: testing on my Uno I could see each level being held for *slightly* less than 5 µs. Then, from time to time, one level is held for ≈ 9 µs. Things could still be made faster by wrapping the `if` inside an infinite loop, instead of relying on the Arduino core to repeatedly call `loop()`:

```
void loop() {
    uint16_t last_toggle = 0;

    for (;;) {  // infinite loop
        if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
            PINB = _BV(PB5);             // invert pin state
            last_toggle += TOGGLE_TIME;
        }
    }
}

```

And now the signal looks still worse: with the program running faster, levels are held most of the time for only 3.5 µs, and then one out of every ≈ 4 levels is held for about 9 µs. The *average* frequency is probably right, but the jitter is absolutely awful, which is likely due to the 4 µs resolution of `micros()` noted by user Talk2.

The conclusion from these tests is: your only hope to get a somewhat clean signal at this frequency is to generate it in hardware, not in software. Choose one of the timers and have it generate the signal you want. I would avoid timer 0, as it is needed by the Arduino timing functions (`delay()`, `millis()`...). Here is how it can be done with timer 2:

```
void setup() {
    // The output will be on digital 3 = PD3 = OC2B.
    pinMode(3, OUTPUT);

    // Configure timer 2 for PWM @ 10 kHz on OC2B.
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS21);   // clock @ F_CPU / 8
    OCR2A  = 19;          // period = (19 + 1) * 8 CPU cycles
    OCR2B  = 9;           // HIGH for (9 + 1) * 8 CPU cycles
}

void loop() {
    // Nothing to do here, the signal is generated in hardware.
}

```

And now you have a perfectly clean 10 kHz square wave, while your program is free to do other stuff at the same time. Notice that the output is now on pin 3: the pin choice is limited when using the hardware-based approach. Notice also that you loose the PWM capability on pin 11, since it depends on timer 2.

# Answer
> 0 votes
First, be sure to use the "{}" in the menu to show your code in a code block

```
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT); }

// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delayMicroseconds(5); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delayMicroseconds(5); // wait for a second }

```

I think you could benefit from reading the Secrets of PWM

using a microsecond delay will only give you an approximate pwm signal.

> The Arduino's programming language makes PWM easy to use; simply call analogWrite(pin, dutyCycle), where dutyCycle is a value from 0 to 255, and pin is one of the PWM pins (3, 5, 6, 9, 10, or 11). The analogWrite function provides a simple interface to the hardware PWM, but doesn't provide any control over frequency. (Note that despite the function name, the output is a digital signal, often referred to as a square wave.)

---
Tags: usb
---


title: Use LDR with 220 ohm resistor

text:
# Question
Title: Use LDR with 220 ohm resistor
I have read many tutorials on LDR(Light dependent resistor) with Arduino which includes a 10 kilo ohm resistor but can i use it with 220 ohm resistor or even without resistor.

# Answer
> 2 votes
Unless properly filtered, an LDR has a spectral sensitivity very different from the human eye, which makes it unsuitable for any kind of photometric measurement. It is also typically very loosely specified, so you won't know the illuminance it receives better than a factor two even if you measure its resistance very accurately. Thus, if you really need accurate illuminance measurements like, e.g., for complying with legal requirements, then forget the LDR and get a real luxmeter with a calibration traceable to the SI lux standard.

Now, if you only want to tell apart substantially different illuminance levels, like sunny and cloudy, then the LDR is fine. And don't let Majenko scare you into believing you really need to know the resistance of your pullup: it doesn't really matter.

That being said, you will get the best sensitivity if your pullup has a resistance in the same range as the resistance of the LDR in the typical conditions you will use it. Thus, if your LDR is nominally 10 kΩ, I would avoid pulling up with 220 Ω, as the sensitivity would be very poor. A 10 kΩ pullup resistor would be ideal, but the internal pullup of the I/O pin (20 – 50 kΩ, 30 kΩ typical) should be fine.

Many tutorials on LDRs use the ADC reading to compute a resistance, for which you need to know the resistance of the pullup. If you want to follow this path, just assume a 30 kΩ pullup. All your numbers will be somewhat off, but that makes absolutely no difference, because you don't know how to relate the resistance to the illuminance anyway.

I would suggest you forget about computing the resistance. Just look at the raw ADC readings instead. Take some test readings in the typical conditions that are of interest to you: now you have a baseline to which you can compare further readings against. Keep in mind, though, that the ADC readings get *lower* as the illuminance gets *higher*. And beware that the resistance of the pullup, and probably that of the LDR also, can be sensitive to temperature variations. You may do a hairdryer test to check whether it gets really bad.

Example code? This one is pretty trivial:

```
/* Connect an LDR between A0 and GND. */

void setup() {
    pinMode(A0, INPUT_PULLUP);  // enable pullup for the LDR
    Serial.begin(9600);
}

void loop() {
    Serial.println(analogRead(A0));  // print out a reading
    delay(1000);                     // delay for one second
}

```

# Answer
> 0 votes
The simple fact is: you need a resistor with it. There's no getting away from that fact (short of building and using a constant-current source, but that's beyond the scope of this answer).

What value should the resistor be? Well, that depends on how sensitive or insensitive you want the LDR to be.

Yes, it will work with 220Ω, but will it give suitable results? Probably not. Ideally you want the resistor to be somewhere in the vicinity of the nominal resistance of the LDR - and that usually means 10s of KΩ.

As Edgar has mentioned, you can, at a pinch, use the internal pullup resistor of an IO pin instead of an external one (`pinMode(A0, INPUT_PULLUP)`), but the variability in the possible resistances that it might be make it pretty useless for anything more than "is it light or dark".

So you are best off getting a 10KΩ resistor where you then know that it is 10KΩ (or within a small percentage) and can calculate the LDR's resistance properly.

---
Tags: arduino-uno, resistor
---


title: Selection of presence sensor

text:
# Question
Title: Selection of presence sensor
For one of my university projects I need to detect the presence of a person in the shower. In order to do that what I have in mind is use a proximity sensor. If the target is in a distance range (let's say 20 to 50 cm) It will assume that the person is in the shower when the distance measure is no longer in this range then it will mean that the person left the shower. I need to detect all the time of the person in the shower (meaning when he/she gets in and then out). I have read a lot of info and forums to properly choose the type of sensor. However I still don't have a clear answer. About the Ultrasonic proximity sensors I know that they are cheap and more accurate by it can be affected by Temperature, humidity and some ambient noise, all of them which happen in a shower. The other option an Infrared one gets affected by lightning conditions and the surface of the target. The last option I checked is a PIR sensor I know it senses Temperature of the target, but I don't know if it will be affected by the running hot water and also is more expensive. In general, I don't know how the running hot water will affect the detection of the person in shower. Also,so again I don't know how this will work. Sorry for the huge amount of questions, I am a little bit confuse with all the factors to have in mind. I am hoping someone out there can help a lost newbie like me and give me a suggestion. Thanks a lot :)

# Answer
There is no one sensor that is perfect, but some are more reliable than others.

Yes, the temperature and humidity can play an important role in your sensing, and has to be taken into account. That's not to say that things like Ultrasound don't have a place in the scheme of things.

There's one word you need to think about here: Correlation.

If one single sensor isn't completely reliable then add a second that works in a different way. If both of them agree that there is someone in the shower (i.e., the sensors *correlate*) then the probability that there is actually someone in the shower is considerably higher.

The great thing about a shower is you are working in a defined enclosed space. That makes it much easier and there are plenty of sensors which, when combined with others, would be quite good at reliably sensing the presence of someone in that enclosed space.

Some ideas:

**Ultrasound above the person's head**

* Pros:
    + Simple to arrange.
    + Safe.
* Cons:
    + Can be fooled by the water from the shower head.
    + Steam isn't good for them.

**Infra-red distance**

* Pros:
    + Accurate
    + Can be sealed
* Cons:
    + Expensive
    + Harder to work with
    + Can be blocked by steam

**Horizontal infra-red beam**

* Pros:
    + Can be positioned outside the shower glass with a reflector inside
    + Safe
* Cons:
    + Small sensing area
    + Can be blocked by steam

**Pressure sensor**

* Pros:
    + People weigh more than water so is very reliable
    + Simple to interface
* Cons:
    + Hard to install safely
    + Needs to be completely waterproof and sealed.
    + Could be a shock hazard if not waterproof

You notice I haven't mentioned PIR. I'm not a fan of PIR for sensing the presence of humans. They work by detecting *moving* heat sources. If the person is moving (entering an area, walking round a room, etc) then they get detected. If the person stands still (as is often the case in a shower) it "forgets" they are there.

Of the choices above (and I am sure someone would come up with others) I would probably opt for the infra-red beam. Maybe split it into a V shape to cover more area - that is, the beam enters the side of the shower at an angle, strikes a reflector on the shower wall, and is reflected back at another angle. The detector is then placed away from the emitter. You could also have a second set to give better coverage.

Infra-red distance measuring in/on the ceiling could be used to improve correlation and thus the probability that there is actually someone there.

I'd stay away from pressure sensing unless you can get hold of a proper waterproof pressure sensing mat designed for in-shower use. Don't try and make one yourself, waterproofing isn't an easy task, especially when people stand on it all the time.
> 1 votes

---
Tags: sensors
---


title: How to simply close a tab?

text:
# Question
Title: How to simply close a tab?
How can one close a tab in the Arduino IDE? There is a Tab button (little triangle) with the Option "Delete"(kind of misleading term). There is no "Close" option. And the "Delete" option doesnt do the job for me either, because the tabs are write-protected, and I just get a prompt.

# Answer
> 5 votes
You cannot close a tab in the Arduino IDE. If a file exists in the sketch then it is there with a tab. Deleting a tab deletes the file.

In the Arduino IDE a tab is a file and a file is a tab. You can't remove one without removing the other.

You might like to check out my IDE, UECIDE, which deals with tabs in a more traditional manner.

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


title: What should I learn next in arduino?

text:
# Question
Title: What should I learn next in arduino?
This what I have learned :

```
digital inputs and outputs

Analog inputs and outputs

Line follower ir sensor

Pir sensor

Ultransonic sensor

Ir transmitter and reciever

Lcd

Key pad

Dc motor

Stepper motor

Servo motor

Interrupts

Timers

Watchdogs

 Arduino with raspberry pi

```

This topics a made with it some projects so the question is what is next to learn about arduino ? What should be my next steps ??

# Answer
You say you have learned these things but were you using a motor shield for the DC motor? How's about building your own H-bridge. And how many types of stepping motors do you now know how to control? What about micro stepping? And what about graphical LCDs. Do you know how to make custom characters?

As your list is hardware-centric, I would next task you to learn how to write in C++ and create a library for others to use. Learn what it means to abstract the hardware down to a few simple function calls. How to create a class which contains an Arduino library for, say, the graphical features of a particular LCD.
> 2 votes

# Answer
I would get myself familiar with low power, sleeping modes, running on batteries.

Also connect others devices using SPI and I2C to familiarize yourself.

Finally give a go on different communication methods... over serial, ethernet, wireless, can bus, etc. No much point in having stand-alone projects that are isolated or always connected to an USB port. IMO the fun begins when your projects start to talk to each other and to the Internet.

Cheers
> 1 votes

# Answer
**Combine**

I see a lot of loose "projects", but try to fit (as much as possible) into one single project. Make a line following robot, that balances, has WiFi communication and a display.

Putting all the different parts together may create whole new problems/difficulties.

**Stop using Arduino?**

Find another IDE, so it's easier to manage a lot more code. Learn how to set up a toolchain/compiler.

Try programming an ATMega328P without Arduino.

*Why?* Because it'll learn you how to other devices work, if you're comfortable programming an AVR without Arduino, it's just a little step to using PIC microcontrollers.

**Hardware**

Design yourself a PCB specific for the project you want to do.

**Work on "Professional skills"**

Try to make some actual designs, requirement analyses and make a report on the project. This way you can practice for school/future jobs' professional skills.

**So what project should you do?**

Something you would really like to do. It's as simple as that. Something of which you think is going to be a challenge (but not too challenging).
> 1 votes

# Answer
The Nrf24L01 is an inexpensive wireless transceiver with very good Arduino library support, and there are still library opportunities, like star and mesh interconnections. It also requires less overhead than WiFi and ethernet. If you're PhD material, you could implement the OSI stack.
> 0 votes

# Answer
Definitely try to make practical projects that make sense and are actually useful in real life. Automation projects for "smarter home" lets say really do come in handy and it is extremely satisfying when you use them. They don't have to be huge, just do something small that you find interesting. Documenting what you have done and keeping something like a report will help you big time in the future. I suggest you decide if you like C++ and if you do dig deeper into it.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: What will happen if I keep my arduino on for 24 hours?
Please tell me that if I keep my arduino uno on for 24 hours with a adapter, will it get harmed?

# Answer
I have several home-brUnos and a genuine Mega 2560 that are now, or have, run 24/7 for periods of weeks to months, powered by either a USB port or a USB-type wall charger. All of them supported (or still do) a string of 2 or 3 DS18b20 digital thermo sensors and a WiFi or Bluetooth radio. None of them slept during those jobs and they all still live and continue work as well as they always have.
> 2 votes

# Answer
I have a number of Arduinos running 24/7. Nothing bad has happened to them. I suggest if you are running them from a wall-wart style adapter that you choose one supplying voltage at the lower-end of the recommended range. That is, for a Uno for example, with a 7V adapter rather than a 12V one. The reason is that the extra voltage basically has to be thrown away by the voltage regulator as heat.

An adapter supplying 9V would be OK.

An alternative is to get one of those USB chargers that supply 5V (eg. for an iPhone), and use that by running a USB cable to the USB port of the Arduino. Then the voltage regulator doesn't have to do anything at all.
> 0 votes

# Answer
I also have a number of Arduinos running 24/7 and no problems what so ever so far. Just keep the input voltage \< 14-15v. because higher voltage = higher temperature (in this case). In case you need to reset your arduino in code due the long up time you can do that by connecting the reset pin to any output pin and supply logical 0 once every 24 hours for example.
> 0 votes

# Answer
It **won't be harmed**.

However, if the code crashes, it wont reset itself, so if the code crashes, the purpose of running you Arduino 24/7 will defeat itself.
> -1 votes

---
Tags: arduino-uno
---


# Question
Title: What type of hardware could make a ball tilt or roll?
I wanted to know what type of component or module I could use to make a hollow ball move. I have these hollow plastic balls (think empty easter eggs) that I was going to put a nano in and a sound detector and was just hoping to just get it to move. I prefer a sort of a tilt left and right effect, but if it just rolls randomly that would work as well.

I was thinking just a simple vibration, but it doesn't really shift the ball at all, so I'm at a loss without building something quite complex with magnets or something. Perhaps a motor stuck to the side?

# Answer
The ball moves are made by a simple physics principle called Conservation of Angular Momentum. The angular momentum is a property that has any object that rotates and is proportional to its mass and velocity. To make a ball move you should play with this momentum, using its simplest application, the mechanical gyroscope. The mechanical gyro is made of a heavy disc rotating at high speed, modulating its velocity you can change the momentum and create a force that will move your sphere.
> 1 votes

# Answer
Maybe some sort of bristlebot? Try a hexbug nano and see if it behaves acceptably. The key behind them is a vibrating motor on top of a biased bristle that turns the vibration into a biased motion.
> 0 votes

# Answer
Read up on Muscle Wire! I'm sure this will be the easiest most elegant solution. Basically apply a small voltage to a section of this wire in response to sound detection and it will deform, changing the centre of gravity of the ball at rest, making it move. Use two pieces and you will manage to get it to move or tilt in two directions!
> 0 votes

# Answer
Want to make a ball move? Maybe look at how sphero does it by looking at a tear down video. You have to use motors. The motor end has to be connected to a wheel which turns the outer shell. The centre which is not at all connected to the shell should be heavier than the shell.
> 0 votes

---
Tags: arduino-nano
---


title: Determine Object Heading

text:
# Question
Title: Determine Object Heading
Is there a sensor I could use which would let me know which direction an object is heading/facing? i.e. I have a servo that can rotate 0 to 180 degrees, and I have another sensor on a block. When I turn the block 45 degrees, I want the servo to also turn 45 degrees - I thought I could do this with a compass, but the varying magnetic fields make it impossible. Gyro/acc maybe? Except I don't know how to use that to solve this problem.

So in other words we need to know the block was rotated 45 degrees using a sensor on the block, which tells the servo to rotate 45 degrees.

# Answer
Use a gyro, it will give you the angle. Gyros are difficult to find spare, so you should buy an IMU like MPU6050 that contains also an accelerometer.
> 1 votes

---
Tags: arduino-uno, sensors, esp8266, servo
---