message:
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.

body: 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.


sender: user

sender: assistant

body:
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](http://oregonembedded.com/batterycalc.htm) 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.


body:
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).


message:
Triggering capacitive touch on a touch device

As you can see in the [video][1], 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.

  [1]: https://www.youtube.com/watch?v=JDgDMBquBw0

body:
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][1] 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".

  [1]: https://electronics.stackexchange.com/questions/60385/how-to-use-a-capacitive-touch-screen-without-a-human-hand


message:
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);

    }

body:
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?


message:
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][1] 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.

[1]: https://1drv.ms/b/s!AnWPsNx8qqvugs0YNoXsvMuq2orDBQ

body:
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:

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

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.

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


message:
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?

body:
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.


message:
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!! :)

body:
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][1].  Then explicitly state the number of characters to compare:

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

  [1]: http://linux.die.net/man/3/strncmp


message:
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**

[![transmitter pwm pins to arduino digital input][1]][1]

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

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

body:
`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).

<!-- language: lang-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);
    }


message:
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)

body:
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


message:
How to pass a static const (progmem) array to a function

I'm implementing a voice synthesizer chip. To build a phrase, I create a list of phonemes like this:

    static const uint8_t PROGMEM heybuddy[] = {
      pPA5, pHH1, pEY, pPA5,
      pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
    };

And to play them I do this:

     for (size_t i=0; i<sizeof(heybuddy); i++){
        say(pgm_read_byte(heybuddy+i));
     }

So what I'd like to do is create a function where I can just pass the array to a function that can take care of the loop and do some other maintenance stuff.

    //what I've tried:
    void sayPhrase(const uint8_t *phrase){
      int open = 0;
      for (size_t i=0; i<sizeof(*phrase); i++){

          if(pgm_read_byte(*phrase) != 4 && open == 0){
              Serial.println("mouth open");
              open = 1;
          } else if(pgm_read_byte(*phrase) == 4 && open == 1){
             Serial.println("mouth closed");
             open = 0;
          }
          say(pgm_read_byte(*phrase+i));
        }
    }

But when it comes to passing a static const I'm lost I've tried passing it as a reference with `*` but nothing I do seems to work - I just don't know the proper way to do this in C.

What I have compiles, but it seems to only get one phoneme and repeat it over and over. The rest are lost.

body:
The problem is, when you call `sizeof(*phrase)`, what is returned is 1, the size of the `uint8_t` array element, the result of your pointer de-reference. On the other hand, if you call `sizeof(phrase)` inside the function, you get the size of the pointer itself and not the size of the array, as you might expect. When you pass the array to the function via a pointer, the function has no idea if you passed the start of an array to it or merely a pointer to some `uint8_t` variable, so it can't know what the size is; context has been lost.

Instead, you should call `sizeof(phrase)` in the same scope where the array was declared and initialized and pass the result to the function, which can then use this value in the `for` loop.

    static const uint8_t PROGMEM heybuddy[] = {
      pPA5, pHH1, pEY, pPA5,
      pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
    };

    size_t SIZE = sizeof(heybuddy);  // this is ok since each element = 1 byte

    sayPhrase(phrase, SIZE);

The function definition should be:

    void sayPhrase(const uint8_t *phrase, size_t size){
      int open = 0;
      for (size_t i=0; i < size; i++){

          if(pgm_read_byte(phrase) != 4 && open == 0){
              Serial.println("mouth open");
              open = 1;
          } else if(pgm_read_byte(phrase) == 4 && open == 1){
             Serial.println("mouth closed");
             open = 0;
          }
          say(pgm_read_byte(phrase+i));
        }
    }


body:
I have some extensive examples of accessing PROGMEM [here](http://www.gammon.com.au/progmem).

I've adapted one of the examples to show how you might do something similar to what you want:

<!-- language: lang-c++ -->

    const int NUMBER_OF_ELEMENTS = 10;

    const char Message0000 [] PROGMEM = "Twas bryllyg, and ye slythy toves";
    const char Message0001 [] PROGMEM = "Did gyre and gymble";
    const char Message0002 [] PROGMEM = "in ye wabe:";
    const char Message0003 [] PROGMEM = "All mimsy were ye borogoves; And ye mome raths outgrabe.";
    const char Message0004 [] PROGMEM = "\"Beware the Jabberwock, my son! \n The jaws that bite, the claws that catch!";
    const char Message0005 [] PROGMEM = "Beware the Jubjub bird, and shun\n The frumious Bandersnatch!\"";
    const char Message0006 [] PROGMEM = "He took his ";
    const char Message0007 [] PROGMEM = "vorpal sword in hand:";
    const char Message0008 [] PROGMEM = "Long time the manxome foe he sought - ";
    const char Message0009 [] PROGMEM = "So rested he by the Tumtum tree, \n And stood awhile in thought.";

    const char * const messages[NUMBER_OF_ELEMENTS] PROGMEM =
       {
       Message0000,
       Message0001,
       Message0002,
       Message0003,
       Message0004,
       Message0005,
       Message0006,
       Message0007,
       Message0008,
       Message0009,
       };

    void sayPhrase (const char * const * message)
      {
      const char * ptr = reinterpret_cast<const char *>(pgm_read_ptr (message));  // pointer to message
      Serial.println(reinterpret_cast<const __FlashStringHelper *>(ptr));    // and print it
      } // end of sayPhrase

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
        sayPhrase (&messages [i]);

      }  // end of setup

    void loop () { }


body:
As others have pointed out, your problem is `sizeof`, which is calculated at compile time, not when the code is run.

You need to pass the size of the array to the function. This can be done in many ways, depending on what else you are doing.

In `c` the most common method is to use a null-terminated string, but I suspect this may not work.

You can store the size of each phrase in a separate array, and pass as a separate parameter or Pascal style as a count byte in the first element of the phrase.


body:
If you're not averse to a bit of C++:

    void sayPhrase(const uint8_t * phrase, size_t size)
    {
     bool open = false;
     for (size_t i = 0; i < size; ++i)
     {
      if(pgm_read_byte(phrase) != 4 && !open)
      {
       Serial.println("mouth open");
       open = true;
      }
      else if(pgm_read_byte(phrase) == 4 && open)
      {
       Serial.println("mouth closed");
       open = false;
      }
      say(pgm_read_byte(&phrase[i]));
     }
    }

    template< size_t size >
    void sayPhrase(const uint8_t (&phrase)[size])
    {
     sayPhrase(phrase, size);
    }

Which can then be called directly on the array:

    sayPhrase(heybuddy);

And the template will infer the array size and call the non-template function.


message:
cu port always busy on Mac

I'm going bonkers here. I'm using a Macbook Pro with Yosemite. Connected to the MKS Gen-2Z V1.1 reprap board (ATmega 2560).

The Arduino IDE only shows the cu port being available and not the tty.

Any attempts at opening the CU port show it as being busy. This is also true when I open the port using PronterFace (3d printer software). Yet, the PronterFace shows the tty port and gladly opens it and communicates. I downloaded Arduino 1.0.6 and the tty is available in the dropdown menu and it will open the port. But my 3D printer firmware will fail building on any Arduino IDEs prior to 1.6.0.

I found a few suggestions on creating a file "lock" in /var/ and then changing the r/w permissions. Also doing the same for /var/spool/uucp. Changing both of those permissions did nothing for me.

I may just have to build it and use AVRdude directly so I can use the tty port, but I have no idea why the cu would be busy all the time. Any suggestions?

Here's the Arduino output when I try to upload:

>avrdude: ser_open(): can't open device "/dev/cu.usbserial-AL00YS9R": Resource busy

    ioctl("TIOCMGET"): Inappropriate ioctl for device

    ioctl("TIOCMGET"): Inappropriate ioctl for device

    avrdude: ser_send(): write error: Bad file descriptor

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

body:
JRobert - I'll have to try the csrutil suggestion. The problem I see with that is the board I am trying to interface with has a genuine FTDI chip, the 232RL. The answer posted was to install a driver for a chinese USB chip.

Gerben - I do have a /dev/tty.usbserial-AL00YS9R. The Arduino IDE is only showing the cu ports.


body: Can't you see what's hooking the serial port with `sudo lsof -n | grep cuaU0` ? If so, `sudo kill -9 12345`, where 12345 is the offending PID. Your FTDI chip may need a driver, try `sudo dmesg` after pluggibg it in, or use systemprofiler.


message:
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?

body:
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][1]

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]: http://www.cplusplus.com/doc/tutorial/classes/


body:
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++:

<!-- language: lang-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.


message:
Is there any way I can connect the RAM of a computer to Arduino?

I was thinking about a way to reuse the RAM of my old computer on my Arduino board. I was thinking about some peojects using neural networks, and more RAM would let the Arduino use more neurons.

So that's my question, how could I do that? Maybe soldering some cables to Tx/Rx pins and creating and interface between the board and the memory?

body:
If you try hard enough it might work, but it will not be easy.

In general there are 2 types of RAM.  [Static][1] and [Dynamic][2].  You can cram a lot more memory into a Dynamic RAM chip so that is what is most likely in your computer. And probably what you are asking about in your question.

Dynamic memory needs to be [refreshed continuously][3].  Otherwise the data will be lost.  This is such a repetitive and time consuming process that special hardware is used to relieve the processor of this task.  In general, embedded processors such at the Atmel (used in most Arduinos) do not have such specialized hardware.

So it will be (very) difficult to use your computer memory in your Arduino.

That said, there are [some specialized RAM chips][4] that you can use with your Arduino.  But they likely do not look like the memory chips in your computer.

  [1]: https://en.wikipedia.org/wiki/Static_random-access_memory
  [2]: https://en.wikipedia.org/wiki/Dynamic_random-access_memory
  [3]: https://en.wikipedia.org/wiki/Dynamic_random-access_memory#Refresh_rate
  [4]: http://playground.arduino.cc/Main/SpiRAM


body:
No, you can't connect your normal desktop computer memory to your Arduino. For a number of reasons:

1. Computer memory (at least for the past 20 years) is DDR SDRAM. That's Synchronous Dynamic RAM. It requires very strict timing and synchronous (clock based) data transfers with clocks measured in the hundreds of MHz - something the Arduino cannot do.
2. You need lots and lots of I/O pins to interface with SDRAM. I mean, just look at all those pins - how would you connect all those up to a little Arduino?
3. Being DRAM you need to use quite a complex process to keep the data refreshed and stop the capacitance of each cell from draining away. Yes, that side of things is do-able, but not child's play.

The only way you will be able to interface DDR SDRAM with an Arduino is through some intermediate interfacing system that can do all the above for you. Your best candidate is to design an SPI to DDR conversion chip using an FPGA and Verilog or VHDL. That way you can communicate with the FPGA using SPI (or you could choose I2C if you like, or a simple 8-bit parallel protocol) and the FPGA then does all the grunt work that the Arduino isn't capable of.

However, while you're at it, you may as well put a CPU core in the FPGA (e.g., NIOS II or something) and do away with the Arduino altogether...


body:
I know this is old, but it comes up on Google so here I am.

Forget about connecting any kind of *modern* computer RAM to an Arduino. Period.

However, an old school SIMM from the 80's/early 90's is very much possible to use with some effort and they're cheap enough to buy on eBay. These are the ones you would have usually found on a 386/486 or early Pentium system.

Here is an example: http://dmitry.gr/?r=05.Projects&proj=07. Linux on 8bit

There are much easier and more cost-effective ways to add RAM to your 8-bit Arduino though. Look up SPI RAM. That's probably what you want. It's only a 4 pin connection, and numerous libraries already exist to interface with them.


message:
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][1].

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?

  [1]: https://github.com/chriscook8/esp-arduino-apboot/blob/master/ESP-wifiboot.ino

body:
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.


body:
`+=` 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 `/=`


body: 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.


message:
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?

body: 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.


body:
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.


body:
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.


message:
Why is there a need to ground a circuit?

Please tell me why I have to connect one of the wires of arduino gnd to the gnd of a relay or a bluetooth module?

body:
Electric circuits need to be closed. The hydraulic analogy might help you in this sense: suppose you have a garden fountain and want to recycle its water;  if you want water to *circulate* by means of a pump, you need a way to put the water back in the pump. That's what the ground connection is for.

Sometimes you have closed circuits using other wires, and a ground connection (or a shorter, direct ground connection) might be required to keep at bay the effect of EMI (electro-magnetic interference).
For example, this is the output of an Arduino Nano sensed by connecting only the tip of the oscillocope probe to pin 13.

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

And this is the same output when I connected the ground tip to Arduino's GND (actually to the USB frame):

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/B63cZ.jpg
  [2]: https://i.stack.imgur.com/vY0Ul.jpg


body:
If you are constructing a complex circuits or connecting many boards and sensors together, you really need to provide a common ground for all the devices.

The main reason is here we are dealing voltage and different circuits operate at different voltages. It is important to understand that voltage is the potential difference between two points in the circuit. This value is relative to the circuit itself since every circuit has its own ground (GND) pin. What this means is there is no absolute potential difference for a complex circuits. Hence, it is important to establish a common ground such that all potential difference can be measured from a common GND pin.

For instance, consider you have an arduino (operates at 5V) connected to motor controllers or relays (operates at 12V) and there are no common ground established between them. This will mess up the signals from arduino to motor controllers or relays. The output signals coming from the arduino may not be 5V but lower. Therefore, it is not detected by the motor controllers/relays.

I hope this helps.


message:
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 ??

body:
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.


body:
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


body: 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.


body:
**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).


body:
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.


message:
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.

body:
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.


message:
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

<!-- language: c -->

    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
    }

body:
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][1]

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.)

  [1]: https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM


body:
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

<!-- language-all: lang-c++ -->

    // 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.

[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[direct port access]: https://www.arduino.cc/en/Reference/PortManipulation


message:
Arduino yun is not creating it's wifi?

I have installed Arduino software into my PC and copied the bin files into the memory card that has to be fixed into Arduino yun.

After switching on the yun board it is not creating any Arduino yun wifi connection.

Can you help me to overcome this problem?
Thanks.

body:
If there is no code that enables the WiFi, it won't be enabled.

Here's the link:
https://www.arduino.cc/en/Guide/ArduinoYun#toc14


body:
Perhaps you need to reset wiffi. Press for 3 seconds. After this you must await for a while. Some leds will open and close. This process takes about 2 or 3 minutes. After this. Your white led will be flashing. That is all.
Have in mind some points:
First time you have to connect your yun by usb. Then you have to openIDE and choose IP PORT which will be showed(192.168....). Then go to your browser and type Ip and configurate your yun for wifi.


message:
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.

body:
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.


body:
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:

<!-- language: lang-c++ -->

    /* 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
    }


message:
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.

body:
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](http://uecide.org), which deals with tabs in a more traditional manner.


message:
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 :)

body:
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.


message:
Changing the tick time in FreeRTOS

I am trying to use FreeRTOS's vTaskDelay() function in order to periodically execute tasks.  The latest version of FreeRTOS came with the "tick" time set to 15 ms. Therefore, the smallest resolution I can delay for is 15 ms. I would like to lower this resolution to at least 1 ms.  Is it possible to configure FreeRTOS in this way?  I found this answer online : http://www.freertos.org/FreeRTOS_Support_Forum_Archive/November_2012/freertos_Problem_changing_Tick_time_from_1ms_to_10ms_6231539.html.

But for me, the configTICK_RATE_HZ is not defined and it seems to be using a watchdog timer to enforce the 15 ms resolution. I think the forums are referring to an earlier version.

body:
See the [configTICK_RATE_HZ][1] configuration option.
Also note it is better to specify times in milliseconds, rather than ticks, so you can change the tick frequency without effecting the timing (other than the resolution of the time).

The `pdMS_TO_TICKS()` macro can be used for that purpose, for example to create a delay of 100ms.

    const TickType_t xBlockTime = pdMS_TO_TICKS( 100 );
    vTaskDelay( xBlockTime );

  [1]: http://www.freertos.org/a00110.html#configTICK_RATE_HZ


message:
How do I communicate with a sensor via an Arduino's RX/TX ports?

I have a sensor that communicates via serial communication. [CTi Sensors TILT-05][1]. It transmits an ASCII string with data separated by commas. I want to be able to read the incoming ASCII data in the Arduino IDE's Serial Monitor in real time (the device is an accelerometer).

I am struggling to convey this in the code. Currently, I have the sensor's RX connected to an Arduino Uno's TX port (digital 1) and sensor TX-> Arduino RX (digital 0). The sensor is powered and grounded via the Arduino.

I have searched for serial communication methods but can't find any that seem to work. How can I receive and interpret the incoming data from the sensor?

[![Basic setup. Not complicated at all, just need some clarification.][2]][2]
[![Closer view of the connections.][3]][3]

  [1]: http://ctisensors.com/wp-content/uploads/2016/03/TILT-05-UserManual-01b.pdf
  [2]: https://i.stack.imgur.com/FIZ8K.jpg
  [3]: https://i.stack.imgur.com/rKT4n.jpg

body:
You don't mention the sensor brand or a datasheet so this will be a very general answer to the problem.

Firstly, how you have the sensor connected now should just spool info into the Serial monitor of the Arduino IDE without any code on the Arduino.

What are the data speed and the exact way the Serial comes out from the sensor?

If you want to interpret the data as it is coming through you should use Software Serial as you can't relay info to the PC with an Arduino's RX TX lines connected to something else.

What you can do is below(***Untested***):

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

    #include <SoftwareSerial.h>

    SoftwareSerial mySer(3, 4); //RX TX

    //these are char areay because its from Serial
    char accel[3] = {'0'};
    uint8_t place = 0;

    // array to print in sync with the accelerometer values array
    const char* SerialText[3] = {
       "\nX Axis: ",
       "\nY Axis: ",
       "\nZ Axis: ",
    };

    char inData = '0';
    char separator = ','; // separator you described

    void setup(){
    //set to the normal baud, mines for the example
         Serial.begin(9600);

         mySer.begin(9600);

    }//~ end setup

    void loop(){

        if(mySer.available()){

         inData = mySer.read(); // get the value at the instance of the serial data being there

            if(inData != separator){
              accel[place] = inData;
              Serial.print(SerialText[place]); // print the current values identifier
              Serial.print(accel[place]); // print value
              place++; // increment for the next time
         }
       }

    if(place >= 3) place = 0;
    }//~ end loop

The above gives this output at the moment, with an input of `$CSACC,-0156.4,-0226.3,+0981.2*49`

    X Axis: $
    Y Axis: C
    Z Axis: S
    X Axis: A
    Y Axis: C
    Z Axis: C
    X Axis:
    Y Axis: -
    Z Axis:
    X Axis: 0
    Y Axis: 1
    Z Axis: 5
    X Axis: 6
    Y Axis: .
    Z Axis: 4
    X Axis:
    Y Axis: -
    Z Axis:
    X Axis: 0
    Y Axis: 2
    Z Axis: 2
    X Axis: 6
    Y Axis: .
    Z Axis: 3
    X Axis: +
    Y Axis: 0
    Z Axis: 9
    X Axis: 8
    Y Axis: 1
    Z Axis: .
    X Axis: 2
    Y Axis: *
    Z Axis: 4
    X Axis: 9
    Y Axis:
    Z Axis:
    X Axis:

The code doesn't filter this the way it should but is a stepping stone. I will update it to do it properly when I have a chance.


body:
With RSM's help I've managed to get the sensor reading into the serial monitor semi-reliably. I have yet to solder the headers onto the sensor yet and am just doing prototyping (basically just me pushing a wire against the sensor output hole) which is unreliable. I believe once I get some headers soldered on the output will be much more reliable. For those searching, this code worked for me.

Digital pins 3/4 function as your RX/TX pins respectively. Connect the TX of your sensor to the RX (3) of the Arduino and likewise for the TX. I used a baud rate of 115200 but you can change it to whatever works in the code. This is simply a simplification of RSM's code in his previous answer and all credit/kudos goes to him.

    #include <SoftwareSerial.h>

    SoftwareSerial mySer(3, 4);

    char inData = '0';

    void setup(){
         Serial.begin(115200);
          mySer.begin(115200);
    }

    void loop(){
        if(mySer.available()){
         inData = mySer.read();
         Serial.print(inData);
      }
    }


message:
Can I connect and control 12 Arduino's over USB/serial to my laptop?

I have 12 arduinos, each of them controlling some simple hardware peripherals. I want to interact with all of them over 1 USB connection to my laptop, where I have a python program communicating over serial.

The following seems like it could work: https://www.amazon.ca/Satechi-Power-Adapter-Control-Switches/dp/B0051PGX2I

Are there any electrical/other considerations to take into account for why this would/wouldn't work?

body:
From a technical standpoint, USB can host up to 127 devices, so 12 Arduino boards is certainly not pushing the limit. Having 12 serial ports shouldn't be an issue in either Linux or Windows.

From a practical standpoint, you will have to find a powered USB hub which can support that many devices, or plug multiple hubs together. I'll leave that up to you as shopping recommendations are off topic.

In terms of the hub you use, you need to make sure you don't exceed its maximum current rating. The Arduino boards draw typically around 60-100mA alone. 12 of those and you will need at least 1.2A rating. The hub you mentioned says that it cannot exceed 2A. Depending on what other circuitry you attach to your Arduino boards you may need an external power supply for the boards.


message:
How accurate is arduino time keeping?

I want to use my arduino to turn a light off for 16 hours and on for 8 hours. I know the general code, just using delays and the relay shield code as well. I want to know how accurate this will be? ( I tagged uno and leonardo, as I have access to both)

body:
Not very.

For that kind of period of timing you are far better off using a Real Time Clock (RTC) module.


body:
There are multiple versions and "clones" of the Arduino, and each one will probably use different components. The time you refer, in this case "millis()" I believe, is maintained from a timer interrupt, which is derived from the main clock (normally 16Mhz).

The main clock on your board might be generated by a ceramic resonator, which is not very accurate: around 0.5%-1% error. It also might be from good quartz crystal, with up to 0.001% accuracy. Those variations on the frequency source will produce some drift over time... Like your watch needs to be readjusted from time to time.

Another factor that affects accuracy, including for RTCs using a 32.768KHz crystal, is the temperature. Here an Application Note on this: [http://www.st.com/content/ccc/resource/technical/document/application_note/55/e2/3d/2a/87/ab/4d/e1/CD00232494.pdf/files/CD00232494.pdf/jcr:content/translations/en.CD00232494.pdf][1]

Your application might not require too much precision, and you could simply write a sketch to print the time every second on the serial... let it run from one hour, one day, and check how much drift you're getting. After that will be easy to estimate how much drift you'll have a after a month.

  [1]: http://www.st.com/content/ccc/resource/technical/document/application_note/55/e2/3d/2a/87/ab/4d/e1/CD00232494.pdf/files/CD00232494.pdf/jcr:content/translations/en.CD00232494.pdf


body:
By definition, the Arduino is as accurate as it's crystal clock/resonator.

This clock runs at approximately 16mhz for an Uno.

The Arduino's internal time is just a count of how many times this crystal has vibrated.

**READ THIS!** - these next two paragraph are apparently **incorrect**. See Nick Gammon's comment below.
> The crystal in question is approximately like this one: https://www.sparkfun.com/products/536 - this one from SparkFun is accurate to 50 ppm - that's parts per million. So, if your Arduino has that EXACT crystal, it may lose or gain 50 parts per million - in a million seconds, it would count somewhere between 999,950 and 1,000,050 seconds. This would mean you gain/lose less than 4.3 seconds per day, or 2 minutes per month.
> If you find the crystal on your board, google the code (probably something like 16.000N, for the Sparkfun one), which should tell you exactly what the accuracy is for that chip. Note that, if you can find the datasheet, it should tell you the accuracy, at particular temperatures - as the temperature goes up and down, the error will change too.

Remember also that an Arduino's clock is in volatile memory - that is, if you power down the Arduino, and power it back up, it has no idea what time it is - you would need to set the clock again, either by connecting it to a PC, network, or via buttons/display on your project.

There are a number of alternatives, depending on your need, to work around this: you can get the data from LAN or WIFI, if your project has that, or you can use a RTC module - you need to set this to the correct time once, then it will remember after that.

Alternatively, you can use a light-dependent resistor (aka photoresistor), and trigger automatically when it gets dark. This may trigger when it gets dark for some other reason, e.g. a storm, which may or may not be an advantage.


body:
I made a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) in August 2013. It uses a RTC chip (DS1307) which you can buy on eBay for $1 if not less. It has a battery backup (lithium cell).

I don't recall ever resetting the clock on it. It is now about 3 years later, and it is running about 11 minutes slow. This would be an acceptable error for something like turning garden lights on and off. Even for taking the temperature, a few minutes out when logging a reading is probably not going to matter.

Using the internal clock probably won't be as accurate, but could be OK in this case. I suggest you follow Chris Stratton's suggestion and code so that errors are not cumulative. For example, if you delay for an hour, and then do something, make sure that the "do something" isn't added to the next delay time.

If you want super accuracy (sounds like you don't) then connecting up a GPS module lets you query the exact time from the satellite, which could cut the error down to negligible amounts. Those GPS modules however aren't cheap.

---

Something to consider if you try to make do with the internal clock is: what happens if the power goes off? Then it loses track of when to turn the lights on and off. A clock chip however (usually) has a battery backup, and will "know the time" once the power comes back on.


body:
I think that RTC modules and real time clock chips have some sort of "mistake" said that, it CAN max. delay for fast forward for max. 6 seconds per month. Something as this, I've read year or so ago, when I was dealing with some sort of doors locking mechanism.

But for app. 8 hours, there's an arduino RTC module more than enough, I'd say. I assume, that seconds doesn't matter.


body:
Just because it's always an option...  I'm usually connecting my Arduinos to the Internet one way or another, so I just get the time from NTP servers once every day or so using UDP to keep the clock accurate, or accurate enough.

The advantage is that, even if power is lost, it's relatively easy to ask Arduino to get the time while booting up.  Then it always knows, and is always on time.

Happy to share fave code, but I found mine in UDP library examples and have adapted it to my own needs.


body:
>  I want to know how accurate this will be?

accuracy is a function of coding and hardware. with good coding, you can make it as accurate as your hardware is capable of.

I experimented with a tco-919 high accuracy oscillator (19.2Mhz), in an unairconditioned environment, no meaningful timing drift after a month.

So if you really want accuracy, go with a good oscillator.

if you just care about reasonable accuracy (1%?), the internal oscillator will do.


message:
Saving library example sketch getting error "you cannot save a sketch into a folder inside itself.."

I'm writing a library, and that library .cpp/.h code is in devel/arduino/libraries/LightBrightLib/.  I have test code that calls that library, and an example program using the library.  Right now they're in /devel/arduino/lightbright/LightBrightMain/ and /devel/arduino/lightbright/LightBrightLibTest/.

I see most libraries have an examples directory inside the library, so I tried moving mine to /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/ and /devel/arduino/libraries/LightBrightLib/examples/LightBrightLibTest/

When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/, it says "You cannot save a sketch into a folder inside itself. This would go on forever.".  And of course it won't let me select the examples directory or any other directory above it.

How do other library makers do this?  Maybe they don't use the IDE, or they copy it in outside the IDE, or use symlinks?
What does the IDE think it's doing and why is it fighting putting the file where it already is?

NOTE: This is not a file permission problem as I own all files

body:
What I normally do is make the examples in their own folders (ie. inside the sketchbook folder). Then when they are tested I just use the file system to move the folders into the "examples" folder under the library.

> When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/,

The IDE makes the folder, so you would (if this works at all) save `LightBrightMain` into the `examples` folder. Don't make a folder of the same name as the sketch. The IDE does that.


message:
Arduino Robot. a function-definition is not allowed here before '{' token

The code is very messy. We have an L293D circuit which has two enable pins always on. We also have an LDR light sensor with two light resistors, one on the left and one on the right.

We are trying to make a line following robot

We are ambitious high school students.

<!-- language: lang-c++ -->

    // Use this code to test your motor with the Arduino board:

    // if you need PWM, just use the PWM outputs on the Arduino
    // and instead of digitalWrite, you should use the digitalWrite command

    // --------------------------------------------------------------------------- Setup
    void setup() {
    {Serial.begin(9600);

    // --------------------------------------------------------------------------- Motors
    int motor_left[] = {2, 7};
    int motor_right[] = {10, 15};
    int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
    int LDRValue = 0;      //that’s a variable to store LDR values
    int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
    int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
    int LDR2Value = 0;      //that’s a variable to store LDR values
    int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
    int i;
    for(i = 0; i < 2; i++){
    pinMode(motor_left[i], OUTPUT);
    pinMode(motor_right[i], OUTPUT);
    LDRValue = analogRead(LDR);
        Serial.println(LDRValue);

        if (LDRValue < light_sensitivity);
        Serial.println("wat");

    }
    // --------------------------------------------------------------------------- Loop

    // --------------------------------------------------------------------------- Drive

    void motor_stop(){
    digitalWrite(motor_left[0], LOW);
    digitalWrite(motor_left[1], LOW);

    digitalWrite(motor_right[0], LOW);
    digitalWrite(motor_right[1], LOW);
    delay(25);
    }

    void drive_forward(){
    digitalWrite(motor_left[0], HIGH);
    digitalWrite(motor_left[1], LOW);

    digitalWrite(motor_right[0], HIGH);
    digitalWrite(motor_right[1], LOW);
    }

    void drive_backward(){
    digitalWrite(motor_left[0], LOW);
    digitalWrite(motor_left[1], HIGH);

    digitalWrite(motor_right[0], LOW);
    digitalWrite(motor_right[1], HIGH);
    }

    void turn_left(){
    digitalWrite(motor_left[0], LOW);
    digitalWrite(motor_left[1], HIGH);

    digitalWrite(motor_right[0], HIGH);
    digitalWrite(motor_right[1], LOW);
    }

    void turn_right(){
    digitalWrite(motor_left[0], HIGH);
    digitalWrite(motor_left[1], LOW);

    digitalWrite(motor_right[0], LOW);
    digitalWrite(motor_right[1], HIGH);
    }
    void loop() {
    drive_forward();
    delay(1000);
    motor_stop();
    Serial.println("1");

    drive_backward();
    delay(1000);
    motor_stop();
    Serial.println("2");

    turn_left();
    delay(1000);
    motor_stop();
    Serial.println("3");

    turn_right();
    delay(1000);
    motor_stop();
    Serial.println("4");

    motor_stop();
    delay(1000);
    motor_stop();
    Serial.println("5");
    }

body:
You need to look more closely at your braces. Use the auto-format tool (Ctrl+T) to help you. For example:

<!-- language: lang-c++ -->

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

    // --------------------------------------------------------------------------- Motors
    int motor_left[] = {2, 7};
    int motor_right[] = {10, 15};
    int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
    int LDRValue = 0;      //that’s a variable to store LDR values
    int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
    int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
    int LDR2Value = 0;      //that’s a variable to store LDR values
    int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
    int i;
    for(i = 0; i < 2; i++){
    pinMode(motor_left[i], OUTPUT);
    pinMode(motor_right[i], OUTPUT);
    LDRValue = analogRead(LDR);
        Serial.println(LDRValue);

        if (LDRValue < light_sensitivity);
        Serial.println("wat");

    }   // <------------------------------------ HERE

    // --------------------------------------------------------------------------- Loop

    // --------------------------------------------------------------------------- Drive

    void motor_stop(){

Where I marked "HERE" you are closing the `for` loop but you should also be closing `setup`.

You also have two opening braces here:

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

Proper indentation is **very helpful** for sorting out these sorts of issues.


message:
Clearing EEPROM

I'm trying to clear my EEPROM and am using this code:

    #include <EEPROM.h>
    void setup()
    {
    // write a 0 to all 4096 bytes of the EEPROM
    for (int i = 0; i < 4096; i++)
    EEPROM.write(i, 0);

    delay(9999999);
    }

    void loop()
    {
    }

I don't see a problem with it but it is ineffective.  Am I missing something?

body:
Thank you all for helping me out.  This is what I ended up using (ESP8266 1.0 12E with Arduino IDE):

    #include <EEPROM.h>
    #include <ESP8266WiFi.h>

    void setup()
    {
      Serial.begin(115200);
      EEPROM.begin(512);
      delay(5000);
      Serial.println("clearing EEPROM...");
      // write a 0 to first 1000 bytes of the EEPROM
      for (int i = 0; i < 1000; ++i) {
        EEPROM.write(i, -1);
     }
      EEPROM.commit();
      delay(5000);
      Serial.println("Reading EEPROM ssid");
      String esid;
      for (int i = 0; i < 64; ++i)
      {
        esid += char(EEPROM.read(i));
      }
      Serial.print("SSID: ");
      Serial.println(esid);
      Serial.println("Reading EEPROM pass");
      String epass = "";
      for (int i = 64; i < 128; ++i)
      {
        epass += char(EEPROM.read(i));
      }
      Serial.print("PASS: ");
      Serial.println(epass);
    }

    void loop()
    {
    }

It's probably longer than it has to be but I pulled stuff from other sketches I've worked on and prioritize function over form.  This writes a "-1" to the first 1000 bytes and then prints the first 128 bytes.  Since I am only concerned about the first 50 bytes or so this was sufficient for my needs.


body:
The tutorial [here][1] is very clear about how to clear the contents of the Atmel's EEPROM.  I only see 2 major difference.  The tutorial finds the size of the EEPROM through a function call.  Probably much safer.  And there is no call to a delay() function.

The tutorial does include lighting up an LED when finished.  And @Edgar Bonet is correct that erasing an EEPROM (altering each [floating gate][2] with in the chip) does take time.  And you have no way to known when the EEPROM clearing is finished in your code.

It is possible you are forcing your code to stop before it is finished.  In which case it would appear the EEPROM is not completely cleared.

  [1]: https://www.arduino.cc/en/Tutorial/EEPROMClear
  [2]: https://en.wikipedia.org/wiki/Floating-gate_MOSFET


message:
Wire.h not found!

Here's the code that's making this error:

    #include "Wire.h"

Here's the error:

    fatal error: Wire.h: No such file or directory
     #include "Wire.h"
                      ^
    compilation terminated.
    Error compiling.
I also can't include any file from my `Arduino\libraries` folder. I tried to reinstall the IDE several times in different places and nothing happened. Why is this happening?

EDIT: after some time I discovered that this error occurs in header files only, not in sketches!

body: First go to your library folder and check whether u included that Wire.h header file or not.If not then first include that file then problem will get solved automatically.


body:
Use `#include <Wire.h>`

Including files in double quotes (") will point to headers in current working directory first.

Edit: ... and there is nothing wrong with copying headers to CWD if you are modifying them, but that's probably not what you want.


body:
I had a similar issue and found this question. However, the solution for me is different.

I already had `#include <Wire.h>`, nevertheless the compiler told me it's missing. It turned out, I had selected a wrong board from a previous project. Needed to change to "Arduino Uno".